#!/usr/bin/env python3
"""Audit benign standard MMC/SCSI host probes that should not become noisy CHECK CONDITION rows.

This report is intentionally about host-enumeration polish, not about firmware-derived
Xbox window/auth behavior. It helps verify v234's READ DVD STRUCTURE / READ TRACK
INFORMATION / SET STREAMING / READ CD handlers against uploaded live JSONL artifacts.
"""
from __future__ import annotations
import argparse, json
from pathlib import Path
from typing import Any

VERSION='v234'

def read_jsonl(path: Path) -> list[dict[str,Any]]:
    rows=[]
    if not path.exists(): return rows
    for line in path.read_text(encoding='utf-8', errors='ignore').splitlines():
        line=line.strip()
        if not line: continue
        try: rows.append(json.loads(line))
        except Exception: pass
    return rows

def op_from_cdb_hex(s: str) -> int|None:
    try:
        p=str(s or '').strip().split()
        return int(p[0],16) if p else None
    except Exception: return None

def classify(row: dict[str,Any]) -> str:
    cdb=str(row.get('cdb_hex') or '').upper()
    op=op_from_cdb_hex(cdb)
    if op==0xAD:
        parts=cdb.split()
        fmt='??'
        vendor='??'
        try:
            fmt=f'0x{int(parts[7],16):02X}'
            vendor=f'0x{int(parts[11],16):02X}' if len(parts)>11 else '0x00'
        except Exception: pass
        if vendor == '0xC0': return 'read_dvd_structure_vendor_c0_catalog'
        return f'read_dvd_structure_standard_fmt_{fmt}'
    if op==0x52: return 'read_track_information'
    if op==0xB6: return 'set_streaming'
    if op==0xBE: return 'read_cd_probe'
    if op==0x2B and row.get('expected_boundary_failure'): return 'expected_locked_seek_boundary'
    return f'op_0x{op:02X}' if op is not None else 'unknown'

def write_json(path: Path, obj: Any):
    path.write_text(json.dumps(obj, indent=2, sort_keys=True)+'\n', encoding='utf-8')

def write_md(path: Path, report: dict[str,Any]):
    lines=[f'# GDR-8050L {VERSION} standard probe coverage report','',f'- ok: `{str(report.get("ok")).lower()}`',f'- live_unexpected_check_condition_count: `{report.get("unexpected_check_condition_count")}`',f'- v234_handlers_cover_live_standard_probe_gaps: `{str(report.get("v234_handlers_cover_live_standard_probe_gaps")).lower()}`','']
    lines += ['## Unexpected CHECK CONDITION classifications','','| class | count | covered by v234 handler |','|---|---:|---|']
    for k,v in sorted((report.get('unexpected_classes') or {}).items()):
        lines.append(f'| `{k}` | {v} | `{str(k in set(report.get("covered_classes") or [])).lower()}` |')
    lines += ['', '## Interpretation', '', report.get('note','')]
    path.write_text('\n'.join(lines)+'\n', encoding='utf-8')

def main(argv=None):
    ap=argparse.ArgumentParser()
    ap.add_argument('jsonl')
    ap.add_argument('--json', default='gdr8050l_auth_v234_standard_probe_coverage_report.json')
    ap.add_argument('--md', default='gdr8050l_auth_v234_standard_probe_coverage_report.md')
    args=ap.parse_args(argv)
    rows=read_jsonl(Path(args.jsonl))
    scsi=[r for r in rows if 'cdb_hex' in r]
    unexpected=[r for r in scsi if str(r.get('scsi_status','')).upper()=='CHECK CONDITION' and not r.get('expected_boundary_failure')]
    classes={}
    examples={}
    for r in unexpected:
        c=classify(r)
        classes[c]=classes.get(c,0)+1
        examples.setdefault(c, r.get('cdb_hex',''))
    covered_prefixes=('read_dvd_structure_standard_fmt_0x00','read_dvd_structure_standard_fmt_0x11','read_track_information','set_streaming','read_cd_probe')
    covered=[k for k in classes if k in covered_prefixes]
    all_standard=all((k in covered_prefixes) for k in classes)
    no_unexpected = (len(unexpected) == 0)
    report={
        'version': VERSION,
        'jsonl': str(args.jsonl),
        'rows': len(rows),
        'scsi_rows': len(scsi),
        'unexpected_check_condition_count': len(unexpected),
        'unexpected_classes': classes,
        'examples': examples,
        'covered_classes': covered,
        'v234_handlers_cover_live_standard_probe_gaps': bool(no_unexpected or all_standard),
        'ok': len(rows)>0 and (no_unexpected or all_standard),
        'note': 'If this report is run on a v231/v232 live trace, nonzero unexpected CHECK CONDITION rows are acceptable only when every row is one of the standard host probe classes that v232/v233/v234 now handle. A fresh v234 live run should have unexpected_check_condition_count zero except for intentional boundary probes. READ CD (0xBE) compatibility handling remains included.',
    }
    write_json(Path(args.json), report)
    write_md(Path(args.md), report)
    print(f"[STANDARD-PROBE-COVERAGE] unexpected={len(unexpected)} classes={classes} v234_handlers_cover={str(report['v234_handlers_cover_live_standard_probe_gaps']).lower()} ok={str(report['ok']).lower()}")
    return 0 if report['ok'] else 1
if __name__=='__main__':
    raise SystemExit(main())
