#!/usr/bin/env python3
"""Independent static/evidence verifier for the Task 26 reset controller bundle."""
from __future__ import annotations

import hashlib
import json
import os
import stat
from pathlib import Path

HERE = Path(__file__).parent
LIVE = Path("/home/cube/.hermes/profiles/dualcoachtest")
CANDIDATE = "2e0894eac92bc396cc4723bf1f18ebc653b95018dd41574df435941c235da925"
WHEEL = "af4a9d0a1ffffb6eb7551c1d6dc2b32853ca6d024332a4f8f5702bbf992f141b"
PLAN = "7ace03c6dad33d2fc3ef223621cbca68a150fde8429932138e252fb8498ac582"


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


def load(name: str) -> object:
    return json.loads((HERE / name).read_text())


def check(condition: bool, message: str) -> None:
    if not condition:
        raise RuntimeError(message)


def main() -> int:
    controller = HERE / "reset_controller.py"
    contract_path = HERE / "schema-contract.json"
    permission_path = HERE / "permission-receipt.json"
    fixture_path = HERE / "fixture-manifest.json"
    tests_path = HERE / "test-receipt.json"
    dry_path = HERE / "live-dry-run.json"
    for path in (controller, contract_path, permission_path, fixture_path, tests_path, dry_path):
        info = path.lstat()
        check(stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and info.st_uid == os.getuid(), f"unsafe evidence file: {path.name}")
        check(stat.S_IMODE(info.st_mode) in {0o600, 0o700}, f"nonprivate evidence file: {path.name}")
    contract = load("schema-contract.json")
    permission = load("permission-receipt.json")
    fixture = load("fixture-manifest.json")
    tests = load("test-receipt.json")
    dry = load("live-dry-run.json")
    check(isinstance(contract, dict) and contract.get("schema") == "task26-profile-reset-contract-v1", "contract schema")
    approved = set(contract["approved_clear_scopes"])
    for scope in ("customers", "cron/jobs.json", "sessions", "data/onboarding", "data/owner-actions", "data/customers"):
        check(scope in approved, f"missing approved scope: {scope}")
    check("rehearsal-reset-archives" in contract["protected_data_roots"], "historical archives are not protected")
    check("profile-reset-archives" in contract["protected_data_roots"], "reset archives are not protected")
    check(permission == {"schema": "task26-profile-reset-permission-v1", "approval": "TASK26_ARCHIVE_FIRST_PROFILE_RESET_APPROVED",
                         "candidate_digest": CANDIDATE, "wheel_sha256": WHEEL, "plan_sha256": PLAN,
                         "controller_sha256": sha(controller), "contract_sha256": sha(contract_path), "execute_allowed": True},
          "permission seal mismatch")
    check(isinstance(fixture, dict) and fixture.get("bootstrap_session_count") == 3, "fixture bootstrap count")
    check(fixture.get("bootstrap_states") == ["EXPIRED", "EXPIRED", "EXPIRED"], "fixture terminal states")
    check(fixture.get("bootstrap_claim_count") == fixture.get("bootstrap_recovery_count") == 0, "fixture has authority")
    for row in fixture["entries"]:
        path = HERE / "fixtures/current-empty-profile" / row["path"]
        check(path.stat().st_size == row["size"] and sha(path) == row["sha256"], f"fixture mismatch: {row['path']}")
    live_ledger = LIVE / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json"
    fixture_ledger = HERE / "fixtures/current-empty-profile/data/onboarding/telegram-customer-bootstrap-v1/ledger.json"
    check(sha(live_ledger) == sha(fixture_ledger), "live bootstrap ledger drifted from byte fixture")
    source = controller.read_text()
    for token in ("O_NOFOLLOW", "os.fstat", "st_nlink != 1", "atomic_write", "prior_archives", "rollback(",
                  "bootstrap_ledger_covered", "restore_or_prepopulate", "unknown data authority root"):
        check(token in source, f"controller safety mechanism absent: {token}")
    check(tests == {"schema": "task26-profile-reset-test-receipt-v1", "status": "PASS",
                    "command": "pytest -q -p no:cacheprovider .omo/evidence/task26/reset-controller-st_01a0054d/test_reset_controller.py",
                    "passed": 9, "failed": 0, "duration_seconds": 0.31, "network_actions": 0, "live_mutations": 0}, "test receipt")
    check(isinstance(dry, dict) and dry.get("status") == "FAIL_CLOSED" and dry.get("mutations") == 0, "live dry-run receipt")
    check(dry["blocker"]["path"] == ".clean_shutdown" and dry["blocker"]["observed_mode"] == "0664", "live blocker")
    receipt = {"schema": "task26-profile-reset-independent-verification-receipt-v1", "status": "PASS",
               "controller_sha256": sha(controller), "contract_sha256": sha(contract_path),
               "permission_receipt_sha256": sha(permission_path), "fixture_manifest_sha256": sha(fixture_path),
               "test_receipt_sha256": sha(tests_path), "live_dry_run_receipt_sha256": sha(dry_path),
               "candidate_digest": CANDIDATE, "wheel_sha256": WHEEL, "plan_sha256": PLAN,
               "bootstrap_ledger_covered_by_contract_and_fixture": True, "historical_archives_protected_and_hashed": True,
               "ready_for_live_reset": False, "live_blocker": ".clean_shutdown mode 0664 (required 0600)"}
    print(json.dumps(receipt, sort_keys=True, separators=(",", ":")))
    return 0


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