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

When Claude reads a source file, inject the LC sidecar context alongside it.
EXIT 0 always — never block Read, only augment.
"""
from __future__ import annotations

import json
import pathlib
import sys

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

# ── Only act in LC-indexed projects ──────────────────────────────────────────
if not pathlib.Path(".linear_canal_data").is_dir():
    sys.exit(0)

tool_input = payload.get("tool_input") or {}
file_path  = str(tool_input.get("file_path", "") or "")
if not file_path:
    sys.exit(0)

file_path = file_path.replace("\\", "/")

# ── Allow reads of LC files, config, docs, etc. ──────────────────────────────
ALLOW_PATTERNS = (
    ".linear_canal_data",
    ".claude",
    ".LC",
    ".md",
    ".json",
    ".toml",
    ".yml",
    ".yaml",
    ".txt",
    ".env",
)
for pat in ALLOW_PATTERNS:
    if pat in file_path:
        sys.exit(0)

# ── Source file extensions that LC indexes ────────────────────────────────────
SOURCE_EXTS = {
    ".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java",
    ".php", ".rb", ".cs", ".c", ".h", ".cpp", ".hpp", ".vue",
    ".svelte", ".kt", ".swift", ".scala", ".sh",
}
ext = pathlib.Path(file_path).suffix.lower()
if ext not in SOURCE_EXTS:
    sys.exit(0)

# ── Check for sidecar file ────────────────────────────────────────────────────
sidecar_path = pathlib.Path(file_path + ".lc.md")
if sidecar_path.exists():
    try:
        sidecar = sidecar_path.read_text(encoding="utf-8", errors="replace")
        if sidecar.strip():
            print(f"[LC] Context for {file_path} (from sidecar):")
            print(sidecar)
            sys.exit(0)
    except Exception:
        pass

# ── No sidecar — emit lightweight reminder ────────────────────────────────────
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 ""
if not project_id:
    sys.exit(0)

print(f"[LC] Reading source file without sidecar context. For coding tasks:")
print(f"  Read: .linear_canal_data/{project_id}/ctx/ARCHITECTURE.ctx")
print(f"  Or call lc_context(task_description='...') via MCP")
print(f"  To generate sidecars: linear-canal watch --sidecars")
sys.exit(0)
