"""Freeze the exact live-representative NutriCoach V14 package closure."""

from __future__ import annotations

import hashlib
import json
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path

from pydantic import JsonValue, TypeAdapter

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from scripts.nutricoach_v150_live_upgrade_common import canonical
from scripts.nutricoach_v150_runtime_ops import dependency_snapshot_digest
from scripts.verify_nutricoach_v150_candidate import verify as verify_candidate

_OBJECT = TypeAdapter(dict[str, JsonValue])
SOURCE = Path("/home/cube/projects/richard/.worktrees/nutricoach-v150-combined")
BASE = Path("/home/cube/.hermes/migrations/nutricoach-v1.5.0-combined")
EVIDENCE = Path(
    "/home/cube/projects/richard/traning coach/.omo/evidence/"
    + "nutricoach-v150-combined"
)
CANDIDATE = "3dab1a5531c71239899c5a836f8689b9b6c59dc07ca7443de76442cf0eb5090d"
CANDIDATE_ROOT = EVIDENCE / "task-v14r20-candidate"
MANIFEST = CANDIDATE_ROOT / "manifest.json"
BASE_MANIFEST = (
    SOURCE
    / (
        ".omo/evidence/nutricoach-v150-combined/task-1-candidate/inputs/"
        + "base-manifest.json"
    )
)
PREFLIGHT = BASE / "preflight-v14-live-representative-r20"
PRESEAL = BASE / "live-transaction-preseal-v14-live-representative-r20"
PRIOR_PRESEAL = BASE / "live-transaction-preseal-v14-live-representative-r19"
PRIOR_PREFLIGHT = BASE / "preflight-v14-live-representative-r19"
PROFILE = Path("/home/cube/.hermes/profiles/dualcoachtest")
AUTHORITY_ID = "nutricoach-v150-v14-live-representative-59-3dab1a55"
R14_AUTHORITY_ID = "nutricoach-v150-v14-live-representative-53-1ee809af"
R14_PACKAGE_DIGEST = (
    "7a60506ffd66f76bfe51e1864f180a3bc597a2d67ffbc39fcf8fb247e90eaeea"
)


def _load(path: Path) -> dict[str, JsonValue]:
    return _OBJECT.validate_json(path.read_bytes())


def _write(path: Path, value: object) -> None:
    document = _OBJECT.validate_python(value)
    _ = path.write_bytes(canonical(document) + b"\n")


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


def _record_sha(path: Path) -> str:
    with zipfile.ZipFile(path) as wheel:
        name = next(name for name in wheel.namelist() if name.endswith("/RECORD"))
        return hashlib.sha256(wheel.read(name)).hexdigest()


def _service_state() -> dict[str, JsonValue]:
    fields = (
        "ActiveState",
        "SubState",
        "MainPID",
        "ExecStart",
        "ExecMainStartTimestampMonotonic",
        "Result",
    )
    result = subprocess.run(
        (
            "/usr/bin/systemctl",
            "--user",
            "show",
            "hermes-gateway-dualcoachtest.service",
            *(f"--property={field}" for field in fields),
        ),
        check=True,
        capture_output=True,
        text=True,
    )
    observed = dict(
        line.split("=", 1) for line in result.stdout.splitlines() if "=" in line
    )
    return {field: observed.get(field, "") for field in fields}


def _registry_shape() -> dict[str, JsonValue]:
    registry_path = PROFILE / "customers/registry.json"
    registry = _load(registry_path)
    customers = registry.get("customers")
    if not isinstance(customers, list):
        raise RuntimeError("registry_customers")
    enabled: list[JsonValue] = []
    disabled: list[JsonValue] = []
    for raw in customers:
        if not isinstance(raw, dict):
            raise RuntimeError("registry_customer")
        key = raw.get("customer_key")
        if not isinstance(key, str):
            raise RuntimeError("registry_key")
        (enabled if raw.get("enabled") is True else disabled).append(key)
    return {
        "schema": "nutricoach-v150-live-registry-shape-v14",
        "registry_path": str(registry_path),
        "registry_sha256": _sha(registry_path),
        "customer_count": len(customers),
        "enabled_customer_keys": enabled,
        "disabled_customer_keys": disabled,
    }


