#!/usr/bin/env python3
"""Aggregate GDR-8050L emulator validation reports into one pass/fail summary.

This is intentionally a report-only harness. It does not bundle firmware and it
never promotes the unlocked window delta unless a lower-level proof report has
already marked it firmware-derived.
"""
from __future__ import annotations
import argparse, json
from pathlib import Path
from typing import Any

VERSION = "v249"

def load(path: Path) -> dict[str, Any] | None:
    try:
        if path.exists():
            return json.loads(path.read_text(encoding="utf-8"))
    except Exception as e:
        return {"ok": False, "error": str(e), "path": str(path)}
    return None

def boolish(obj: dict[str,Any]|None, key="ok") -> bool:
    return bool(obj and obj.get(key))

def write_json(path: Path, obj: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(obj, indent=2)+"\n", encoding="utf-8")

def write_md(path: Path, r: dict[str,Any]) -> None:
    checks = r.get("checks", {})
    lines = [
        f"# GDR-8050L {VERSION} emulator test-suite summary",
        "",
        f"- ok: `{str(r.get('ok')).lower()}`",
        f"- suite_mode: `{r.get('suite_mode')}`",
        f"- live_trace: `{r.get('live_trace')}`",
        f"- firmware_derived_host_lba: `{str(r.get('firmware_derived_host_lba')).lower()}`",
        f"- firmware_derived_delta: `{str(r.get('firmware_derived_delta')).lower()}`",
        "",
        "## Checks",
        "",
        "| check | ok | notes |",
        "|---|---:|---|",
    ]
    for name, c in checks.items():
        lines.append(f"| `{name}` | `{str(c.get('ok')).lower()}` | {c.get('notes','')} |")
    lines += ["", "## Interpretation", ""]
    if r.get("firmware_derived_delta"):
        lines.append("The suite reports the READ-window delta as firmware-derived because the lower-level proof did so.")
    else:
        lines.append("The suite keeps `firmware_derived_delta=false`. The live bridge/media-profile mapping is clean, and firmware host-LBA ingestion is proven, but the executed firmware descriptor/window selector path is still the active proof target.")
    lines += ["", "## Operator notes", "", "Use `gdr8050l_auth_v249_run_emulator_test_suite.ps1` for the normal loop. It starts the target, optionally connects Windows iSCSI, runs VLC and unlockdrive automatically, then collects every report and writes this summary plus a ZIP.", ""]
    path.write_text("\n".join(lines), encoding="utf-8")

def main(argv=None) -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--base", default="gdr8050l_auth_v249_stateful_relock_keep_loaded_iscsi_start_live")
    ap.add_argument("--json", default=None)
    ap.add_argument("--md", default=None)
    ap.add_argument("--suite-mode", default="live")
    args = ap.parse_args(argv)
    base = args.base
    p = Path
    trace = load(p(f"{base}_trace_report.json"))
    standard = load(p(f"{base}_standard_probe_coverage_report.json"))
    lba = load(p(f"{base}_firmware_shadow_lba_map_report.json"))
    sweep = load(p(f"{base}_firmware_read_cdb_cpu_sweep_report.json"))
    delta = load(p(f"{base}_firmware_window_delta_audit_report.json"))
    pathprobe = load(p(f"{base}_firmware_read_window_path_probe_report.json"))
    app_validation = load(p(f"{base}_automated_app_validation.json"))
    media_preflight = load(p(f"{base}_media_profile_preflight_report.json"))
    payload = load(p(f"{base}_media_payload_integrity_report.json"))
    fleet = load(p(f"{base}_local_regression_fleet_report.json"))
    checks = {
        "trace_clean": {"ok": bool(trace is not None) and int(trace.get("unexpected_check_condition_count", 999) or 0) == 0, "notes": f"unexpected_check_condition_count={None if not trace else trace.get('unexpected_check_condition_count')}"},
        "standard_probe_coverage": {"ok": boolish(standard) and int(standard.get("unexpected_check_condition_count", standard.get("unexpected", 999)) or 0) == 0, "notes": "benign host probes handled"},
        "media_profile_preflight": {"ok": boolish(media_preflight), "notes": "Redump media/profile preflight"},
        "media_payload_integrity": {"ok": boolish(payload), "notes": "sidecar/profile response payloads"},
        "local_regression_fleet": {"ok": boolish(fleet) or bool((fleet or {}).get("evaluation", {}).get("ok")), "notes": "bridge/regression fleet"},
        "firmware_host_lba_cpu_sweep": {"ok": boolish(sweep) and bool(sweep.get("firmware_derived_host_lba")), "notes": "READ(10)/READ(12) -> SRAM 0x05EC"},
        "firmware_shadow_lba_map": {"ok": boolish(lba), "notes": "live READ LBA map audit"},
        "firmware_window_delta_audit": {"ok": boolish(delta) or bool((delta or {}).get("live_effective_delta_ok")), "notes": "keeps delta unpromoted unless proof exists"},
        "firmware_read_window_path_probe": {"ok": boolish(pathprobe) and bool(pathprobe.get("firmware_derived_host_lba")), "notes": "0x05EC -> 0x06E4/0x0760/0x0780 proof-gap tracker"},
    }
    require_app_validation = str(args.suite_mode).lower() in {"automated-live", "full-live"}
    if app_validation is not None or require_app_validation:
        checks["automated_windows_app_validation"] = {
            "ok": boolish(app_validation) or (not require_app_validation and app_validation is None),
            "notes": "VLC locked-video probe + unlockdrive auth/unlock" if app_validation is not None else "not run",
        }
    firmware_derived_host_lba = bool((sweep or {}).get("firmware_derived_host_lba")) or bool((pathprobe or {}).get("firmware_derived_host_lba"))
    firmware_derived_delta = bool((delta or {}).get("firmware_derived_delta")) or bool((pathprobe or {}).get("firmware_derived_delta"))
    # Missing optional reports should not pass silently.
    ok = all(c["ok"] for c in checks.values()) and firmware_derived_host_lba
    report = {
        "version": VERSION,
        "suite_mode": args.suite_mode,
        "live_trace": f"{base}.jsonl",
        "automated_app_validation": app_validation,
        "checks": checks,
        "firmware_derived_host_lba": firmware_derived_host_lba,
        "firmware_derived_delta": firmware_derived_delta,
        "ok": ok,
    }
    jp = Path(args.json or f"{base}_emulator_test_suite_report.json")
    mp = Path(args.md or f"{base}_emulator_test_suite_report.md")
    write_json(jp, report); write_md(mp, report)
    print(f"[EMULATOR-TEST-SUITE] ok={str(ok).lower()} host_lba={str(firmware_derived_host_lba).lower()} firmware_delta={str(firmware_derived_delta).lower()} checks={sum(1 for c in checks.values() if c['ok'])}/{len(checks)}")
    return 0 if ok else 1
if __name__ == "__main__":
    raise SystemExit(main())
