#!/bin/bash
# UserPromptSubmit hook: auto-detect project context and inject on first prompt.
# Uses a sentinel file to run detection only once per session.
# Outputs JSON with additionalContext for Claude's context.

set -uo pipefail

INPUT=$(cat)
eval "$(echo "$INPUT" | jq -r '
  @sh "CWD_RAW=\(.cwd // "")",
  @sh "SESSION_ID=\(.session_id // "unknown")"
' 2>/dev/null)"
CWD="${CWD_RAW:-${CLAUDE_PROJECT_DIR:-$(pwd)}}"

CODEFLASH_DIR="$CWD/.codeflash"
SENTINEL="$CODEFLASH_DIR/.context-injected-$SESSION_ID"

# Only run once per session
if [ -f "$SENTINEL" ]; then
  exit 0
fi

# Collect context fragments
CONTEXT=""

# 1. Previous session state from HANDOFF.md
if [ -f "$CODEFLASH_DIR/HANDOFF.md" ]; then
  PHASE=$(grep -i '^\#*\s*phase:\?\s*' "$CODEFLASH_DIR/HANDOFF.md" 2>/dev/null | head -1 | sed 's/^#*\s*[Pp]hase:\?\s*//' | xargs)
  if [ -n "$PHASE" ]; then
    CONTEXT="Previous optimization session detected (phase: $PHASE). Read .codeflash/HANDOFF.md for full state."
  fi
fi

# 2. Experiment history from results.tsv
if [ -f "$CODEFLASH_DIR/results.tsv" ]; then
  TOTAL=$(tail -n +2 "$CODEFLASH_DIR/results.tsv" 2>/dev/null | grep -c '[^\s]' 2>/dev/null || echo 0)
  KEEPS=$(tail -n +2 "$CODEFLASH_DIR/results.tsv" 2>/dev/null | grep -ci 'keep' 2>/dev/null || echo 0)
  if [ "$TOTAL" -gt 0 ] 2>/dev/null; then
    CONTEXT="$CONTEXT Experiment history: $TOTAL total, $KEEPS keeps."
  fi
fi

# 3. Setup info
if [ -f "$CODEFLASH_DIR/setup.md" ]; then
  RUNNER=$(grep -i 'runner\|python' "$CODEFLASH_DIR/setup.md" 2>/dev/null | head -1 | xargs)
  if [ -n "$RUNNER" ]; then
    CONTEXT="$CONTEXT Setup: $RUNNER"
  fi
fi

# 4. Auto-detect project environment (only if no setup.md)
if [ ! -f "$CODEFLASH_DIR/setup.md" ]; then
  PYVER=$(python3 --version 2>/dev/null | head -1)
  PKG_MGR=""
  if [ -f "$CWD/uv.lock" ]; then PKG_MGR="uv"
  elif [ -f "$CWD/poetry.lock" ]; then PKG_MGR="poetry"
  elif [ -f "$CWD/Pipfile.lock" ]; then PKG_MGR="pipenv"
  elif [ -f "$CWD/requirements.txt" ]; then PKG_MGR="pip"
  fi

  if [ -n "$PYVER" ] || [ -n "$PKG_MGR" ]; then
    DETECT="Detected: ${PYVER:-Python unknown}"
    if [ -n "$PKG_MGR" ]; then
      DETECT="$DETECT, package manager: $PKG_MGR"
    fi
    CONTEXT="$CONTEXT $DETECT"
  fi
fi

# If nothing to inject, exit silently
if [ -z "$CONTEXT" ]; then
  exit 0
fi

# Write sentinel to prevent re-running
mkdir -p "$CODEFLASH_DIR"
touch "$SENTINEL"

# Output context — plain text to stdout goes into Claude's context
echo "$CONTEXT"

exit 0
