#!/usr/bin/env pwsh
# Linear Canal - UserPromptSubmit Hook
#
# Fires before every user prompt is processed by Claude Code.
# Calls semantic-inject.py to run vector search + ctx keyword match and
# inject relevant context BEFORE Claude processes the query.
# Zero tool calls needed from Claude's side.

param()

# ── Read stdin payload (non-blocking) ────────────────────────────────────────
$raw = ""
try {
    if ([Console]::In.Peek() -ne -1) {
        $raw = [Console]::In.ReadToEnd()
    }
} catch { }

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

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

if (-not $projectId) {
    exit 0
}

# ── Find Python ───────────────────────────────────────────────────────────────
$python = $null
foreach ($candidate in @("python", "python3")) {
    $found = Get-Command $candidate -ErrorAction SilentlyContinue
    if ($found) { $python = $found.Source; break }
}

# ── Run semantic-inject.py ────────────────────────────────────────────────────
$context = $null
$scriptPath = Join-Path $PSScriptRoot "semantic-inject.py"

if ($python -and (Test-Path $scriptPath)) {
    try {
        if ($raw) {
            $context = ($raw | & $python $scriptPath 2>$null) -join "`n"
        } else {
            $context = (& $python $scriptPath 2>$null) -join "`n"
        }
    } catch {
        $context = $null
    }
}

# ── Fallback: basic reminder if Python failed or no output ────────────────────
if (-not $context -or $context.Trim() -eq "") {
    $context = @"
[Linear Canal active — project: $projectId]
MANDATORY: Read ctx files BEFORE any Glob, Grep, or raw file reads.

Start here — use the Read tool on this exact path:
  .linear_canal_data/$projectId/ctx/ARCHITECTURE.ctx

NOTE: .linear_canal_data/ may be gitignored but IS accessible via the Read tool.
"@
}

# ── Output JSON structure expected by Claude Code ─────────────────────────────
$response = [ordered]@{
    continue           = $true
    hookSpecificOutput = [ordered]@{
        hookEventName     = "UserPromptSubmit"
        additionalContext = $context
    }
} | ConvertTo-Json -Compress -Depth 5

Write-Output $response
exit 0
