#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Linear Canal — UserPromptSubmit Hook  [cross-platform]

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.
"""
from __future__ import annotations

import json
import os
import pathlib
import subprocess
import sys

# Force UTF-8 I/O
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")

# ── Read stdin payload ────────────────────────────────────────────────────────
try:
    raw = sys.stdin.read()
except Exception:
    raw = ""

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

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)

# ── Find semantic-inject.py (same directory as this script) ──────────────────
script_dir  = pathlib.Path(__file__).parent
inject_path = script_dir / "semantic-inject.py"

context: str | None = None

if inject_path.exists():
    try:
        result = subprocess.run(
            [sys.executable, str(inject_path)],
            input=raw,
            capture_output=True,
            text=True,
            timeout=15,
            cwd=str(pathlib.Path.cwd()),
        )
        if result.returncode == 0 and result.stdout.strip():
            context = result.stdout.strip()
    except Exception:
        pass

# ── Fallback: basic reminder if semantic inject failed ───────────────────────
if not context:
    context = (
        f"[Linear Canal active — project: {project_id}]\n"
        "MANDATORY: Read ctx files BEFORE any Glob, Grep, or raw file reads.\n\n"
        "Start here — use the Read tool on this exact path:\n"
        f"  .linear_canal_data/{project_id}/ctx/ARCHITECTURE.ctx\n\n"
        "NOTE: .linear_canal_data/ may be gitignored but IS accessible via the Read tool."
    )

# ── Output JSON structure expected by Claude Code ─────────────────────────────
response = {
    "continue": True,
    "hookSpecificOutput": {
        "hookEventName": "UserPromptSubmit",
        "additionalContext": context,
    },
}
print(json.dumps(response))
sys.exit(0)
