#!/usr/bin/env python3
"""Run repository validation when a Codex turn stops and request one more pass if it fails."""

from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path


def main() -> int:
    try:
        payload = json.load(sys.stdin)
    except json.JSONDecodeError:
        return 0

    if payload.get("stop_hook_active"):
        return 0

    root = Path(payload.get("cwd") or ".").resolve()
    validator = root / "scripts" / "validate_workspace.py"
    if not validator.exists():
        return 0

    result = subprocess.run(
        [sys.executable, str(validator)],
        cwd=root,
        capture_output=True,
        text=True,
        timeout=240,
    )

    if result.returncode == 0:
        return 0

    summary = (result.stdout or result.stderr or "workspace validation failed").strip()
    if len(summary) > 1200:
        summary = summary[:1200].rstrip() + "..."

    json.dump(
        {
            "decision": "block",
            "reason": (
                "Validation failed. Review the output, fix the repo, then continue.\n\n"
                f"{summary}"
            ),
        },
        sys.stdout,
    )
    return 0


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