#!/usr/bin/env python3
"""UserPromptSubmit hook for erk.

Consolidates multiple hooks into a single script:
1. Session ID injection + file persistence
2. Coding standards reminders (devrun)
3. Tripwires reminder

Reminders are opt-in via capability marker files in .erk/capabilities/.

Exit codes:
    0: All checks pass, stdout goes to Claude's context

This command is invoked via:
    ERK_HOOK_ID=user-prompt-hook erk exec user-prompt-hook
"""

from pathlib import Path

import click

from erk.core.capabilities.detection import is_reminder_installed
from erk.hooks.decorators import HookContext, hook_command

# ============================================================================
# Pure Functions for Output Building
# ============================================================================


def build_session_context(session_id: str | None) -> str:
    """Build the session ID context string.

    Pure function - string building only.
    """
    if session_id is None:
        return ""
    return f"session: {session_id}"


def build_devrun_reminder() -> str:
    """Return devrun agent reminder.

    Pure function - returns static string.
    """
    return """No direct Bash for: pytest/ty/ruff/prettier/make/gt
Use Task(subagent_type='devrun') instead."""


def build_tripwires_reminder() -> str:
    """Return tripwires context.

    Reminds Claude to check category-specific tripwires based on AGENTS.md routing.
    Universal tripwires are in AGENTS.md, category tripwires in
    docs/learned/<category>/tripwires.md.
    """
    return "Before taking ANY action covered by a tripwire, read the linked document FIRST."


def build_explore_docs_reminder() -> str:
    """Return explore-docs reminder for doc-first exploration.

    Pure function - returns static string.
    """
    return """explore-docs: When spawning Explore agents via Task tool, ALWAYS include:
"FIRST check docs/learned/index.md for existing documentation on this topic.
Read relevant docs before exploring raw files. Then explore codebase as necessary.\""""


# ============================================================================
# I/O Helper Functions
# ============================================================================


def _persist_session_id(repo_root: Path, session_id: str | None) -> None:
    """Write session ID to file.

    Args:
        repo_root: Path to the git repository root.
        session_id: The current session ID, or None if not available.
    """
    if session_id is None:
        return

    session_file = repo_root / ".erk" / "scratch" / "current-session-id"
    session_file.parent.mkdir(parents=True, exist_ok=True)
    session_file.write_text(session_id, encoding="utf-8")


# ============================================================================
# Main Hook Entry Point
# ============================================================================


@hook_command(name="user-prompt-hook")
def user_prompt_hook(ctx: click.Context, *, hook_ctx: HookContext) -> None:
    """UserPromptSubmit hook for session persistence and coding reminders.

    This hook runs on every user prompt submission in erk-managed projects.
    Reminders are opt-in via capability marker files in .erk/capabilities/.

    Exit codes:
        0: Success - context emitted to stdout
    """
    # Scope check: only run in erk-managed projects
    if not hook_ctx.is_erk_project:
        return

    # Persist session ID
    _persist_session_id(hook_ctx.repo_root, hook_ctx.session_id)

    # Build context parts - session context is always included
    context_parts = [build_session_context(hook_ctx.session_id)]

    # Add reminders based on installed capabilities
    if is_reminder_installed(hook_ctx.repo_root, "devrun"):
        context_parts.append(build_devrun_reminder())

    if is_reminder_installed(hook_ctx.repo_root, "tripwires"):
        context_parts.append(build_tripwires_reminder())

    if is_reminder_installed(hook_ctx.repo_root, "explore-docs"):
        context_parts.append(build_explore_docs_reminder())

    click.echo("\n".join(p for p in context_parts if p))


if __name__ == "__main__":
    user_prompt_hook()
