from pathlib import Path
import subprocess, shutil, os, json, hashlib, sys
ROOT=Path(__file__).resolve().parent
WS=ROOT/'workspace'; EVID=ROOT/'evidence'

def run(args,cwd=WS,env=None,check=True):
    return subprocess.run(args,cwd=cwd,text=True,capture_output=True,env=env,check=check)

def write(rel,text):
    p=WS/rel; p.parent.mkdir(parents=True,exist_ok=True); p.write_text(text,encoding='utf-8',newline='\n')

def shafile(p): return hashlib.sha256(p.read_bytes()).hexdigest()

def git_env(ts):
    e=os.environ.copy(); e['GIT_AUTHOR_DATE']=ts; e['GIT_COMMITTER_DATE']=ts; return e

if WS.exists(): shutil.rmtree(WS)
if EVID.exists(): shutil.rmtree(EVID)
WS.mkdir(); EVID.mkdir()
run(['git','init','-b','main'])
run(['git','config','user.name','MAKNOW Fixture'])
run(['git','config','user.email','fixture@example.invalid'])
write('README.md','# Coupon Audit Fixture\n\nStatus: implementation in progress.\n')
write('app/coupon.py','''def coupon_is_valid(expires_day, today_day):\n    return expires_day >= today_day\n\ndef apply_coupon(amount, percent, expires_day, today_day):\n    if not coupon_is_valid(expires_day, today_day):\n        return amount\n    return round(amount * (1 - percent / 100), 2)\n''')
write('app/audit.py','''def audit_event(coupon_code, accepted):\n    return {"event": "coupon_checked", "accepted": bool(accepted)}\n''')
write('tests/current_checks.py','''from pathlib import Path\nimport importlib.util\nROOT=Path(__file__).resolve().parents[1]\n\ndef load(name,path):\n    spec=importlib.util.spec_from_file_location(name,ROOT/path); m=importlib.util.module_from_spec(spec); spec.loader.exec_module(m); return m\n\ndef main():\n    coupon=load("coupon",Path("app/coupon.py")); audit=load("audit",Path("app/audit.py"))\n    assert coupon.apply_coupon(100,10,10,9)==90.0\n    assert coupon.apply_coupon(100,10,8,9)==100\n    e=audit.audit_event("SAVE10",True); assert e["event"]=="coupon_checked" and e["accepted"] is True\n    print("CURRENT_CHECKS_PASS")\nif __name__=="__main__": main()\n''')
run(['git','add','.'])
run(['git','commit','-m','Initialize coupon audit fixture'],env=git_env('2026-09-01T09:00:00+00:00'))
base=run(['git','rev-parse','HEAD']).stdout.strip()
run(['git','checkout','-b','feature/coupon-audit'])
write('README.md','# Coupon Audit Fixture\n\nStatus: COMPLETE — coupon audit change implemented and checked.\n')
write('app/audit.py','''def audit_event(coupon_code, accepted):\n    return {"event": "coupon_checked", "accepted": bool(accepted), "coupon": coupon_code}\n''')
run(['git','add','README.md','app/audit.py'])
run(['git','commit','-m','Implement coupon audit change'],env=git_env('2026-09-02T10:00:00+00:00'))
head=run(['git','rev-parse','HEAD']).stdout.strip()
write('app/audit.py','''def audit_event(coupon_code, accepted):\n    return {\n        "event": "coupon_checked",\n        "accepted": bool(accepted),\n        "coupon": coupon_code,\n        "schema": "audit-v2",\n    }\n''')
run(['git','add','app/audit.py'])
# Prior verification is generated now, before the later coupon fix.
report={'report_id':'VERIFY-COUPON-27','generated_at':'2026-09-02T10:15:00Z','head_oid':head,'result':'PASS','covered_files':{'app/audit.py':shafile(WS/'app/audit.py'),'app/coupon.py':shafile(WS/'app/coupon.py')},'scope':'local synthetic checks only; no deployment/release claim'}
(EVID/'prior_verification.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
write('app/coupon.py','''def coupon_is_valid(expires_day, today_day):\n    return expires_day > today_day\n\ndef apply_coupon(amount, percent, expires_day, today_day):\n    if not coupon_is_valid(expires_day, today_day):\n        return amount\n    return round(amount * (1 - percent / 100), 2)\n''')
write('notes/scratch.txt','Personal scratch: compare terminal color themes later.\n')
meta={'fixture':'FND007-LAB1','known_base_commit':base,'created_branch':'feature/coupon-audit','prior_report':'evidence/prior_verification.json'}
(ROOT/'fixture_metadata.json').write_text(json.dumps(meta,indent=2)+'\n',encoding='utf-8')
print('FND007_FIXTURE_READY')
print('workspace=',WS)
