#!/usr/bin/env python3
"""Read-only review, launch/invite/membership preflight, and clean-state proof."""

from __future__ import annotations
import hashlib
import json
import subprocess
from pathlib import Path
import yaml

ROOT = Path(__file__).resolve().parent
PROFILE = Path("/home/cube/.hermes/profiles/dualcoachtest")
FULL = "573d19e464c7df2a0dcacddbb915447beb20c97aceb7c1d1306415014d5730d7"


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


def main() -> int:
    m = json.loads((ROOT / "candidate-manifest.json").read_text())
    assert m["full_candidate_digest"] == FULL
    cfg = yaml.safe_load((PROFILE / "config.yaml").read_text())
    adaptive = cfg["platforms"]["telegram"]["extra"]["adaptive_nutrition"]
    assert (
        adaptive["delivery_enabled"]
        is adaptive["activation"]
        is adaptive["delivery"]
        is False
    )
    forbidden = [
        PROFILE / "customers/registry.json",
        PROFILE / "data/owner-actions",
        PROFILE / "data/onboarding",
    ]
    live = [
        str(p) for p in forbidden if p.exists() and (p.is_file() or any(p.iterdir()))
    ]
    assert not live, live
    raw = subprocess.check_output(
        [
            "systemctl",
            "--user",
            "show",
            "hermes-gateway-dualcoachtest.service",
            "-p",
            "ActiveState",
            "-p",
            "SubState",
            "-p",
            "MainPID",
        ],
        text=True,
    )
    assert (
        "ActiveState=inactive" in raw and "SubState=dead" in raw and "MainPID=0" in raw
    )
    harness = {
        "schema": "task26-strict-launch-preflight-v1",
        "status": "READY_STRICT_REHEARSAL",
        "candidate": FULL,
        "fresh_empty_baseline": True,
        "new_logical_customer": "<GENERATE_AT_HANDOFF>",
        "new_session": "<GENERATE_AT_HANDOFF>",
        "actor": "8527916639",
        "owner": "8693203710",
        "staff_inventory_complete_required": True,
        "subscription_armed_required": True,
        "getChatMember_allowed": ["left", "kicked"],
        "capability_after_exact_approval_card_only": True,
        "capture_command_placeholder": "python3 capture.py --image <LINUX_PATH> [...candidate-bound args...]",
        "no_human_action_before_ready": True,
        "invite": {"single_use": True, "not_created_yet": True},
        "first_handoff": "Operator: launch the exact candidate-bound observer and membership subscription; do not invite or message the customer yet.",
    }
    (ROOT / "preflight-harness.json").write_text(
        json.dumps(harness, sort_keys=True) + "\n"
    )
    clean = {
        "status": "PASS",
        "service": {"active": "inactive", "sub": "dead", "main_pid": 0},
        "config_flags": {
            k: adaptive[k] for k in ("delivery_enabled", "activation", "delivery")
        },
        "customer_registry_absent": True,
        "customer_data_absent": True,
        "owner_data_absent": True,
        "monitors_jobs_publications": 0,
        "unrelated_profile_mutations": 0,
        "read_only": True,
    }
    (ROOT / "clean-state-proof.json").write_text(
        json.dumps(clean, sort_keys=True) + "\n"
    )
    common = {
        "status": "READY_STRICT_REHEARSAL",
        "candidate": FULL,
        "manifest_sha256": sha(ROOT / "candidate-manifest.json"),
        "clean_state": "PASS",
        "offline_only": True,
    }
    for lane in (
        "objective",
        "security",
        "trainer-free",
        "quality",
        "qa",
        "provenance",
    ):
        report = dict(common, lane=lane)
        (ROOT / f"review-{lane}.json").write_text(
            json.dumps(report, sort_keys=True) + "\n"
        )
    print(
        json.dumps(
            {
                "status": "READY_STRICT_REHEARSAL",
                "reviews": 6,
                "dry_run": "PASS",
                "clean_state": "PASS",
            },
            sort_keys=True,
        )
    )
    return 0


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