#!/usr/bin/env python3
"""Independent offline verifier for the sealed Task26 invite harness v2."""
from __future__ import annotations

import hashlib
import json
import os
import shutil
import stat
import subprocess
import sys
import tempfile
from pathlib import Path

HERE = Path(__file__).resolve().parent
HARNESS = HERE / "invite_harness_v2.py"
PERMISSION = HERE / "permission-seal-v2.json"
SCHEMA = HERE / "schema-v2.json"
OPERATIONS = HERE / "OPERATIONS-v2.md"
APPROVAL = HERE / "approval-receipt.json"
PYTHON = Path("/home/cube/projects/richard/hermes-agent/.venv/bin/python")
LIVE_RESET = Path("/home/cube/.hermes/profiles/dualcoachtest/data/profile-reset-archives/task26-live-reset-2e0894ea")


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


def main() -> int:
    output = Path(sys.argv[1]) if len(sys.argv) == 2 else None
    seal = json.loads(PERMISSION.read_text())
    checks = {
        "harness_hash": sha(HARNESS) == seal["harness_sha256"],
        "schema_hash": sha(SCHEMA) == seal["schema_sha256"],
        "operations_hash": sha(OPERATIONS) == seal["operations_sha256"],
        "approval_hash": sha(APPROVAL) == seal["approval_receipt_sha256"],
        "harness_mode": stat.S_IMODE(HARNESS.stat().st_mode) == 0o500,
        "sealed_files_private": all(stat.S_IMODE(path.stat().st_mode) == 0o600 for path in (PERMISSION, SCHEMA, APPROVAL)),
        "v1_preserved": (HERE.parent / "task26-invite-harness-st_01a0056a/invite_harness.py").exists(),
    }
    with tempfile.TemporaryDirectory(prefix="task26-invite-v2-verify-") as temporary:
        root = Path(temporary)
        profile = root / "profile"
        archive = profile / "data/profile-reset-archives/task26-live-reset-2e0894ea"
        archive.mkdir(parents=True, mode=0o700)
        profile.chmod(0o700)
        (profile / "data").chmod(0o700)
        for name in ("manifest.json", "receipt.json"):
            shutil.copyfile(LIVE_RESET / name, archive / name)
            (archive / name).chmod(0o600)
        before = tuple(sorted((item.relative_to(profile).as_posix(), sha(item)) for item in profile.rglob("*") if item.is_file()))
        exits = []
        for mode in ("dry-run", "verify"):
            receipt = root / f"{mode}.json"
            result = subprocess.run(
                [str(PYTHON), "-B", str(HARNESS), mode, "--profile", str(profile),
                 "--permission", str(PERMISSION), "--receipt", str(receipt)],
                text=True, capture_output=True, check=False,
                env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"},
            )
            exits.append(result.returncode)
            checks[f"{mode}_pass"] = result.returncode == 0 and json.loads(receipt.read_text())["status"] == "PASS"
        after = tuple(sorted((item.relative_to(profile).as_posix(), sha(item)) for item in profile.rglob("*") if item.is_file()))
        checks["disposable_profile_unchanged"] = before == after
    receipt_value = {
        "schema": "task26-invite-harness-v2-independent-verification-receipt-v1",
        "status": "PASS" if all(checks.values()) else "FAIL",
        "checks": checks,
        "dry_run_verify_exit_codes": exits,
        "profile_mutations": 0 if checks["disposable_profile_unchanged"] else 1,
        "network_service_telegram_provider_git_actions": 0,
    }
    raw = json.dumps(receipt_value, sort_keys=True, separators=(",", ":")) + "\n"
    if output is not None:
        fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o600)
        with os.fdopen(fd, "w") as stream:
            stream.write(raw)
    else:
        print(raw, end="")
    return 0 if receipt_value["status"] == "PASS" else 2


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