#!/usr/bin/env python3
import difflib, hashlib, json, pathlib, subprocess
here=pathlib.Path(__file__).resolve().parent
business=here.parents[4]/'zhctproject'/'store'
frozen={s.split(None,1)[1]:s.split(None,1)[0] for s in (here/'SOURCE_SHA256.txt').read_text().splitlines()}
patch=[];sha={}
for rel in ['application/p/logic/MealOrder.php','application/p/logic/Api.php']:
    old=(business/rel).read_bytes();new=(here/'source'/rel).read_bytes()
    assert hashlib.sha256(old).hexdigest()==frozen[rel], 'Main source drift '+rel
    patch.extend(difflib.unified_diff(old.decode().splitlines(True),new.decode().splitlines(True),fromfile='a/'+rel,tofile='b/'+rel))
    sha[rel]={'original':hashlib.sha256(old).hexdigest(),'candidate':hashlib.sha256(new).hexdigest()}
tests={}
for label,root,wanted in [('original',business,1),('candidate',here/'source',0)]:
    result=subprocess.run(['/opt/homebrew/Cellar/php@7.4/7.4.33_13/bin/php',str(here/'ResponseContractTest.php'),str(root)],capture_output=True,text=True)
    assert result.returncode==wanted
    tests[label]={'exit_code':result.returncode,'result':json.loads(result.stdout)}
(here/'proposed.patch').write_text(''.join(patch))
(here/'CANDIDATE_TDD.json').write_text(json.dumps({'source_sha256':sha,'tests':tests,'main_business_writes':0,'db_operations':0},indent=2)+'\n')
print(json.dumps({'source_sha256':sha,'candidate_assertions':tests['candidate']['result']['assertions']}))
