#!/usr/bin/env python3
import difflib
import hashlib
import json
import pathlib
import subprocess

here=pathlib.Path(__file__).resolve().parent
business=here.parents[4]/'zhctproject'/'store'
frozen={line.split(None,1)[1]:line.split(None,1)[0] for line in (here/'SOURCE_SHA256.txt').read_text().splitlines()}
files=['application/p/logic/Equipment.php','application/m/logic/Dishes.php']
patch=[]
sha={}
for f in files:
    original=(business/f).read_bytes()
    candidate=(here/'source'/f).read_bytes()
    assert hashlib.sha256(original).hexdigest()==frozen[f], 'Main source changed: '+f
    patch.extend(difflib.unified_diff(original.decode().splitlines(True),candidate.decode().splitlines(True),fromfile='a/'+f,tofile='b/'+f))
    sha[f]={'original':hashlib.sha256(original).hexdigest(),'candidate':hashlib.sha256(candidate).hexdigest()}
(here/'proposed.patch').write_text(''.join(patch))
php='/opt/homebrew/Cellar/php@7.4/7.4.33_13/bin/php'
results={}
for test in ['ResponseContractTest.php','VersionCodeDomainContractTest.php']:
    results[test]={}
    for name,root,expected in [('original',business,1),('candidate',here/'source',0)]:
        p=subprocess.run([php,str(here/test),str(root)],capture_output=True,text=True)
        assert p.returncode==expected
        results[test][name]={'exit_code':p.returncode,'output':json.loads(p.stdout)}
(here/'CANDIDATE_TDD.json').write_text(json.dumps({'source_sha256':sha,'tests':results,'main_business_writes':0},indent=2)+'\n')
print(json.dumps({'patch_files':len(files),'candidate_assertions':sum(v['candidate']['output']['assertions'] for v in results.values())}))
