#!/bin/bash
# NagLint PostToolUse hook — runs after Write/Edit on source files

NAG=/Users/matsbosson/Documents/StayThree/NagLint/target/release/nag

INPUT=$(cat -)
FILE=$(echo "$INPUT" | python3 -c "
import sys, json
d = json.load(sys.stdin)
print(d.get('tool_input', {}).get('file_path', ''))
" 2>/dev/null)

if [ -z "$FILE" ]; then
  echo "{}"
  exit 0
fi

case "$FILE" in
  *.ts|*.tsx|*.js|*.jsx|*.mjs|*.cjs|*.mts|*.cts|*.rs) ;;
  *) echo "{}"; exit 0 ;;
esac

if [ ! -f "$FILE" ]; then
  echo "{}"
  exit 0
fi

RAW=$("$NAG" "$FILE" --agent-json 2>/dev/null)

if [ "$RAW" = "{}" ] || [ -z "$RAW" ]; then
  echo "{}"
  exit 0
fi

# For .tsx/.jsx files: filter out AI-08 (logic density) — JSX is declarative
case "$FILE" in
  *.tsx|*.jsx)
    FILTERED=$(echo "$RAW" | python3 -c "
import sys, json

raw = sys.stdin.read().strip()
try:
    d = json.loads(raw)
except Exception:
    print(raw)
    sys.exit(0)

if d.get('decision') != 'block':
    print(raw)
    sys.exit(0)

reason = d.get('reason', '')
filtered_lines = [l for l in reason.splitlines() if '[AI-08]' not in l]
filtered_reason = '\n'.join(filtered_lines).strip()

if not filtered_reason:
    print('{}')
else:
    d['reason'] = filtered_reason
    ctx = d.get('hookSpecificOutput', {}).get('additionalContext', '')
    ctx_lines = [l for l in ctx.splitlines() if '[AI-08]' not in l]
    d['hookSpecificOutput']['additionalContext'] = '\n'.join(ctx_lines)
    print(json.dumps(d))
" 2>/dev/null)
    echo "${FILTERED:-$RAW}"
    ;;
  *)
    echo "$RAW"
    ;;
esac
