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

Fires when Claude is about to stop responding. If the conversation
involved dependency-related work but BK was never consulted, blocks
once to suggest checking BK.

Uses stop_hook_active for loop protection — only blocks the first time.
"""

import json
import sys


def main() -> None:
    try:
        stdin_data = sys.stdin.read()
        if not stdin_data.strip():
            return

        data = json.loads(stdin_data)

        # Loop protection: if stop hook already fired, allow stop
        stop_hook_active = data.get("stop_hook_active", False)
        if stop_hook_active:
            return

        # Check if BK tools were used in this conversation
        # The tool_uses field contains tools used so far in the session
        tool_uses = data.get("tool_uses", [])

        bk_was_used = False
        has_dependency_context = False

        for tool_use in tool_uses:
            tool_name = ""
            if isinstance(tool_use, dict):
                tool_name = tool_use.get("tool_name", tool_use.get("name", ""))
            elif isinstance(tool_use, str):
                tool_name = tool_use

            # Check if BK search was used
            if "bluera-knowledge" in tool_name and (
                "search" in tool_name or "get_full_context" in tool_name
            ):
                bk_was_used = True
                break

            # Check if dependency dirs were accessed (Read/Grep in node_modules etc.)
            tool_input = (
                tool_use.get("tool_input", {}) if isinstance(tool_use, dict) else {}
            )
            path = tool_input.get("path", tool_input.get("file_path", ""))
            if isinstance(path, str):
                dep_markers = (
                    "/node_modules/",
                    "/vendor/",
                    "/site-packages/",
                    "/.venv/",
                )
                if any(marker in path for marker in dep_markers):
                    has_dependency_context = True

        # If BK was used or no dependency context detected, allow stop
        if bk_was_used or not has_dependency_context:
            return

        # Block stop once — suggest checking BK
        output = {
            "decision": "block",
            "reason": (
                "You accessed dependency directories but haven't consulted Bluera Knowledge. "
                "Consider using mcp__bluera-knowledge__search to verify your answer "
                "against authoritative source code before completing."
            ),
        }
        print(json.dumps(output))

    except Exception:
        # Hooks must never crash — silent failure allows stop
        pass


if __name__ == "__main__":
    main()
