#!/usr/bin/env python3
"""
PostToolUse hook for bluera-knowledge plugin.

Fires after WebSearch tool calls. Checks if the search query relates to a
library that is already indexed in BK, and if so reminds Claude to use BK
search instead of relying solely on web results.

Deduplicates per-project so the same store only triggers once per hour.
"""

import hashlib
import json
import os
import sys
import time
from pathlib import Path


# How long (seconds) before a seen store can trigger again
DEDUP_TTL = 3600  # 1 hour

# Minimum store name length to avoid false positives on short names
MIN_STORE_NAME_LEN = 3


def get_stores_path() -> Path | None:
    """Get path to stores.json from project root."""
    project_root = os.environ.get("PROJECT_ROOT") or os.environ.get("PWD")
    if not project_root:
        return None
    return Path(project_root) / ".bluera" / "bluera-knowledge" / "data" / "stores.json"


def load_stores() -> list[dict]:
    """Load stores from stores.json. Returns empty list on error."""
    stores_path = get_stores_path()
    if stores_path is None or not stores_path.exists():
        return []
    try:
        with open(stores_path, encoding="utf-8") as f:
            data = json.load(f)
        if isinstance(data, dict):
            stores = data.get("stores", [])
            return stores if isinstance(stores, list) else []
        return data if isinstance(data, list) else []
    except (json.JSONDecodeError, IOError, OSError):
        return []


def _dedup_path(project_root: str) -> str:
    """Return the path to the per-project dedup file."""
    h = hashlib.md5(project_root.encode()).hexdigest()[:8]
    return f"/tmp/bk-websearch-{h}.json"


def is_already_seen(store_name: str, project_root: str) -> bool:
    """Check if this store was already flagged within the TTL."""
    try:
        path = _dedup_path(project_root)
        with open(path) as f:
            seen: dict[str, float] = json.load(f)
        ts = seen.get(store_name, 0)
        return (time.time() - ts) < DEDUP_TTL
    except Exception:
        return False


def mark_seen(store_name: str, project_root: str) -> None:
    """Record this store as seen, pruning expired entries."""
    try:
        path = _dedup_path(project_root)
        now = time.time()
        seen: dict[str, float] = {}
        try:
            with open(path) as f:
                seen = json.load(f)
        except Exception:
            pass
        seen = {k: v for k, v in seen.items() if (now - v) < DEDUP_TTL}
        seen[store_name] = now
        with open(path, "w") as f:
            json.dump(seen, f)
    except Exception:
        pass


def find_matching_stores(query: str, stores: list[dict]) -> list[str]:
    """Find store names that appear in the search query."""
    query_lower = query.lower()
    matched = []
    for store in stores:
        name = store.get("name", "")
        if len(name) < MIN_STORE_NAME_LEN:
            continue
        if name.lower() in query_lower:
            matched.append(name)
    return matched


def main() -> int:
    try:
        stdin_data = sys.stdin.read()
        if not stdin_data.strip():
            return 0
        hook_input = json.loads(stdin_data)

        tool_name = hook_input.get("tool_name", "")
        if tool_name != "WebSearch":
            return 0

        tool_input = hook_input.get("tool_input", {})
        query = tool_input.get("query", "")
        if not query:
            return 0

        stores = load_stores()
        if not stores:
            return 0

        matched = find_matching_stores(query, stores)
        if not matched:
            return 0

        project_root = os.environ.get("PROJECT_ROOT", os.environ.get("PWD", ""))

        # Filter out already-seen stores
        unseen = [s for s in matched if not is_already_seen(s, project_root)]
        if not unseen:
            return 0

        for store_name in unseen:
            mark_seen(store_name, project_root)

        store_list = ", ".join(unseen)
        message = (
            f"You searched the web for a topic related to indexed libraries: {store_list}\n"
            f"You have authoritative source code indexed in Bluera Knowledge.\n"
            f"Use mcp__bluera-knowledge__search to get definitive answers from the actual source:\n"
            f"  mcp__bluera-knowledge__search(query='{query}', intent='find-implementation')\n"
            f"This is faster and more accurate than web results."
        )

        output = {
            "hookSpecificOutput": {
                "hookEventName": "PostToolUse",
                "additionalContext": message,
            }
        }
        print(json.dumps(output))
        return 0

    except Exception:
        return 0


if __name__ == "__main__":
    raise SystemExit(main())
