#!/usr/bin/env python3
from __future__ import annotations
import csv, sys
from pathlib import Path

KEY_ADDRS = {
    0x000005CD: "0x05CD", 0x0000D95C: "0xD95C", 0x0000071E: "0x071E", 0x00000722: "0x0722",
    0x0000077C: "0x077C", 0x0000077D: "0x077D", 0x0000077E: "0x077E", 0x0000077F: "0x077F",
    0x0003E7BA: "0x8003E7BA", 0x0003E7BB: "0x8003E7BB", 0x0003E7BC: "0x8003E7BC",
    0x0003E7BD: "0x8003E7BD", 0x0003E7BE: "0x8003E7BE", 0x0003E7BF: "0x8003E7BF",
    0x0003E7DC: "0x8003E7DC", 0x0003E7DE: "0x8003E7DE", 0x0003E804: "0x8003E804", 0x0003E80C: "0x8003E80C",
}
KEY_PCS = {p.lower(): desc for p, desc in {
    "0x9001D086": "writes low 0x071E = 02",
    "0x9001D090": "writes high 0x8003E7BA = 01",
    "0x900396FD": "reads high 0x8003E7BB",
    "0x9003971A": "reads high 0x8003E7BC word",
    "0x90039767": "reads high 0x8003E7BB later",
    "0x90039778": "reads high 0x8003E7BC later",
    "0x9001EF26": "checks 0x8003E7DE latch",
    "0x9001EF60": "writes 0x8003E7DE latch",
    "0x90021696": "clears 0x05CD side-effect",
    "0x9001EF66": "clears 0x077C side-effect",
}.items()}

def main(argv):
    if len(argv) < 2:
        print("usage: python analyze_gdr8050l_v105_real_auth_flag.py TRACE.csv")
        return 2
    src = Path(argv[1])
    rows=[]; hit=set(); last={}
    with src.open(newline='', encoding='utf-8', errors='replace') as f:
        for r in csv.DictReader(f):
            pc=(r.get('pc') or '').lower()
            if r.get('event')=='break' and pc in KEY_PCS: hit.add(pc)
            addr_s=r.get('addr_physical') or r.get('addr') or ''
            try: addr=int(addr_s,16) if addr_s else None
            except Exception: addr=None
            if addr in KEY_ADDRS:
                r['addr_label']=KEY_ADDRS[addr]; rows.append(r)
                if r.get('event') in ('watch_write','synthetic_write'):
                    last[KEY_ADDRS[addr]]=r
    out_events=src.with_name(src.stem+'_authflag_events.csv')
    if rows:
        fields=list(rows[0].keys())
        with out_events.open('w',newline='',encoding='utf-8') as f:
            w=csv.DictWriter(f, fieldnames=fields, extrasaction='ignore'); w.writeheader(); w.writerows(rows)
    out_report=src.with_name(src.stem+'_authflag_report.md')
    lines=['# v105 auth flag analysis','', '## PC hits','', '| PC | Meaning | Hit |','|---|---|---|']
    for pc,desc in KEY_PCS.items(): lines.append(f'| {pc} | {desc} | {"HIT" if pc in hit else "miss"} |')
    lines += ['', '## Last writes', '', '| Address | PC | Bytes | Event |', '|---|---|---|---|']
    for label in ['0x071E','0x8003E7BA','0x8003E7BB','0x8003E7BC','0x8003E7BD','0x8003E7BE','0x8003E7DE','0x8003E804','0x8003E80C','0x077C','0x05CD','0xD95C']:
        r=last.get(label)
        lines.append(f'| {label} | {r.get("pc") if r else "—"} | {r.get("bytes_hex") if r else "—"} | {r.get("event") if r else "—"} |')
    out_report.write_text('\n'.join(lines)+'\n',encoding='utf-8')
    print(f'[OK] {out_report}')
    print(f'[OK] {out_events}')
    return 0
if __name__=='__main__': raise SystemExit(main(sys.argv))
