#!/usr/bin/env pwsh
# Linear Canal - PreToolUse Hook (Read interceptor)
#
# When Claude reads a source file, inject the LC sidecar context alongside it.
# EXIT 0 always — never block Read, only augment.

param()

$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 in LC-indexed projects
if (-not (Test-Path ".linear_canal_data")) { exit 0 }

$filePath = if ($payload -and $payload.tool_input -and $payload.tool_input.file_path) {
    [string]$payload.tool_input.file_path
} else { exit 0 }

# Normalize path separators
$filePath = $filePath -replace "\\", "/"

# Allow reads of LC files themselves, config, docs, etc.
$allowPatterns = @(
    "\.linear_canal_data",
    "\.claude",
    "\.LC",
    "\.md$",
    "\.json$",
    "\.toml$",
    "\.yml$",
    "\.yaml$",
    "\.txt$",
    "\.env"
)
foreach ($pat in $allowPatterns) {
    if ($filePath -match $pat) { exit 0 }
}

# Source file extensions that LC indexes
$sourceExts = @(".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java",
                ".php", ".rb", ".cs", ".c", ".h", ".cpp", ".hpp", ".vue",
                ".svelte", ".kt", ".swift", ".scala", ".sh")
$ext = [System.IO.Path]::GetExtension($filePath)
if ($ext -notin $sourceExts) { exit 0 }

# Check for sidecar file
$sidecarPath = $filePath + ".lc.md"
if (Test-Path $sidecarPath) {
    $sidecar = Get-Content $sidecarPath -Raw -ErrorAction SilentlyContinue
    if ($sidecar) {
        Write-Output "[LC] Context for $filePath (from sidecar):"
        Write-Output $sidecar
        exit 0
    }
}

# No sidecar — emit a lightweight reminder with ctx path
$projectId = Get-ChildItem -Path ".linear_canal_data" -Directory -ErrorAction SilentlyContinue |
             Select-Object -First 1 -ExpandProperty Name
if (-not $projectId) { exit 0 }

$basename = [System.IO.Path]::GetFileNameWithoutExtension($filePath)
Write-Output "[LC] Reading source file without sidecar context. For coding tasks:"
Write-Output "  Read: .linear_canal_data/$projectId/ctx/ARCHITECTURE.ctx"
Write-Output "  Or call lc_context(task_description='...') via MCP"
Write-Output "  To generate sidecars: linear-canal watch --sidecars"
exit 0
