#!/usr/bin/env pwsh
# Linear Canal - PreToolUse Hook (Glob/Grep interceptor)
#
# 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 an error message

param()

# ── Read tool-call payload from stdin (non-blocking) ─────────────────────────
$raw     = ""
$payload = $null
try {
    if ([Console]::In.Peek() -ne -1) {
        $raw = [Console]::In.ReadToEnd()
    }
    if ($raw) {
        $payload = $raw | ConvertFrom-Json -ErrorAction Stop
    }
} catch {
    exit 0
}

# ── Only act when a Linear Canal index is present ────────────────────────────
if (-not (Test-Path ".linear_canal_data")) {
    exit 0
}

$tool      = if ($payload -and $payload.tool_name)  { $payload.tool_name }  else { "" }
$toolInput = if ($payload -and $payload.tool_input) { $payload.tool_input } else { $null }

# ── Allow when targeting the index itself (correct usage) ────────────────────
if ($toolInput) {
    $searchPath = ""
    if ($toolInput.path)    { $searchPath = [string]$toolInput.path }
    if ($toolInput.pattern) { $searchPath += " " + [string]$toolInput.pattern }

    $searchPath = $searchPath -replace "\\", "/"

    if ($searchPath -match "\.linear_canal_data" -or
        $searchPath -match "\.claude" -or
        $searchPath -match "\.claude-plugin") {
        exit 0
    }
}

# ── Resolve project ID ────────────────────────────────────────────────────────
$projectId = Get-ChildItem -Path ".linear_canal_data" -Directory -ErrorAction SilentlyContinue |
             Select-Object -First 1 -ExpandProperty Name

if (-not $projectId) { $projectId = "<unknown>" }

# ── Terminal warning (visible to user) ───────────────────────────────────────
Write-Host ""
Write-Host "  [Linear Canal] '$tool' blocked — use ctx files instead" `
           -ForegroundColor Yellow
Write-Host ""

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

exit 2
