#!/usr/bin/python3
"""
Checkpoint Reminder Hook (PostToolUse)

Fires AFTER any Write to an episode file.
If the episode completes a batch (ep 5, 10, 15, etc.), outputs a STOP reminder.

This is a safety net to ensure checkpoints are run between batches.
"""

import json
import sys
import re
from pathlib import Path

# Add engine tools to path for imports
_SCRIPT_DIR = Path(__file__).parent.resolve()
_ENGINE_TOOLS = _SCRIPT_DIR.parent.parent / 'tools'
if _ENGINE_TOOLS.exists():
    sys.path.insert(0, str(_ENGINE_TOOLS))

try:
    from engine_constants import GENERATION_BATCH_SIZE
except ImportError:
    GENERATION_BATCH_SIZE = 5


def get_episode_number(filepath):
    """Extract episode number from filepath like ep_042.md"""
    match = re.search(r'ep_(\d{3})\.md', filepath)
    if match:
        return int(match.group(1))
    return None


def get_batch_number(ep_num):
    """Episodes 1-5 = batch 1, 6-10 = batch 2, etc."""
    return ((ep_num - 1) // GENERATION_BATCH_SIZE) + 1


def is_batch_complete(ep_num):
    """Returns True if this episode completes a batch (5, 10, 15, etc.)"""
    return ep_num % GENERATION_BATCH_SIZE == 0


def get_project_name(filepath):
    """Extract project name from path."""
    path = Path(filepath)
    # Walk up to find the project root (parent of /episodes/)
    for parent in path.parents:
        if parent.name == "episodes":
            return parent.parent.name
    return "unknown"


def main():
    # Read hook input from stdin
    try:
        hook_input = json.load(sys.stdin)
    except (json.JSONDecodeError, ValueError, EOFError):
        sys.exit(0)

    tool_name = hook_input.get("tool_name", "")
    tool_input = hook_input.get("tool_input", {})

    # Only check Write operations
    if tool_name != "Write":
        sys.exit(0)

    file_path = tool_input.get("file_path", "")

    # Only check episode files
    if "/episodes/ep_" not in file_path or not file_path.endswith(".md"):
        sys.exit(0)

    ep_num = get_episode_number(file_path)
    if ep_num is None:
        sys.exit(0)

    # Check if this completes a batch
    if is_batch_complete(ep_num):
        batch_num = get_batch_number(ep_num)
        project_name = get_project_name(file_path)

        # Output reminder (this will be shown to Claude)
        print(f"""
╔══════════════════════════════════════════════════════════════════╗
║  🛑 BATCH {batch_num} COMPLETE - CHECKPOINT REQUIRED                     ║
╠══════════════════════════════════════════════════════════════════╣
║                                                                  ║
║  You just wrote episode {ep_num}. Batch {batch_num} is complete.               ║
║                                                                  ║
║  ▶ STOP AND RUN THIS COMMAND NOW:                                ║
║                                                                  ║
║    python3 .claude/hooks/save_checkpoint.py ./{project_name} {batch_num}      ║
║                                                                  ║
║  DO NOT write episode {ep_num + 1} until checkpoint passes.               ║
║  The enforcement hook will BLOCK further writes anyway.          ║
║                                                                  ║
╚══════════════════════════════════════════════════════════════════╝
""")

    sys.exit(0)


if __name__ == "__main__":
    main()
