"""Read-only verifier for the live-representative NutriCoach V14 preseal."""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
import stat
import sys

from pydantic import JsonValue, TypeAdapter

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

from scripts.nutricoach_v150_detached_bootstrap import (
    verify_closure,
    verify_package_inventory,
)
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])
_WORKTREE = Path("/home/cube/projects/richard/.worktrees/nutricoach-v150-combined")
_EVIDENCE = Path(
    "/home/cube/projects/richard/traning coach/.omo/evidence/"
    + "nutricoach-v150-combined"
)
_BASE_MANIFEST = (
    _WORKTREE
    / (
        ".omo/evidence/nutricoach-v150-combined/task-1-candidate/inputs/"
        + "base-manifest.json"
    )
)
PRESEAL = Path(
    "/home/cube/.hermes/migrations/nutricoach-v1.5.0-combined/"
    + "live-transaction-preseal-v14-live-representative-r20"
)
CANDIDATE = "3dab1a5531c71239899c5a836f8689b9b6c59dc07ca7443de76442cf0eb5090d"
_CANDIDATE_ROOT = _EVIDENCE / "task-v14r20-candidate"
_AUTHORITY_ID = "nutricoach-v150-v14-live-representative-59-3dab1a55"
_PRIOR_R19_PACKAGE = (
    "a1e193044a227d73d7c3f805f52f7b0e16991f67cd90a94c4c0647a684b19d6e"
)
_PRIOR_R18_PACKAGE = (
    "fe048a6fb0676622a046d441d6d8cf399530c46f6db44476e20eba96282eca29"
)
_PRIOR_R17_PACKAGE = (
    "04ab3bcbb9e3ce3e1f4ddf7395162f2b97ba2a9cd5db9baf7a40d4251396ca7f"
)
_R14_AUTHORITY_ID = "nutricoach-v150-v14-live-representative-53-1ee809af"
_PRIOR_R16_PACKAGE = (
    "734f9d34f6375a797f821230777d3467a8428696c08ab53bf5d04171a07897e2"
)
_PRIOR_R14_PACKAGE = (
    "7a60506ffd66f76bfe51e1864f180a3bc597a2d67ffbc39fcf8fb247e90eaeea"
)
_PRIOR_R13_PACKAGE = (
    "14f80dbe8977fbac1ec641f8f3bed287c3ba88072f31187ad852c2a2bee5dda5"
)
_V13_PACKAGE = "25ca8f7708eb5c30d43984af8f73ebeafe191b7faeee37de1e7aead2bf7baae4"
_REJECTED_V14_PACKAGE = (
    "fa58fc80a38ca4f4d58db84db9db46ba48b842e2d12b983f4f7eee236cabd147"
)
_REQUIRED = {
    "gateway/platforms/nutrition_weekly_reminder_authority.py",
    "gateway/platforms/nutrition_weekly_reminder_bootstrap_customers.py",
    "gateway/platforms/nutrition_weekly_reminder_owner_factory.py",
    "scripts/nutricoach_v150_concrete_host.py",
    "scripts/nutricoach_v150_controller_worker.py",
    "scripts/nutricoach_v150_detached_bootstrap.py",
    "scripts/nutricoach_v150_host_operations.py",
    "scripts/nutricoach_v150_runtime_ops.py",
    "scripts/nutricoach_v150_sealed_controller.py",
    "scripts/nutricoach_v150_weekly_authority.py",
    "scripts/nutricoach_v150_weekly_startup_smoke.py",
    "tests/test_nutricoach_v150_v14_safety.py",
}


class VerificationDenied(RuntimeError):
    """Stable V14 preseal denial."""


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


def _mapping(value: JsonValue | None, label: str) -> dict[str, JsonValue]:
    if not isinstance(value, dict):
        raise VerificationDenied(label)
    return value


def _text(value: JsonValue | None, label: str) -> str:
    if not isinstance(value, str):
        raise VerificationDenied(label)
    return value


