import difflib, hashlib, json, os, subprocess
from pathlib import Path

here = Path(__file__).resolve().parent
main = here.parents[4] / 'zhctproject/store/application/p/logic'
candidate = here / 'private-evidence/status-candidate'
candidate.mkdir(mode=0o700, exist_ok=True)
patches = []
specs = [
    ('NutritionTime.php', "$ret = $this->model->modify($params['uuid'], ['status'=>$params['status']]);", """if (ltrim((string)config('database.type'), '\\\\') === \\app\\cores\\database\\Dm::class
                && in_array($params['status'], [0, 1, '0', '1'], true)) {
                $ret = $this->model->modifyByWhere(
                    ['uuid' => $params['uuid'], 'status' => ['<>', $params['status']]],
                    ['status' => $params['status']]
                );
            } else {
                $ret = $this->model->modify($params['uuid'], ['status'=>$params['status']]);
            }"""),
    ('Nutrition.php', "$ret = $this->modelSet->modify($uuid, ['status'=>$status]);", """if (ltrim((string)config('database.type'), '\\\\') === \\app\\cores\\database\\Dm::class
                && in_array($status, [0, 1, '0', '1'], true)) {
                $ret = $this->modelSet->modifyByWhere(
                    ['uuid' => $uuid, 'status' => ['<>', $status]],
                    ['status' => $status]
                );
            } else {
                $ret = $this->modelSet->modify($uuid, ['status'=>$status]);
            }"""),
]
sha = {}
for filename, old, new in specs:
    raw = (main / filename).read_text()
    assert raw.count(old) == 1
    fixed = raw.replace(old, new)
    output = candidate / filename
    output.write_text(fixed)
    os.chmod(output, 0o600)
    patches.extend(difflib.unified_diff(raw.splitlines(keepends=True), fixed.splitlines(keepends=True), fromfile='a/application/p/logic/' + filename, tofile='b/application/p/logic/' + filename))
    sha[filename] = {'original': hashlib.sha256(raw.encode()).hexdigest(), 'candidate': hashlib.sha256(fixed.encode()).hexdigest()}
(here / 'status-fix.patch').write_text(''.join(patches))
container_here = '/workspace/zhct/' + str(here.relative_to(here.parents[4]))
for label, source, expected in [('red', '/workspace/zhct/zhctproject/store/application/p/logic', 1), ('green', container_here + '/private-evidence/status-candidate', 0)]:
    result = subprocess.run(['docker','exec','zhctapp_v2_0','/usr/local/php7.3/bin/php',container_here+'/TimeSetStatusContract.check.php',source],capture_output=True,text=True)
    assert result.returncode == expected, (label, result.stderr, result.stdout)
    report = json.loads(result.stdout)
    (here / 'private-evidence' / ('status-test-' + label + '.json')).write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
    os.chmod(here / 'private-evidence' / ('status-test-' + label + '.json'),0o600)
    sha[label] = {'assertions': report['assertions'], 'failures': report['failures']}
(here / 'status-candidate-summary.json').write_text(json.dumps(sha,indent=2)+'\n')
print(json.dumps(sha))
