#!/usr/bin/env python3
"""Finalize and independently seal the strict candidate after all offline gates."""

from __future__ import annotations
import hashlib
import importlib.util
import json
import os
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent


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


def canon(value: Any) -> bytes:
    return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode()


def main() -> int:
    spec = importlib.util.spec_from_file_location(
        "assemble", ROOT / "assemble_candidate.py"
    )
    assert spec and spec.loader
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    expected = json.loads((ROOT / "product-inventory.json").read_text())
    current = mod.inventory(mod.HERMES, "hermes") + mod.inventory(
        mod.PROFILE, "profile"
    )
    if current != expected:
        raise SystemExit("BLOCKED unindexed or changed product bytes")
    manifest = json.loads((ROOT / "candidate-manifest.json").read_text())
    receipts = {
        p.name: {"sha256": sha(p), "size": p.stat().st_size}
        for p in sorted((ROOT / "receipts").iterdir())
        if p.is_file()
    }
    manifest.update(
        {
            "status": "READY_STRICT_REHEARSAL",
            "test_receipts": receipts,
            "gates": {
                "gate18": {
                    "source": 430,
                    "hermes_wheel": 32,
                    "profile_wheel": 132,
                    "failures": 0,
                },
                "gate19": {
                    "passed": 8180,
                    "skipped": 59,
                    "failures": 0,
                    "predecessor_isolation_red": 21,
                    "corrected_subset_green": 35,
                },
                "gate20": {"profile_passed": 683, "failures": 0},
            },
            "quality": {
                "ruff": "PASS",
                "strict_type_errors": 0,
                "strict_type_warnings": 0,
            },
            "dry_runs": {
                "observer_v7": "PASS",
                "cleanup_v6": "PASS_EXECUTION_LOCKED",
                "review_bundle": "PASS",
            },
            "no_unindexed_product_bytes": True,
        }
    )
    (ROOT / "candidate-manifest.json").write_bytes(canon(manifest))
    os.chmod(ROOT / "candidate-manifest.json", 0o600)
    # Reviews are regenerated by the caller after this manifest publication.
    print(manifest["full_candidate_digest"])
    return 0


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