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

HERE = Path(__file__).parent
PROFILE = Path("/home/cube/.hermes/profiles/dualcoachtest")
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:
    c = json.loads((HERE / "schema-contract-v1.json").read_text())
    reg = PROFILE / "customers/registry.json"
    s = reg.lstat()
    d = reg.parent.lstat()
    check(
        stat.S_ISREG(s.st_mode)
        and stat.S_IMODE(s.st_mode) == 0o600
        and s.st_nlink == 1
        and s.st_uid == os.getuid(),
        "unsafe registry",
    )
    check(
        stat.S_ISDIR(d.st_mode)
        and stat.S_IMODE(d.st_mode) == 0o700
        and d.st_uid == os.getuid(),
        "unsafe customers directory",
    )
    check(
        reg.read_bytes()
        == (
            json.dumps(c["canonical_registry"], sort_keys=True, separators=(",", ":"))
            + "\n"
        ).encode(),
        "noncanonical registry",
    )
    check(
        sha(ARCHIVE / "manifest.json") == c["archive_manifest_sha256"]
        and sha(ARCHIVE / "receipt.json") == c["archive_receipt_sha256"],
        "archive drift",
    )
    check(
        sha(PROFILE / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json")
        == c["invite_ledger_sha256"],
        "invite drift",
    )
    v = json.loads((HERE / "offline-candidate-verification-receipt.json").read_text())
    check(
        v["status"] == "PASS"
        and v["load_committed_customer_registry_customers"] == 0
        and v["registry_sha256"] == c["canonical_registry_sha256"],
        "candidate verification",
    )
    out = subprocess.run(
        [
            "systemctl",
            "--user",
            "show",
            "hermes-gateway-dualcoachtest.service",
            "--property=ActiveState,SubState,MainPID",
            "--value",
        ],
        check=True,
        capture_output=True,
        text=True,
    ).stdout.splitlines()
    check(out == ["0", "inactive", "dead"], "service changed")
    receipt = {
        "schema": "task26-reset-baseline-completion-independent-post-verification-v1",
        "status": "PASS",
        "archive_unchanged": True,
        "invite_unchanged": True,
        "registry_sha256": sha(reg),
        "customers": 0,
        "service_started": False,
        "ready_for_gateway_restart": True,
    }
    print(json.dumps(receipt, sort_keys=True, separators=(",", ":")))
    return 0


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