#!/usr/bin/env python3
"""
Standalone <1s Public Reproducibility & Provenance Verifier — bsar (v0.2.0 HUD)
===============================================================================
Zero external dependencies. Verifies:
  1. Bit-exact SHA-256 digests of every artifact listed in MANIFEST_SHA256.json
  2. Exact 5-chore token totals, savings, and compression ratios directly from
     bsar_benchmark_metrics.csv, cerebral_valley_metrics.csv, and
     cerebral_valley_benchmark.json (no hardcoded illusions).

Sweetbrier Attestation: probabilistic_structural
"""

from __future__ import annotations

import csv
import hashlib
import json
import pathlib
import time

HERE = pathlib.Path(__file__).resolve().parent.parent


def sha256_file(path: pathlib.Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main() -> None:
    t0 = time.perf_counter()

    # 1. Verify MANIFEST_SHA256.json byte-for-byte
    manifest_path = HERE / "MANIFEST_SHA256.json"
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    files = manifest.get("files", {})
    assert files, "MANIFEST_SHA256.json contains no files"
    for rel, meta in files.items():
        p = HERE / rel
        assert p.exists(), f"Missing manifest file: {rel}"
        digest = sha256_file(p)
        expected = meta["sha256"] if isinstance(meta, dict) else meta
        assert digest == expected, f"SHA-256 mismatch on {rel}: {digest} != {expected}"

    # 2. Load primary CSVs & JSON bundle
    with open(HERE / "bsar_benchmark_metrics.csv", encoding="utf-8", newline="") as f:
        bench_rows = list(csv.DictReader(f))
    with open(HERE / "cerebral_valley_metrics.csv", encoding="utf-8", newline="") as f:
        cv_rows = list(csv.DictReader(f))
    report = json.loads((HERE / "cerebral_valley_benchmark.json").read_text(encoding="utf-8"))

    # 3. Cross-check 5-chore sums directly from primary CSV rows
    chores = [r for r in bench_rows if r["row_type"] == "CHORE"]
    assert len(chores) == 5, f"Expected 5 CHORE rows, got {len(chores)}"
    assert len(cv_rows) == 5, f"Expected 5 cerebral_valley_metrics rows, got {len(cv_rows)}"

    naive_sum = sum(int(r["naive_tokens"]) for r in chores)
    bsar_sum = sum(int(r["bsar_tokens"]) for r in chores)
    saved_sum = sum(int(r["tokens_saved"]) for r in chores)
    assert naive_sum - bsar_sum == saved_sum

    cv_naive = sum(int(r["naive_tokens"]) for r in cv_rows)
    cv_bsar = sum(int(r["bsar_tokens"]) for r in cv_rows)
    assert cv_naive == naive_sum and cv_bsar == bsar_sum, "CSV pair mismatch"

    hs = report["headline_summary"]
    assert hs["total_naive_tokens_per_suite"] == naive_sum
    assert hs["total_bsar_tokens_per_suite"] == bsar_sum
    assert hs["total_tokens_saved_per_suite"] == saved_sum

    full_x = round(naive_sum / bsar_sum, 2)
    full_red = round(100.0 * saved_sum / naive_sum, 2)
    assert abs(full_x - hs["cold_start_suite_compression_x"]) < 0.02
    assert abs(full_red - hs["overall_token_reduction_pct"]) < 0.02

    # 4. Data + Public Traces + Guardrail plane (Chores 1, 2, 3, 5)
    dtg_ids = {
        "CHORE_1_CORPUS_5Q",
        "CHORE_2_TRANSCRIPT_AUDIT",
        "CHORE_3_PORCH_ZD_FIREWALL",
        "CHORE_5_PUBLIC_MULTIAGENT_TRACES",
    }
    dtg_rows = [r for r in chores if r["row_id"] in dtg_ids]
    dtg_naive = sum(int(r["naive_tokens"]) for r in dtg_rows)
    dtg_bsar = sum(int(r["bsar_tokens"]) for r in dtg_rows)
    dtg_x = round(dtg_naive / dtg_bsar, 1)
    assert hs["data_trace_guardrail_naive_tokens"] == dtg_naive
    assert hs["data_trace_guardrail_bsar_tokens"] == dtg_bsar
    assert abs(dtg_x - hs["data_trace_guardrail_compression_x"]) < 0.2

    # 5. Verify Asar 3-pass zero drift & hardware pin invariants
    zd = report["asar_q88_zd_microbench"]
    assert zd["asar_three_pass_deterministic"] is True
    assert zd["pass1_to_pass2_byte_drift"] == 0
    assert zd["rats_header"]["valid"] is True

    elapsed_ms = (time.perf_counter() - t0) * 1000.0
    print(
        f"VERIFIED [probabilistic_structural] | slug=bsar | files_hashed={len(files)} "
        f"| 5-chore={naive_sum:,}->{bsar_sum:,} ({full_x}x, -{full_red}%) "
        f"| data+traces={dtg_naive:,}->{dtg_bsar:,} ({dtg_x}x) | elapsed={elapsed_ms:.1f}ms"
    )


if __name__ == "__main__":
    main()