def _controller_files(candidate: dict[str, JsonValue]) -> dict[str, JsonValue]:
    rows = candidate.get("source_inventory")
    if not isinstance(rows, list):
        raise RuntimeError("source_inventory")
    files: dict[str, JsonValue] = {}
    for raw in rows:
        if not isinstance(raw, dict) or not isinstance(raw.get("path"), str):
            raise RuntimeError("source_entry")
        relative = Path(str(raw["path"]))
        product = Path(*relative.parts[2:])
        if (SOURCE / product).is_file():
            files[product.as_posix()] = _sha(SOURCE / product)
    for relative in (
        "scripts/execute_nutricoach_v150_sealed_live.py",
        "scripts/nutricoach_v150_live_upgrade_boundary.py",
        "scripts/nutricoach_v150_live_upgrade_common.py",
        "scripts/nutricoach_v150_live_upgrade_state.py",
        "scripts/nutricoach_v150_phase_journal.py",
        "scripts/nutricoach_v150_sealed_authority.py",
        "scripts/nutricoach_v150_sealed_target.py",
        "scripts/verify_nutricoach_v150_preseal_v14.py",
        "tests/test_nutricoach_v150_preseal_v14.py",
    ):
        files[relative] = _sha(SOURCE / relative)
    return dict(sorted(files.items()))


