#!/usr/bin/env -S python3 -I -B
"""Canonical, code-only verifier for the Task22 compatibility implementation."""

from __future__ import annotations

import hashlib
import json
import subprocess
import sys
from pathlib import Path
from typing import Final, cast

EVIDENCE: Final = Path(__file__).resolve().parent
VENV: Final = Path("/home/cube/projects/richard/hermes-agent/.venv")
VERIFIER: Final = EVIDENCE / "verify-task22-supplemental-candidate.py"
EXPECTED_VERIFIER_SHA256: Final = "fd57070f322f4de6a8a416d2c306652deb4313d8ba2aa44dba0aaf9e43f08bd2"
EXPECTED: Final = {
    "candidate": "3ce5b95637211b0289529c35b452cf1771fe868a34777140388a8caa75e183cc",
    "changed_paths": [
        "gateway:gateway/platforms/telegram_nutrition_onboarding_supplemental_review.py",
        "gateway:scripts/task22-supplemental-owner-review",
        "gateway:tests/gateway/test_task22_supplemental_owner_review.py",
    ],
    "freeze": "5c98ffeb84961eb91ae33e184094f2382ceff14ad6110263ffdb6ca860f23b48",
    "manifest": "e456cfc6c93d97989319818879a38237cd70c0d516ae5d2e33543a59962658e8",
    "mode": "narrow-code-only-compatibility-verification",
    "paths": 177,
    "wheel": "f592abefa3deca172c9d0b8dcb8013e0e8a1fc97ff03db4054adb3f0b6f3abf2",
    "wheel_receipt": "188a2e0451ddc52ef583d232d53f6ae51ba6db7ae4d078e50c9fe0f9df4a8663",
}


def _snapshot(path: Path, expected: str) -> None:
    if hashlib.sha256(path.read_bytes()).hexdigest() != expected:
        raise RuntimeError(f"canonical pin mismatch: {path.name}")


def main() -> int:
    if sys.flags.isolated != 1 or Path(sys.prefix) != VENV:
        raise RuntimeError("canonical verifier requires the isolated Task22 virtual environment")
    _snapshot(VERIFIER, EXPECTED_VERIFIER_SHA256)
    result = subprocess.run(
        [sys.executable, "-I", "-B", str(VERIFIER)],
        cwd=EVIDENCE,
        env={
            "HOME": "/home/cube",
            "LANG": "C.UTF-8",
            "LC_ALL": "C.UTF-8",
            "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
        },
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        check=False,
    )
    if result.returncode != 0 or result.stderr:
        raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "direct verifier failed")
    value = cast(object, json.loads(result.stdout))
    if value != EXPECTED:
        raise RuntimeError("canonical verifier result does not match exact pins")
    print(json.dumps({
        "mode": "canonical-code-only-verification",
        "ready": True,
        "successor": EXPECTED,
    }, sort_keys=True))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (OSError, RuntimeError, ValueError, json.JSONDecodeError) as exc:
        print(json.dumps({"mode": "canonical-code-only-verification", "ready": False, "error": str(exc)}, sort_keys=True), file=sys.stderr)
        raise SystemExit(1)
