#!/usr/bin/env python3
import difflib,hashlib,json,pathlib,subprocess
here=pathlib.Path(__file__).resolve().parent;business=here.parents[4]/'zhctproject'/'store';rel='application/api/service/Card.php'
original=(business/rel).read_bytes();candidate=(here/'source'/rel).read_bytes()
frozen={s.split(None,1)[1]:s.split(None,1)[0] for s in (here/'SOURCE_SHA256.txt').read_text().splitlines()}
assert hashlib.sha256(original).hexdigest()==frozen[rel],'Main source drift'
tests={}
for name,root,want in [('original',business,1),('candidate',here/'source',0)]:
    p=subprocess.run(['/opt/homebrew/Cellar/php@7.4/7.4.33_13/bin/php',str(here/'CardResponseContractTest.php'),str(root)],capture_output=True,text=True)
    assert p.returncode==want
    tests[name]={'exit_code':p.returncode,'result':json.loads(p.stdout)}
(here/'card-proposed.patch').write_text(''.join(difflib.unified_diff(original.decode().splitlines(True),candidate.decode().splitlines(True),fromfile='a/'+rel,tofile='b/'+rel)))
result={'source':rel,'original_sha256':hashlib.sha256(original).hexdigest(),'candidate_sha256':hashlib.sha256(candidate).hexdigest(),'tests':tests,'business_source_writes':0,'database_operations':0}
(here/'CARD_TDD.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result))