def validate_bound_contract(
    target: dict[str, JsonValue],
    package: dict[str, JsonValue],
    supersession: dict[str, JsonValue],
    registry_shape: dict[str, JsonValue],
) -> None:
    """Validate candidate, registry shape, roots, and supersession."""
    payload = _mapping(package.get("payload"), "package_payload")
    digest = _text(package.get("package_digest"), "package_digest")
    phrase = _text(package.get("approval_phrase"), "approval_phrase")
    if hashlib.sha256(canonical(payload)).hexdigest() != digest:
        raise VerificationDenied("package_digest")
    if phrase != f"AUTHORIZE NUTRICOACH V1.5 LIVE UPGRADE {digest}":
        raise VerificationDenied("approval_phrase")
    expected_paths = {
        "authority_id": _AUTHORITY_ID,
        "global_approval_ledger": str(
            PRESEAL.parent / "live-authorization-v14" / _AUTHORITY_ID
        ),
        "execution_root": str(
            PRESEAL.parent / "live-executions-v14" / _AUTHORITY_ID
        ),
        "controller_target_binding": str(PRESEAL / "sealed-target.json"),
    }
    if any(target.get(key) != value for key, value in expected_paths.items()):
        raise VerificationDenied("v14_paths")
    dependency_path = Path(
        _text(target.get("dependency_snapshot"), "dependency_snapshot")
    )
    dependency_digest = _text(
        target.get("dependency_snapshot_sha256"),
        "dependency_snapshot_sha256",
    )
    if (
        dependency_path != PRESEAL / "dependencies/site-packages"
        or dependency_snapshot_digest(dependency_path) != dependency_digest
    ):
        raise VerificationDenied("dependency_snapshot")
    if any((
        target.get("candidate_digest") != CANDIDATE,
        payload.get("candidate_digest") != CANDIDATE,
        target.get("package_digest") != digest,
        target.get("approval_phrase") != phrase,
    )):
        raise VerificationDenied("target_binding")
    bound_target = _mapping(payload.get("target_binding"), "target_binding")
    for key, value in bound_target.items():
        if target.get(key) != value:
            raise VerificationDenied("operational_target_binding")
    enabled = registry_shape.get("enabled_customer_keys")
    disabled = registry_shape.get("disabled_customer_keys")
    if (
        registry_shape.get("customer_count") != 2
        or enabled != ["pilot_20260820_01"]
        or not isinstance(disabled, list)
        or len(disabled) != 1
        or disabled == enabled
    ):
        raise VerificationDenied("registry_shape")
    if payload.get("registry_shape_sha256") != hashlib.sha256(
        canonical(registry_shape)
    ).hexdigest():
        raise VerificationDenied("registry_shape_binding")
    weekly = _mapping(payload.get("weekly_authority"), "weekly_authority")
    expected_created = [
        "/home/cube/.hermes/profiles/dualcoachtest/data/weekly-operations-authority",
        "/home/cube/.hermes/profiles/dualcoachtest/.strict-runtime/3dab1a55-v150",
        (
            "/home/cube/.hermes/profiles/dualcoachtest/.strict-runtime/"
            + "3dab1a55-v150/runtime-authority"
        ),
        (
            "/home/cube/.hermes/profiles/dualcoachtest/data/customers/"
            + "pilot_20260820_01/wizard/events.jsonl"
        ),
        (
            "/home/cube/.hermes/profiles/dualcoachtest/data/customers/"
            + "pilot_20260820_01/wizard/.events.lock"
        ),
    ]
    if (
        weekly.get("authority_created_paths_rollback") != expected_created
        or target.get("weekly_authority") != weekly
    ):
        raise VerificationDenied("created_paths")
    rows = supersession.get("superseded")
    v13 = next(
        (
            row
            for row in rows
            if isinstance(row, dict) and row.get("package_digest") == _V13_PACKAGE
        ),
        None,
    ) if isinstance(rows, list) else None
    rejected_v14 = next(
        (
            row
            for row in rows
            if isinstance(row, dict)
            and row.get("package_digest") == _REJECTED_V14_PACKAGE
        ),
        None,
    ) if isinstance(rows, list) else None
    prior_r13 = next(
        (
            row
            for row in rows
            if isinstance(row, dict)
            and row.get("package_digest") == _PRIOR_R13_PACKAGE
        ),
        None,
    ) if isinstance(rows, list) else None
    prior_r14 = next(
        (
            row
            for row in rows
            if isinstance(row, dict)
            and row.get("package_digest") == _PRIOR_R14_PACKAGE
        ),
        None,
    ) if isinstance(rows, list) else None
    prior_r16 = next(
        (
            row
            for row in rows
            if isinstance(row, dict)
            and row.get("package_digest") == _PRIOR_R16_PACKAGE
        ),
        None,
    ) if isinstance(rows, list) else None
    prior_r17 = next(
        (
            row
            for row in rows
            if isinstance(row, dict)
            and row.get("package_digest") == _PRIOR_R17_PACKAGE
        ),
        None,
    ) if isinstance(rows, list) else None
    prior_r18 = next(
        (
            row
            for row in rows
            if isinstance(row, dict)
            and row.get("package_digest") == _PRIOR_R18_PACKAGE
        ),
        None,
    ) if isinstance(rows, list) else None
    prior_r19 = next(
        (
            row
            for row in rows
            if isinstance(row, dict)
            and row.get("package_digest") == _PRIOR_R19_PACKAGE
        ),
        None,
    ) if isinstance(rows, list) else None
    if (
        supersession.get("active_package_digest") != digest
        or not isinstance(v13, dict)
        or v13.get("approval_phrase_reusable") is not False
        or not isinstance(rejected_v14, dict)
        or rejected_v14.get("approval_phrase_reusable") is not False
        or not isinstance(prior_r13, dict)
        or prior_r13.get("approval_phrase_reusable") is not False
        or not isinstance(prior_r14, dict)
        or prior_r14.get("approval_phrase_reusable") is not False
        or not isinstance(prior_r16, dict)
        or prior_r16.get("approval_phrase_reusable") is not False
        or not isinstance(prior_r17, dict)
        or prior_r17.get("approval_phrase_reusable") is not False
        or not isinstance(prior_r18, dict)
        or prior_r18.get("approval_phrase_reusable") is not False
        or not isinstance(prior_r19, dict)
        or prior_r19.get("approval_phrase_reusable") is not False
    ):
        raise VerificationDenied("v13_supersession")
    tombstone_path = (
        PRESEAL.parent
        / "live-authorization-v14"
        / _R14_AUTHORITY_ID
        / "superseded.json"
    )
    tombstone = load_document(tombstone_path)
    if (
        payload.get("superseded_authority_tombstone") != str(tombstone_path)
        or payload.get("superseded_authority_tombstone_sha256")
        != hashlib.sha256(tombstone_path.read_bytes()).hexdigest()
        or tombstone.get("status") != "SUPERSEDED"
        or tombstone.get("package_digest") != _PRIOR_R14_PACKAGE
    ):
        raise VerificationDenied("historical_authority_tombstone")


