"""
UserPromptSubmit Hook

Called when user submits a prompt. Records the chunk start position
so we know where to start reading the JSONL for triage.
"""

import os
import sys
from pathlib import Path

# Skip if this is a CodeContext subprocess (prevents recursive hooks)
if os.environ.get("CODECONTEXT_SUBPROCESS") == "1":
    sys.exit(0)

# Add parent to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))

from hooks.state import ChunkState, find_jsonl_for_session, get_current_jsonl_path


def on_user_prompt_submit(event_data: dict) -> None:
    """
    Handle UserPromptSubmit event.

    Args:
        event_data: Event data from Claude Code containing:
            - session_id: Current session ID
            - prompt: The user's prompt text
            - cwd: Current working directory (project path)
            - transcript_path: Direct path to JSONL file (preferred)
    """
    session_id = event_data.get("session_id", "unknown")
    user_prompt = event_data.get("prompt", "")

    # Get project path - env var (set by Claude) or cwd from stdin event
    project_path = os.environ.get("CLAUDE_PROJECT_DIR") or event_data.get("cwd", "")

    # Use transcript_path directly if provided (most reliable)
    jsonl_path = event_data.get("transcript_path")

    # Fallback: try to find JSONL path by session_id
    if not jsonl_path and session_id != "unknown":
        found_path = find_jsonl_for_session(session_id, project_path)
        if found_path:
            jsonl_path = str(found_path)

    # Final fallback: get most recent JSONL
    if not jsonl_path:
        current = get_current_jsonl_path()
        if current:
            jsonl_path = str(current)

    # Create and save state
    state = ChunkState.create(
        session_id=session_id,
        project_path=project_path,
        user_prompt=user_prompt,
        jsonl_path=jsonl_path
    )
    state.save()

    # Truncate prompt for display
    prompt_preview = user_prompt[:50] + "..." if len(user_prompt) > 50 else user_prompt
    prompt_preview = prompt_preview.replace("\n", " ")

    print(f"[CodeContext] Chunk started: {prompt_preview}")


# Entry point - reads from stdin when called by Claude Code hooks
if __name__ == "__main__":
    import json

    try:
        # Claude Code passes event data via stdin as JSON
        input_data = sys.stdin.read()

        if input_data.strip():
            event = json.loads(input_data)

            # Map Claude Code's field names to our expected format
            # UserPromptSubmit provides: session_id, prompt, cwd, transcript_path
            # Note: CLAUDE_PROJECT_DIR is only in env var, not stdin (see docs/claude-hook-event-data.md)
            event_data = {
                "session_id": event.get("session_id", "unknown"),
                "prompt": event.get("prompt", ""),
                "cwd": event.get("cwd", ""),
                "transcript_path": event.get("transcript_path"),
            }

            on_user_prompt_submit(event_data)
        else:
            # No stdin - might be manual test
            print("[CodeContext] No event data received via stdin", file=sys.stderr)
            sys.exit(0)

    except json.JSONDecodeError as e:
        print(f"[CodeContext] JSON parse error: {e}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"[CodeContext] Hook error: {e}", file=sys.stderr)
        sys.exit(1)
