"""PreToolUse hook: block PR creation without passing tests.

Matcher: Bash

Reads tool_input from stdin (JSON). If command matches 'gh pr create':
1. Get current branch, extract task ID
2. If no task ID (not on a task branch) → allow
3. Check all_tests_passing(task_id)
4. If tests haven't passed → deny

This is the core guarantee: no PR without locally passing tests.
"""

import json
import re
import sys

from peon_mcp.hooks.common import all_tests_passing, extract_task_id_from_branch


def main() -> None:
    try:
        raw = sys.stdin.read()
        event = json.loads(raw)
    except (json.JSONDecodeError, IOError):
        sys.exit(0)

    tool_input = event.get("tool_input", {})
    command = tool_input.get("command", "")

    # Only gate on 'gh pr create' commands
    if not re.search(r"\bgh\s+pr\s+create\b", command):
        sys.exit(0)

    # Extract task ID from current branch
    try:
        task_id = extract_task_id_from_branch()
    except Exception:
        # Can't determine branch → fail-open
        sys.exit(0)

    if task_id is None:
        # Not on a task branch → allow
        sys.exit(0)

    # Check test results
    try:
        if all_tests_passing(task_id):
            sys.exit(0)
    except Exception:
        # API unreachable → fail-open
        sys.exit(0)

    # Tests not passing → block
    response = {
        "decision": "block",
        "reason": f"Cannot create PR: tests have not all passed for task #{task_id}. Run tests and ensure all pass before creating a PR."
    }
    print(json.dumps(response))
    sys.exit(0)


if __name__ == "__main__":
    main()