def main() -> int:
    if PREFLIGHT.exists() or PRESEAL.exists():
        raise RuntimeError("v14_paths_exist")
    _ = PREFLIGHT.mkdir(parents=True)
    _ = PRESEAL.mkdir(parents=True)
    candidate = _load(MANIFEST)
    verified = verify_candidate(BASE_MANIFEST, CANDIDATE_ROOT, MANIFEST)
    if verified != CANDIDATE:
        raise RuntimeError("candidate")
    shape = _registry_shape()
    disabled_shape = shape["disabled_customer_keys"]
    if (
        shape["customer_count"] != 2
        or shape["enabled_customer_keys"] != ["pilot_20260820_01"]
        or not isinstance(disabled_shape, list)
        or len(disabled_shape) != 1
    ):
        raise RuntimeError("live_registry_shape")
    protected = PREFLIGHT / "snapshot-before.json"
    _ = shutil.copy2(PRIOR_PREFLIGHT / "snapshot-before.json", protected)
    _write(PRESEAL / "registry-shape.json", shape)
    dependency_root = PRESEAL / "dependencies/site-packages"
    predecessor_site = next(
        (PROFILE / ".strict-runtime/6c9c4394-v132/venv/lib").glob(
            "python*/site-packages"
        )
    )
    for name in ("croniter", "croniter-6.0.0.dist-info"):
        _ = shutil.copytree(
            predecessor_site / name,
            dependency_root / name,
            ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo"),
        )
    dependency_digest = dependency_snapshot_digest(dependency_root)
    wheels = [
        CANDIDATE_ROOT
        / "artifacts/build-1/hermes_agent-0.17.0-py3-none-any.whl",
        CANDIDATE_ROOT
        / "artifacts/build-1/physique_checkin_cli-0.1.0-py3-none-any.whl",
    ]
    wheel_rows: list[JsonValue] = [
        {"path": str(path), "sha256": _sha(path), "record_sha256": _record_sha(path)}
        for path in wheels
    ]
    controller_files = _controller_files(candidate)
    controller = {
        "schema": "nutricoach-v150-controller-source-manifest-v14",
        "files": controller_files,
    }
    controller_root = PRESEAL / "controller-source"
    for relative in controller_files:
        destination = controller_root / relative
        destination.parent.mkdir(parents=True, exist_ok=True)
        _ = shutil.copy2(SOURCE / relative, destination)
    _write(PRESEAL / "controller-source-manifest.json", controller)
    derivation = hashlib.sha256(canonical(controller_files)).hexdigest()
    target_root = PROFILE / ".strict-runtime/3dab1a55-v150"
    weekly = _OBJECT.validate_python({
        "capacity": 5,
        "channel_inbox_authorized": False,
        "registry_identity": "canonical-stat-and-content-binding-v1",
        "receipt_validity": {
            "issued_at": "2026-08-27T00:00:00+09:00",
            "expires_at": "2026-09-30T23:59:59+09:00",
        },
        "authority_created_paths_rollback": [
            str(PROFILE / "data/weekly-operations-authority"),
            str(target_root),
            str(target_root / "runtime-authority"),
            str(
                PROFILE
                / "data/customers/pilot_20260820_01/wizard/events.jsonl"
            ),
            str(
                PROFILE
                / "data/customers/pilot_20260820_01/wizard/.events.lock"
            ),
        ],
        "external_events_authorized": 0,
        "telegram_customer_events_authorized": 0,
        "provider_events_authorized": 0,
    })
    target_binding = _OBJECT.validate_python({
        "authority_id": AUTHORITY_ID,
        "profile_root": str(PROFILE),
        "current_runtime": str(PROFILE / ".strict-runtime/6c9c4394-v132/venv"),
        "successor_runtime": str(target_root / "venv"),
        "service_name": "hermes-gateway-dualcoachtest.service",
        "unit": str(
            Path.home() / ".config/systemd/user/hermes-gateway-dualcoachtest.service"
        ),
        "dropin": str(
            Path.home()
            / (
                ".config/systemd/user/hermes-gateway-dualcoachtest.service.d/"
                + "task26-authority.conf"
            )
        ),
        "execution_root": str(BASE / "live-executions-v14" / AUTHORITY_ID),
        "global_approval_ledger": str(BASE / "live-authorization-v14" / AUTHORITY_ID),
        "protected_inventory": str(protected),
        "dependency_snapshot": str(dependency_root),
        "dependency_snapshot_sha256": dependency_digest,
        "registry_sha256": _sha(PROFILE / "customers/registry.json"),
    })
    tombstone_path = (
        BASE / "live-authorization-v14" / R14_AUTHORITY_ID / "superseded.json"
    )
    if not tombstone_path.is_file():
        _ = tombstone_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
        _write(tombstone_path, {
            "candidate_digest": "1ee809af87e1ce256b6c9c8543ad096e190c6f58a252df80cf48dfb32d2c106e",
            "package_digest": R14_PACKAGE_DIGEST,
            "schema": "nutricoach-v150-authority-supersession-v1",
            "status": "SUPERSEDED",
            "superseded_by_authority_id": AUTHORITY_ID,
            "superseded_by_candidate_digest": CANDIDATE,
        })
        tombstone_path.chmod(0o400)
    tombstone = _load(tombstone_path)
    if (
        tombstone.get("package_digest") != R14_PACKAGE_DIGEST
        or tombstone.get("status") != "SUPERSEDED"
    ):
        raise RuntimeError("r14_tombstone")
    payload = _OBJECT.validate_python({
        "schema": "nutricoach-v150-live-upgrade-package-v14",
        "candidate_digest": CANDIDATE,
        "candidate_manifest": str(MANIFEST),
        "candidate_manifest_sha256": _sha(MANIFEST),
        "controller_derivation_sha256": derivation,
        "registry_shape_sha256": hashlib.sha256(canonical(shape)).hexdigest(),
        "protected_inventory_sha256": _sha(protected),
        "dependency_snapshot": str(dependency_root),
        "dependency_snapshot_sha256": dependency_digest,
        "registry_sha256": _sha(PROFILE / "customers/registry.json"),
        "target_binding": target_binding,
        "read_only_preflight": True,
        "superseded_authority_tombstone": str(tombstone_path),
        "superseded_authority_tombstone_sha256": _sha(tombstone_path),
        "service": _service_state(),
        "weekly_authority": weekly,
        "wheels": wheel_rows,
    })
    package_digest = hashlib.sha256(canonical(payload)).hexdigest()
    phrase = f"AUTHORIZE NUTRICOACH V1.5 LIVE UPGRADE {package_digest}"
    package: dict[str, JsonValue] = {
        "package_digest": package_digest,
        "approval_phrase": phrase,
        "payload": payload,
    }
    _write(PREFLIGHT / "package.json", package)
    supersession = _load(PRIOR_PRESEAL / "package-supersession.json")
    rows = supersession.get("superseded")
    if not isinstance(rows, list):
        raise RuntimeError("supersession")
    rows.append({
        "package_digest": supersession["active_package_digest"],
        "approval_phrase_reusable": False,
        "reason": (
            "r19 rejected because dependency verification used a read-only staging copy"
        ),
    })
    supersession["schema"] = "nutricoach-v150-package-supersession-v14"
    supersession["active_package_digest"] = package_digest
    supersession["active_package_sha256"] = _sha(PREFLIGHT / "package.json")
    supersession["active_approval_phrase"] = phrase
    _write(PRESEAL / "package-supersession.json", supersession)
    target = _OBJECT.validate_python({
        "schema": "nutricoach-v150-sealed-live-target-v14",
        "authority_id": AUTHORITY_ID,
        "approval_phrase": phrase,
        "package_digest": package_digest,
        "candidate_digest": CANDIDATE,
        "candidate_manifest": str(MANIFEST),
        "candidate_manifest_sha256": _sha(MANIFEST),
        "controller_derivation_sha256": derivation,
        "controller_target_binding": str(PRESEAL / "sealed-target.json"),
        "permission_package": str(PREFLIGHT / "package.json"),
        "permission_package_sha256": _sha(PREFLIGHT / "package.json"),
        "protected_inventory": str(protected),
        "protected_inventory_sha256": _sha(protected),
        "dependency_snapshot": str(dependency_root),
        "dependency_snapshot_sha256": dependency_digest,
        "registry_sha256": _sha(PROFILE / "customers/registry.json"),
        "profile_root": str(PROFILE),
        "current_runtime": str(PROFILE / ".strict-runtime/6c9c4394-v132/venv"),
        "successor_runtime": str(target_root / "venv"),
        "service_name": "hermes-gateway-dualcoachtest.service",
        "unit": str(
            Path.home()
            / ".config/systemd/user/hermes-gateway-dualcoachtest.service"
        ),
        "dropin": str(
            Path.home()
            / (
                ".config/systemd/user/hermes-gateway-dualcoachtest.service.d/"
                + "task26-authority.conf"
            )
        ),
        "execution_root": str(BASE / "live-executions-v14" / AUTHORITY_ID),
        "global_approval_ledger": str(BASE / "live-authorization-v14" / AUTHORITY_ID),
        "weekly_authority": weekly,
        "wheels": wheel_rows,
    })
    _write(PRESEAL / "sealed-target.json", target)
    plan = _OBJECT.validate_python({
        "schema": "nutricoach-v150-external-transaction-plan-v14",
        "authority_id": AUTHORITY_ID,
        "controller": "scripts/nutricoach_v150_detached_bootstrap.py",
        "controller_target": str(PRESEAL / "sealed-target.json"),
        "external_events_authorized": 0,
        "stages": [
            "network_isolation_gate", "sealed_target_binding",
            "protected_inventory_capture", "stop", "post_stop_snapshot",
            "protected_inventory_recheck", "stopped_probe",
            "install_exact_wheels", "off_smoke_channel_inbox_off",
            "capacity_dry_run", "weekly_and_capacity_apply",
            "weekly_startup_smoke", "switch_unit_dropin", "reload", "start",
            "post_fence",
        ],
    })
    _write(PRESEAL / "transaction-plan-v14.json", plan)
    _write(PRESEAL / "candidate-verification.json", {
        "candidate_digest": verified,
        "candidate_manifest_sha256": _sha(MANIFEST),
        "status": "PASS",
    })
    verifier = "scripts/verify_nutricoach_v150_preseal_v14.py"
    verifier_files = {
        verifier: _sha(SOURCE / verifier),
        "scripts/nutricoach_v150_detached_bootstrap.py": _sha(
            SOURCE / "scripts/nutricoach_v150_detached_bootstrap.py"
        ),
        "scripts/nutricoach_v150_live_upgrade_common.py": _sha(
            SOURCE / "scripts/nutricoach_v150_live_upgrade_common.py"
        ),
        "scripts/verify_nutricoach_v140_candidate_core.py": _sha(
            SOURCE / "scripts/verify_nutricoach_v140_candidate_core.py"
        ),
        "scripts/verify_nutricoach_v150_candidate.py": _sha(
            SOURCE / "scripts/verify_nutricoach_v150_candidate.py"
        ),
        "scripts/verify_nutricoach_v150_candidate_inputs.py": _sha(
            SOURCE / "scripts/verify_nutricoach_v150_candidate_inputs.py"
        ),
    }
    _write(PRESEAL / "verifier-source.json", {"files": verifier_files})
    _ = (PRESEAL / "README.md").write_text(
        "Frozen V14 live-representative closure. No authority is granted.\n"
    )
    entries = {
        path.relative_to(PRESEAL).as_posix(): _sha(path)
        for path in PRESEAL.rglob("*")
        if path.is_file() and path.name != "package-manifest.json"
    }
    manifest: dict[str, JsonValue] = {
        "schema": "nutricoach-v150-detached-preseal-package-v14",
        "status": "FROZEN_AWAITING_AUDIT",
        "self_exclusion": "package-manifest.json only",
        "new_package_digest": package_digest,
        "new_approval_phrase": phrase,
        "approval_consumed": False,
        "entries": dict(sorted(entries.items())),
    }
    _write(PRESEAL / "package-manifest.json", manifest)
    for path in PRESEAL.rglob("*"):
        if path.is_file() and not path.is_symlink():
            path.chmod(0o444)
    for path in sorted(
        (entry for entry in PRESEAL.rglob("*") if entry.is_dir()),
        reverse=True,
    ):
        path.chmod(0o555)
    PRESEAL.chmod(0o555)
    print(json.dumps({
        "candidate_digest": CANDIDATE,
        "package_digest": package_digest,
        "approval_phrase": phrase,
        "status": "FROZEN_AWAITING_AUDIT",
    }, sort_keys=True))
    return 0


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