"""Reproduce the website's recorded fixtures using the public PyCharter API."""

from __future__ import annotations

import argparse
import hashlib
import json
from importlib.metadata import version
from pathlib import Path

from pycharter import Validator

ROOT = Path(__file__).resolve().parent
CASES = ("valid", "rejected", "corrected")


def digest(path: Path) -> str:
    """Return the exact file's SHA-256 fingerprint."""
    return hashlib.sha256(path.read_bytes()).hexdigest()


def reproduce() -> dict:
    """Run all three fixtures and preserve the validator's actual diagnostics."""
    installed = version("pycharter")
    if installed != "0.0.67":
        raise RuntimeError("Install requirements.txt: this example pins pycharter==0.0.67")
    contract = ROOT / "contract.json"
    validator = Validator.from_file(str(contract))
    cases = {}
    for case in CASES:
        path = ROOT / f"{case}.json"
        rows = json.loads(path.read_text())
        results = validator.validate_batch(rows)
        count = sum(result.is_valid for result in results)
        cases[case] = {
            "input": path.name,
            "input_sha256": digest(path),
            "record_count": len(rows),
            "valid_count": count,
            "invalid_count": len(rows) - count,
            "records": [result.to_dict() for result in results],
        }
    return {
        "example_version": "price-batch-v1",
        "evidence_mode": "recorded_fixture",
        "pycharter_version": installed,
        "contract": {"file": contract.name, "version": "1.0.0", "sha256": digest(contract)},
        "cases": cases,
    }


def main() -> int:
    """Print fresh results, optionally comparing them with the recorded evidence."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--check", action="store_true", help="Compare with evidence.json")
    args = parser.parse_args()
    result = reproduce()
    print(json.dumps(result, indent=2))
    if args.check and result != json.loads((ROOT / "evidence.json").read_text()):
        print("Evidence mismatch: review changed inputs, dependencies, or validator behavior.")
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
