#!/usr/bin/env python3
"""Read the retained Lean CI artifact and bind its fresh replay receipt."""
from __future__ import annotations

import hashlib
import json
import sys
import zipfile
from pathlib import Path


ROOT = Path(__file__).resolve().parent
OK = True
PASS_COUNT = 0
FAIL_COUNT = 0


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


def line(label: str, condition: bool) -> None:
    global OK, PASS_COUNT, FAIL_COUNT
    OK = OK and condition
    if condition:
        PASS_COUNT += 1
        print("PASS " + label)
    else:
        FAIL_COUNT += 1
        print("FAIL " + label)


def main() -> int:
    try:
        outer = json.loads((ROOT / "CI_RECEIPT.json").read_text(encoding="utf-8"))
        artifact_name = outer["artifact"]["archive"]
        artifact_path = ROOT / artifact_name
        embedded_name = outer["artifact"]["embedded_receipt"]
        line(
            "L1 CI artifact bytes equal the declared SHA-256 and byte count",
            artifact_path.stat().st_size == outer["artifact"]["bytes"]
            and digest(artifact_path) == outer["artifact"]["sha256"],
        )
        with zipfile.ZipFile(artifact_path) as archive:
            names = archive.namelist()
            line(
                "L2 CI artifact members are readable and include the replay receipt, log, and checksum file",
                len(names) == len(set(names))
                and archive.testzip() is None
                and {embedded_name, "011-leanchecker.log", "011-leanchecker.sha256"} <= set(names),
            )
            sums: dict[str, str] = {}
            for raw in archive.read("011-leanchecker.sha256").decode("utf-8").splitlines():
                expected, name = raw.split("  ", 1)
                sums[name] = expected
            embedded = json.loads(archive.read(embedded_name))
            embedded_ok = (
                sums.get(embedded_name) == hashlib.sha256(archive.read(embedded_name)).hexdigest()
                and sums.get("011-leanchecker.log") == hashlib.sha256(archive.read("011-leanchecker.log")).hexdigest()
                and embedded.get("schema") == "011-kernel-replay/v1"
                and embedded.get("commit") == outer["source"]["commit"]
                and embedded.get("toolchain") == outer["source"]["toolchain"]
                and embedded.get("mathlib_revision") == outer["source"]["mathlib_commit"]
                and embedded.get("command") == outer["fresh_kernel_replay"]["command"]
                and embedded.get("target_module") == outer["fresh_kernel_replay"]["target"]
                and embedded.get("mode") == "fresh"
                and embedded.get("verdict") == "PASS"
                and embedded.get("checker_exit_code") == 0
                and embedded.get("runner_exit_code") == 0
                and embedded.get("working_tree_dirty") is False
                and embedded.get("inputs_unchanged") is True
                and embedded.get("ci", {}).get("event_sha") == outer["source"]["commit"]
                and embedded.get("ci", {}).get("repository") == outer["ci"]["repository"]
                and embedded.get("ci", {}).get("job") == outer["ci"]["job"]
                and embedded.get("ci", {}).get("run_id") == str(outer["ci"]["run_id"])
                and embedded.get("log_sha256") == hashlib.sha256(archive.read("011-leanchecker.log")).hexdigest()
            )
            line(
                "L3 embedded fresh Lean receipt binds the declared commit, toolchain, command, clean source, and PASS verdict",
                embedded_ok,
            )
    except (KeyError, OSError, ValueError, zipfile.BadZipFile) as error:
        line("L0 CI artifact read", False)
        print("INFO " + type(error).__name__)
    print(f"COUNT PASS={PASS_COUNT} FAIL={FAIL_COUNT}")
    print("RESULT " + ("PASS" if OK else "FAIL"))
    return 0 if OK else 1


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