#!/usr/bin/env python3
import argparse, csv, collections
PCS = ["0x9001DF69","0x9001DF75","0x9001D05B","0x9001D086","0x9001D090","0x900396FD","0x9003971A","0x90039767","0x90039778","0x900397B4"]
ADDRS = ["0x00000729","0x0000071E","0x0003E7BA","0x0003E7BB","0x0003E7BC","0x0003E7BD","0x0003E7BE","0x0003E7BF","0x8003E7BA","0x8003E7BB","0x8003E7BC","0x8003E7BD","0x8003E7BE","0x8003E7BF"]
def norm(s): return (s or '').upper()
def main():
    ap=argparse.ArgumentParser(); ap.add_argument('trace'); ap.add_argument('--out', default='gdr8050l_v108_route_probe_summary.md'); ns=ap.parse_args()
    rows=list(csv.DictReader(open(ns.trace,newline='')))
    pc_counts=collections.Counter(norm(r.get('pc')) for r in rows if r.get('pc'))
    addr_last={}; rel=[]
    pc_set=[p.upper() for p in PCS]; addr_set=[a.upper() for a in ADDRS]
    for r in rows:
        pc=norm(r.get('pc')); addr=norm(r.get('addr')); phys=norm(r.get('addr_physical'))
        if pc in pc_set or addr in addr_set or phys in addr_set:
            rel.append(r)
            if addr: addr_last[addr]=r
    with open(ns.out,'w',newline='') as f:
        f.write('# GDR-8050L v108 route probe summary\n\n')
        f.write('## PC hits\n\n| PC | hits |\n|---|---:|\n')
        for p in PCS: f.write(f'| {p} | {pc_counts[p.upper()]} |\n')
        f.write('\n## Last relevant address events\n\n| addr | event | pc | bytes | value | cycle |\n|---|---|---|---|---|---:|\n')
        for a in ADDRS:
            r=addr_last.get(a.upper())
            if r: f.write(f"| {a} | {r.get('event','')} | {r.get('pc','')} | {r.get('bytes_hex','')} | {r.get('value','')} | {r.get('cycle','')} |\n")
            else: f.write(f'| {a} | miss | | | | |\n')
        f.write('\n## First 60 relevant events\n\n```text\n')
        for r in rel[:60]:
            f.write(f"seq={r.get('seq')} cyc={r.get('cycle')} {r.get('event')} pc={r.get('pc')} addr={r.get('addr')} phys={r.get('addr_physical')} bytes={r.get('bytes_hex')} value={r.get('value')} name={r.get('name')}\n")
        f.write('```\n')
    print('[OK] wrote', ns.out, 'relevant_events=', len(rel))
if __name__ == '__main__': main()
