#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Linear Canal — PreToolUse Hook (Glob/Grep interceptor)  [cross-platform]

Fires before Glob and Grep tool calls.
Blocks raw source exploration and tells Claude to use the indexed ctx files.

Exit 0 = allow the tool call to proceed
Exit 2 = block the tool call; stdout is shown to Claude as feedback
"""
from __future__ import annotations

import json
import pathlib
import sys

# ── Read stdin payload ────────────────────────────────────────────────────────
try:
    raw = sys.stdin.read()
    payload: dict = json.loads(raw) if raw.strip() else {}
except Exception:
    sys.exit(0)

# ── Only act when a Linear Canal index is present ────────────────────────────
if not pathlib.Path(".linear_canal_data").is_dir():
    sys.exit(0)

tool       = payload.get("tool_name", "")
tool_input = payload.get("tool_input") or {}

# ── Allow when targeting the index itself (correct usage) ────────────────────
search_path = ""
if tool_input.get("path"):
    search_path += str(tool_input["path"])
if tool_input.get("pattern"):
    search_path += " " + str(tool_input["pattern"])
search_path = search_path.replace("\\", "/")

for skip in (".linear_canal_data", ".claude", ".claude-plugin"):
    if skip in search_path:
        sys.exit(0)

# ── Resolve project ID ────────────────────────────────────────────────────────
lc_dir   = pathlib.Path(".linear_canal_data")
subdirs  = [d for d in lc_dir.iterdir() if d.is_dir()]
project_id = subdirs[0].name if subdirs else "<unknown>"

# ── Terminal warning (visible to user) ───────────────────────────────────────
print(f"\n  [Linear Canal] '{tool}' blocked — use ctx files instead\n", file=sys.stderr)

# ── Message for Claude (exit 2 makes Claude see stdout) ──────────────────────
print("[Linear Canal] Raw exploration blocked.")
print()
print(f"This project is indexed by Linear Canal (project: {project_id}).")
print(f"Do NOT use {tool} — read the pre-compiled ctx files instead.")
print()
print("NOTE: .linear_canal_data/ may appear gitignored but IS accessible on disk.")
print("Use the Read tool directly with these paths (do NOT Glob for them):")
print()
print(f"  Read: .linear_canal_data/{project_id}/ctx/ARCHITECTURE.ctx   <- START HERE")
print(f"  Read: .linear_canal_data/{project_id}/ctx/INTERFACES.ctx")
print(f"  Read: .linear_canal_data/{project_id}/ctx/RISKS.ctx")
print(f"  Read: .linear_canal_data/{project_id}/ctx/<module-name>.ctx")
print()
print(f"This saves 80-95% of tokens vs raw {tool} on source files.")
sys.exit(2)