def verify() -> dict[str, JsonValue]:
    """Verify complete V14 closure without changing authority state."""
    verify_package_inventory(PRESEAL / "package-manifest.json", PRESEAL)
    for root in (PRESEAL, _CANDIDATE_ROOT):
        for path in (root, *root.rglob("*")):
            if path.is_symlink():
                raise VerificationDenied("immutable_symlink")
            mode = stat.S_IMODE(path.stat(follow_symlinks=False).st_mode)
            if mode & 0o222:
                raise VerificationDenied("immutable_mode")
    closure_document = load_document(PRESEAL / "controller-source-manifest.json")
    closure_files = _mapping(closure_document.get("files"), "closure_files")
    if not _REQUIRED.issubset(closure_files):
        raise VerificationDenied("closure_incomplete")
    closure_digest = verify_closure(
        PRESEAL / "controller-source-manifest.json",
        PRESEAL / "controller-source",
    )
    _ = verify_closure(
        PRESEAL / "verifier-source.json",
        PRESEAL / "controller-source",
        exact_inventory=False,
    )
    target = load_document(PRESEAL / "sealed-target.json")
    package_path = Path(_text(target.get("permission_package"), "package_path"))
    package_sha256 = hashlib.sha256(package_path.read_bytes()).hexdigest()
    if target.get("permission_package_sha256") != package_sha256:
        raise VerificationDenied("package_sha256")
    package = load_document(package_path)
    supersession = load_document(PRESEAL / "package-supersession.json")
    registry_shape = load_document(PRESEAL / "registry-shape.json")
    validate_bound_contract(target, package, supersession, registry_shape)
    candidate_manifest = Path(
        _text(target.get("candidate_manifest"), "candidate_manifest")
    )
    candidate = verify_candidate(_BASE_MANIFEST, _CANDIDATE_ROOT, candidate_manifest)
    if candidate != CANDIDATE:
        raise VerificationDenied("candidate")
    ledger = Path(_text(target.get("global_approval_ledger"), "ledger"))
    execution = Path(_text(target.get("execution_root"), "execution"))
    successor = Path(_text(target.get("successor_runtime"), "successor")).parent
    if ledger.exists() or execution.exists() or successor.exists():
        raise VerificationDenied("authority_touched")
    return {
        "approval_phrase": _text(package.get("approval_phrase"), "approval_phrase"),
        "candidate_digest": CANDIDATE,
        "closure_digest": closure_digest,
        "package_digest": _text(package.get("package_digest"), "package_digest"),
        "package_sha256": package_sha256,
        "status": "V14_LIVE_REPRESENTATIVE_PRESEAL_VERIFIED",
    }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    _ = parser.add_argument("--verify", action="store_true", required=True)
    _ = parser.parse_args()
    try:
        result = verify()
    except (OSError, ValueError, VerificationDenied) as error:
        print(f"DENIED:{error}")
        return 2
    print(json.dumps(result, sort_keys=True, separators=(",", ":")))
    return 0


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