"""Check the WhiteBoxXAI sample evidence pack yourself.

Download every file from the same folder as this script (the PDFs, the JSON
files, the two CSVs and manifest.json), then run:

    python verify_sample.py [folder]

It needs only Python 3.9+. The drift check also needs scipy
(``pip install scipy``); without it that one check is skipped and says so.

What it checks, and what each check proves:

1. File hashes. Every file's SHA-256 matches manifest.json, so the files are
   the ones the generator wrote.
2. Sign-offs. The pack PDF's SHA-256 equals the hash each sign-off pinned.
   Change one byte of the PDF and no sign-off vouches for it any more.
3. Audit chain. Each event's SHA-256 is recomputed from its recorded fields
   and the previous event's hash, and each link is checked. Alter, insert or
   delete any event and the chain breaks from that point on.
4. Drift p-values. Each Kolmogorov-Smirnov statistic and p-value is
   recomputed with scipy from the raw samples in the two CSVs.
5. SHAP additivity. For every published explanation, the base value plus the
   SHAP values equals the model's output (in the space the manifest names).
   Numbers written by hand would not satisfy this.
6. Global attribution. The ranking printed in the pack is recomputed as the
   mean absolute SHAP value over the published explanations.

Exit status is 0 only if every check that ran passed.
"""

from __future__ import annotations

import csv
import hashlib
import json
import math
import sys
from pathlib import Path

PACK_FILE = "auditor-evidence-pack-sample.pdf"
PACK_JSON_FILE = "auditor-evidence-pack-sample.json"


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


def check_file_hashes(folder: Path, manifest: dict) -> list[str]:
    problems = []
    for name, expected in manifest["files"].items():
        path = folder / name
        if not path.exists():
            problems.append(f"{name}: missing")
        elif _sha256(path) != expected["sha256"]:
            problems.append(f"{name}: SHA-256 does not match the manifest")
    return problems


def check_signoffs(folder: Path, manifest: dict) -> list[str]:
    signoffs = manifest["signoffs"]
    actual = _sha256(folder / signoffs["pinned_file"])
    problems = []
    if actual != signoffs["export_file_hash"]:
        problems.append("the pack's SHA-256 is not the hash recorded for the export")
    for signoff in signoffs["recorded"]:
        if signoff["content_hash"] != actual:
            problems.append(f"{signoff['role']} sign-off pins a different hash")
    roles = [s["user"] for s in signoffs["recorded"]]
    if len(set(roles)) != len(roles):
        problems.append("one person holds more than one sign-off role")
    return problems


def event_hash(fields: dict, previous_hash: str | None) -> str:
    """The platform's hash: SHA-256 over json.dumps(..., sort_keys=True) of the
    hashed fields plus the previous event's hash."""
    payload = dict(fields)
    payload["previous_hash"] = previous_hash
    return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()


def check_audit_chain(manifest: dict) -> list[str]:
    problems = []
    previous = None
    for index, event in enumerate(manifest["audit_chain"]["events"], start=1):
        if index > 1 and event["previous_event_hash"] != previous:
            problems.append(f"event {index}: does not link to event {index - 1}")
        if (
            event_hash(event["hashed_fields"], event["previous_event_hash"])
            != event["event_hash"]
        ):
            problems.append(f"event {index}: hash does not match its fields")
        previous = event["event_hash"]
    return problems


def _read_csv(path: Path) -> dict[str, list[float]]:
    with open(path, newline="", encoding="utf-8") as handle:
        rows = list(csv.DictReader(handle))
    return {name: [float(r[name]) for r in rows] for name in rows[0]}


def check_drift(folder: Path, manifest: dict) -> list[str] | None:
    try:
        from scipy.stats import ks_2samp
    except ImportError:
        return None
    drift = manifest["drift"]
    reference = _read_csv(folder / drift["reference_file"])
    current = _read_csv(folder / drift["current_file"])
    problems = []
    for feature in drift["feature_results"]:
        name = feature["feature_name"]
        for test in feature["test_results"]:
            if test["test"] != "Kolmogorov-Smirnov":
                continue
            statistic, p_value = ks_2samp(reference[name], current[name])
            if not math.isclose(statistic, test["statistic"], rel_tol=1e-9):
                problems.append(f"{name}: KS statistic does not reproduce")
            if not math.isclose(p_value, test["p_value"], rel_tol=1e-6, abs_tol=1e-300):
                problems.append(f"{name}: KS p-value does not reproduce")
    return problems


def check_shap_additivity(manifest: dict) -> list[str]:
    explain = manifest["explainability"]
    problems = []
    for index, row in enumerate(explain["explanations"], start=1):
        total = row["base_value"] + sum(row["shap_values"].values())
        p = row["model_output_probability"]
        target = math.log(p / (1 - p)) if explain["output_space"] == "log_odds" else p
        if not math.isclose(total, target, abs_tol=1e-6):
            problems.append(f"explanation {index}: SHAP values do not add up")
    return problems


def check_global_attribution(folder: Path, manifest: dict) -> list[str]:
    rows = manifest["explainability"]["explanations"]
    totals: dict[str, float] = {}
    for row in rows:
        for feature, value in row["shap_values"].items():
            totals[feature] = totals.get(feature, 0.0) + abs(value)
    sections = json.loads((folder / PACK_JSON_FILE).read_text(encoding="utf-8"))
    explainability = next(s for s in sections if s["key"] == "explainability")
    printed = explainability["data"]["global_attribution"]
    problems = []
    if printed["explanations_used"] != len(rows):
        problems.append("the pack averaged a different number of explanations")
    for entry in printed["features"]:
        mean = totals.get(entry["feature"], 0.0) / len(rows)
        if not math.isclose(mean, entry["mean_abs_shap"], rel_tol=1e-9):
            problems.append(f"{entry['feature']}: mean |SHAP| does not reproduce")
    return problems


def run_checks(folder: Path) -> list[tuple[str, list[str] | None]]:
    """Every check as (name, problems); problems is None when skipped."""
    manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))
    return [
        ("File hashes match the manifest", check_file_hashes(folder, manifest)),
        ("Sign-offs pin this exact PDF", check_signoffs(folder, manifest)),
        ("Audit chain recomputes and links", check_audit_chain(manifest)),
        (
            "Drift KS p-values reproduce from the raw samples",
            check_drift(folder, manifest),
        ),
        ("SHAP values add up to the model output", check_shap_additivity(manifest)),
        (
            "Pack attribution ranking reproduces",
            check_global_attribution(folder, manifest),
        ),
    ]


def main() -> int:
    folder = Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).parent)
    failed = False
    for name, problems in run_checks(folder):
        if problems is None:
            print(f"SKIP  {name} (install scipy to run it)")
        elif problems:
            failed = True
            print(f"FAIL  {name}")
            for problem in problems:
                print(f"        - {problem}")
        else:
            print(f"PASS  {name}")
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())
