#!/bin/bash
# PostToolUse hook (matcher: Bash): auto-capture benchmark results.
# Reads hook input from stdin, pattern-matches tool_response for benchmark output.
# Appends structured results to .codeflash/results-auto.tsv.
# Observational only — always exits 0, never blocks.

set -uo pipefail

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

RESULTS_FILE="$CWD/.codeflash/results-auto.tsv"

# Nothing to capture if no response
if [ -z "$TOOL_RESPONSE" ]; then
  exit 0
fi

# Only capture if .codeflash/ directory exists (optimization session active)
if [ ! -d "$CWD/.codeflash" ]; then
  exit 0
fi

TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
CAPTURED=""

# Pattern 1: codeflash compare output (speedup table)
if echo "$TOOL_RESPONSE" | grep -q "codeflash compare\|Speedup\|speedup.*[0-9].*x" 2>/dev/null; then
  # Extract speedup values (e.g., "2.3x" or "Speedup: 1.5x")
  SPEEDUPS=$(echo "$TOOL_RESPONSE" | grep -oE '[0-9]+\.[0-9]+x' | head -3 | tr '\n' ', ' | sed 's/,$//')
  if [ -n "$SPEEDUPS" ]; then
    CAPTURED="codeflash-compare	speedup	$SPEEDUPS"
  fi
fi

# Pattern 2: hyperfine output ("Time (mean ± σ)")
if echo "$TOOL_RESPONSE" | grep -q "Time (mean" 2>/dev/null; then
  MEAN=$(echo "$TOOL_RESPONSE" | grep -oE 'Time \(mean ± σ\):\s*[0-9.]+ [a-zμ]+' | head -1 | sed 's/Time (mean ± σ):\s*//')
  if [ -n "$MEAN" ]; then
    CAPTURED="hyperfine	mean_time	$MEAN"
  fi
fi

# Pattern 3: pytest-benchmark
if echo "$TOOL_RESPONSE" | grep -q "benchmark\|--benchmark" 2>/dev/null; then
  if echo "$TOOL_RESPONSE" | grep -qE 'Mean\s+StdDev|min.*max.*mean' 2>/dev/null; then
    CAPTURED="pytest-benchmark	detected	see full output"
  fi
fi

# Pattern 4: timeit output
if echo "$TOOL_RESPONSE" | grep -qE '[0-9]+ loops?, best of [0-9]+' 2>/dev/null; then
  TIMING=$(echo "$TOOL_RESPONSE" | grep -oE '[0-9.]+ [a-zμ]+ per loop' | head -1)
  if [ -n "$TIMING" ]; then
    CAPTURED="timeit	per_loop	$TIMING"
  fi
fi

# Append to results file if we captured something
if [ -n "$CAPTURED" ]; then
  # Create header if file doesn't exist
  if [ ! -f "$RESULTS_FILE" ]; then
    echo -e "timestamp\ttool\tmetric\tvalue\tcommand" > "$RESULTS_FILE"
  fi
  # Truncate command to 100 chars for readability
  SHORT_CMD=$(echo "$COMMAND" | head -c 100)
  echo -e "$TIMESTAMP\t$CAPTURED\t$SHORT_CMD" >> "$RESULTS_FILE"
fi

exit 0
