#!/usr/bin/env python3
"""Fail-closed strict-rerun and cleanup retention gate."""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Callable, TypeVar

from retention_control import RetentionError, verify

T = TypeVar("T")


def retention_gated(proof: Path | None, action: Callable[[], T]) -> T:
    if proof is None:
        raise RetentionError("immutable retention proof is required before strict rehearsal or cleanup")
    try:
        verify(proof)
    except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError) as exc:
        raise RetentionError(f"immutable retention proof verification failed: {exc}") from exc
    return action()


def parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser()
    p.add_argument("mode", choices=("strict-rehearsal-preflight", "cleanup-preflight"))
    p.add_argument("--retention-proof", type=Path)
    return p


def main() -> int:
    args = parser().parse_args()
    try:
        result = retention_gated(args.retention_proof, lambda: {
            "schema": "task26-strict-rerun-retention-gate-v1",
            "status": "READY",
            "mode": args.mode,
            "retention_verified": True,
            "cleanup_replay_permitted": False,
        })
        print(json.dumps(result, sort_keys=True, separators=(",", ":")))
        return 0
    except (RetentionError, OSError, ValueError, KeyError, TypeError, json.JSONDecodeError) as exc:
        print(f"BLOCKED: {exc}", file=sys.stderr)
        return 2


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