#!/usr/bin/env python3
"""Create the deterministic v6 artifact inventory and seal exactly once."""

from __future__ import annotations

import hashlib
import json
import os
from pathlib import Path

ROOT = Path(__file__).resolve().parent
SEALED = (
    "OPERATIONS.md",
    "continuous_lifecycle.py",
    "independent_verify.py",
    "observer_v61.py",
    "readiness.json",
    "seal_artifacts.py",
    "test_continuous_lifecycle.py",
    "test_observer_v61.py",
)


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


def exclusive(path: Path, value: object) -> None:
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o600)
    try:
        os.write(fd, (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode())
        os.fsync(fd)
    finally:
        os.close(fd)


def main() -> int:
    files = [{"path": name, "sha256": digest(ROOT / name)} for name in SEALED]
    inventory = {
        "schema": "task26-observer-v6.1-hash-inventory-v1",
        "files": files,
        "sealed_file_count": len(files),
    }
    exclusive(ROOT / "hash-inventory.json", inventory)
    seal = {
        "schema": "task26-continuous-lifecycle-observer-v6.1-seal-v1",
        "status": "PASS_SEALED_CORRECTED_READY_OPERATOR_ACTIVATION_CUTOVER",
        "predecessor_root": "task26-continuous-lifecycle-observer-v6-6aaef77d",
        "predecessor_seal_sha256": "34b9b4d8677c0a4f977c659f99bad1e9a9d94e289a10c25fdcb12faf14be1168",
        "candidate": "6aaef77de87489c3be493978645781b24b55ab07513ff1f880164741d0bd3c73",
        "core": "f759460a42155925ef68d75a03f4c86cffe6d1b6ec774bd61efb73174e10b60c",
        "profile_wheel": "f75856d6d986b64d3d2f083aec2f865c7aea19f5950b84ff06e519f2f6505af6",
        "hermes_wheel": "33688875a0d1ce20955bd8272257ee34d84cb138f6a23a43e5d16682368ae5e5",
        "inventory_sha256": digest(ROOT / "hash-inventory.json"),
        "sealed_file_count": len(files),
        "tests_passed": 29,
        "registered_root_regression": "PASS_REAL_CUSTOMER_ADMIN_RESOLVER",
        "failed_attempt_zero_mutation": True,
        "profile_module_parity_count": 44,
        "lsp_errors": 0,
        "ruff": "PASS",
        "compile": "PASS",
        "network_calls": 0,
        "profile_mutated": False,
        "service_actions": 0,
        "ui_actions": 0,
    }
    exclusive(ROOT / "SEAL.json", seal)
    print(json.dumps(seal, sort_keys=True))
    return 0


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