# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Hook input parsing — extract search query from file paths and hook events."""

from pathlib import Path


def _query_from_filepath(file_path: str) -> str:
    """Build a search query from a file path."""
    p = Path(file_path)
    name = p.stem.replace("_", " ").replace("-", " ")
    parent = p.parent.name
    if parent and parent not in (".", "", "Tools", "Daemons", "Utilities"):
        return f"{name} {parent.replace('_', ' ')}".strip()
    return name.strip()


def _query_from_hook(hook_input: dict) -> str:
    """Extract search query from Claude Code hook stdin JSON."""
    event = hook_input.get("hook_event_name", "")

    if event in ("UserPromptSubmit", "BeforeAgent"):
        raw = hook_input.get("prompt", "")[:200].strip()
        return raw.encode("utf-8", errors="replace").decode("utf-8", errors="replace")

    # PreToolUse: Edit or Write
    tool_input = hook_input.get("tool_input", {})
    file_path = tool_input.get("file_path", "")
    if file_path:
        query = _query_from_filepath(file_path)
        # Enrich with actual content being written/edited so the brain
        # query reflects what the agent is doing, not just the filename.
        content_snippet = (
            tool_input.get("new_string", "")   # Edit tool
            or tool_input.get("content", "")   # Write tool
        )
        if content_snippet:
            snippet = content_snippet[:150].strip().replace("\n", " ")
            query = f"{query} {snippet}".strip()
        return query

    # Fallback: try command for Bash hooks
    command = tool_input.get("command", "")
    if command:
        return command[:100].strip()

    return ""


def _tier_from_model(model: str) -> str:
    """Map model ID string to task tier (fast/standard/premium)."""
    m = (model or "").lower()
    if "opus" in m:
        return "premium"
    if "haiku" in m or "flash" in m or "mini" in m:
        return "fast"
    if "sonnet" in m or "pro" in m or "gemini" in m:
        return "standard"
    return ""


def _tier_from_hook(hook_input: dict) -> str:
    """Extract model tier from Claude Code hook stdin JSON."""
    model = hook_input.get("model", "") or hook_input.get("model_id", "")
    return _tier_from_model(str(model))
