#!/usr/bin/env python3
from __future__ import annotations
import hashlib
import importlib.util
import json
import os
import stat
from pathlib import Path

HERE = Path(__file__).parent
PROFILE = Path("/home/cube/.hermes/profiles/dualcoachtest")
OTHER = Path("/home/cube/.hermes/profiles/physique-coach")
ARCHIVE = PROFILE / "data/profile-reset-archives/task26-live-reset-2e0894ea"


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


def check(v: bool, m: str):
    if not v:
        raise RuntimeError(m)


def main() -> int:
    for p in HERE.iterdir():
        if p.is_file():
            s = p.lstat()
            check(
                not p.is_symlink()
                and stat.S_ISREG(s.st_mode)
                and s.st_uid == os.getuid()
                and s.st_nlink == 1
                and stat.S_IMODE(s.st_mode) in (0o600, 0o700),
                f"unsafe evidence {p}",
            )
    c = json.loads((HERE / "schema-contract-v1.json").read_text())
    p = json.loads((HERE / "permission-seal-v1.json").read_text())
    t = json.loads((HERE / "test-receipt.json").read_text())
    d = json.loads((HERE / "live-dry-run-receipt.json").read_text())
    check(
        p["controller_sha256"] == sha(HERE / "baseline_controller.py")
        and p["contract_sha256"] == sha(HERE / "schema-contract-v1.json")
        and p["rollback_record_sha256"] == sha(HERE / "rollback-record.json"),
        "seal mismatch",
    )
    check(
        c["archive_manifest_sha256"] == sha(ARCHIVE / "manifest.json")
        and c["archive_receipt_sha256"] == sha(ARCHIVE / "receipt.json"),
        "archive drift",
    )
    check(
        c["invite_ledger_sha256"]
        == sha(PROFILE / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json"),
        "invite drift",
    )
    check(
        t["status"] == "PASS"
        and t["passed"] == 11
        and t["ruff"] == "PASS"
        and t["compile"] == "PASS"
        and t["lsp_errors"] == 0,
        "test gates",
    )
    check(
        d["status"] == "PASS"
        and d["mode"] == "dry-run"
        and d["mutations"] == 0
        and d["planned_registry_sha256"] == c["canonical_registry_sha256"],
        "dry run gate",
    )
    source = (HERE / "baseline_controller.py").read_text()
    check(
        source.index("rollback record drift") < source.index("publish(a.profile")
        and "archive_restore" not in source
        and "customer row" not in source,
        "publication boundary",
    )
    spec = importlib.util.spec_from_file_location(
        "baseline_independent", HERE / "baseline_controller.py"
    )
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)
    m.preflight(PROFILE, OTHER, ARCHIVE, c)
    out = {
        "schema": "task26-reset-baseline-completion-independent-verification-v1",
        "status": "PASS",
        "controller_sha256": sha(HERE / "baseline_controller.py"),
        "contract_sha256": sha(HERE / "schema-contract-v1.json"),
        "permission_sha256": sha(HERE / "permission-seal-v1.json"),
        "archive_unchanged": True,
        "invite_unchanged": True,
        "live_dry_run_pass": True,
        "ready_to_complete_once": True,
    }
    print(json.dumps(out, sort_keys=True, separators=(",", ":")))
    return 0


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