#!/usr/bin/env bash
# Auto-generated by transpile plugin — runs on SessionStart.
# 1) Installs the transpile binary if missing
# 2) Writes the PostToolUse hook script to ~/.claude/

set -euo pipefail

# Skip on native Windows (non-WSL) — no bash/python3/wc available
case "$(uname -s 2>/dev/null)" in
  MINGW*|MSYS*|CYGWIN*) exit 0 ;;
esac

HOOK_DEST="$HOME/.claude/transpile-hook.sh"

# ── 1. Ensure transpile binary is installed ────────────────────────────────────
if ! command -v transpile >/dev/null 2>&1; then
  echo "[transpile plugin] transpile not found — installing..."
  if command -v cargo-binstall >/dev/null 2>&1; then
    cargo binstall -y --no-confirm llm-transpile
  elif command -v cargo >/dev/null 2>&1; then
    cargo install llm-transpile
  else
    echo "[transpile plugin] ERROR: cargo not found. Install Rust from https://rustup.rs then restart Claude Code." >&2
    exit 0  # non-fatal — don't break the session
  fi
fi

# ── 2. Write PostToolUse hook script (idempotent) ─────────────────────────────
SCRIPT=$(transpile --print-hook-script 2>/dev/null) || true

# Fallback: embed the script directly if --print-hook-script not supported yet
if [ -z "$SCRIPT" ]; then
SCRIPT='#!/usr/bin/env bash
set -euo pipefail
THRESHOLD=${TRANSPILE_THRESHOLD:-8192}
INPUT=$(cat)
FILE=$(printf '"'"'%s'"'"' "$INPUT" | python3 -c "
import json, sys
d = json.load(sys.stdin)
print(d.get('"'"'tool_input'"'"', {}).get('"'"'file_path'"'"', '"'"''"'"'))
" 2>/dev/null) || exit 0
[ -z "$FILE" ] && exit 0
[ -f "$FILE" ] || exit 0
BYTES=$(wc -c < "$FILE" 2>/dev/null || echo 0)
[ "$BYTES" -lt "$THRESHOLD" ] && exit 0
export TRANSPILE_AGENT=claude
JSON_OUT=$(transpile --input "$FILE" --fidelity semantic --json 2>/dev/null) || exit 0
[ -z "$JSON_OUT" ] && exit 0
FNAME=$(basename "$FILE")
python3 -c "
import json, sys

data  = json.loads(sys.argv[1])
fname = sys.argv[2]
size  = sys.argv[3]

content = data.get('"'"'content'"'"', '"'"''"'"')
inp     = data.get('"'"'input_tok'"'"', 0)
out     = data.get('"'"'output_tok'"'"', 0)
pct     = data.get('"'"'reduction_pct'"'"', '"'"'0'"'"')
saved   = inp - out

msg = (
    f'"'"'[llm-transpile] {fname} ({size}B) \u2192 {inp} tok \u2192 {out} tok '"'"'
    f'"'"'({pct}% reduction, {saved} tokens saved)\n\n{content}'"'"'
)
print(json.dumps({'"'"'additionalContext'"'"': msg}))
" "$JSON_OUT" "$FNAME" "$BYTES" 2>/dev/null || exit 0
'
fi

# Write only if different
EXISTING=$(cat "$HOOK_DEST" 2>/dev/null || true)
if [ "$EXISTING" != "$SCRIPT" ]; then
  mkdir -p "$(dirname "$HOOK_DEST")"
  printf '%s\n' "$SCRIPT" > "$HOOK_DEST"
  chmod +x "$HOOK_DEST"
fi

exit 0
