#!/bin/bash
# ============================================================
# 🧠 analyze-feedback.sh
# Full automated analysis for Feedback System test failures
# ------------------------------------------------------------
#  Requirements:
#   - Gemini CLI installed and authenticated
#   - vitest output logs available (or will be generated)
#   - prompt template under ./prompts/analyze-feedback-broken.txt
# ============================================================

set -e

# --- Paths ---
PROMPT_FILE="./prompts/analyze-feedback-broken.txt"
OUTPUT_DIR="./analysis"
OUTPUT_FILE="$OUTPUT_DIR/fix_report_$(date +%Y%m%d_%H%M%S).md"
LOG_FILE="./analysis/vitest-latest.log"

# --- Ensure structure ---
mkdir -p "$OUTPUT_DIR"
mkdir -p "./prompts"

# --- 1️⃣  Create default prompt if not exist ---
if [ ! -f "$PROMPT_FILE" ]; then
  cat <<'EOF' > "$PROMPT_FILE"
You are Gemini-Engineer analyzing a partial failure in a complex feedback system written in TypeScript.

Context:
- The system implements a full feedback cycle: evaluator → policy → runner → memory → metrics.
- 83/87 tests pass successfully.
- The remaining failures are all related to "executeSafe", "safety guard", and "entropy diversity".

Tasks:
1. Parse the latest vitest log.
2. Correlate each failed test with the function that likely caused it.
3. Detect logic inversion errors (true vs false expectations) and explain their cause.
4. Suggest precise code patches (minimal diff) for each failure.
5. Output a "root cause summary" + "patch suggestions" per file.

Constraints:
- Maintain existing architecture (runner, evaluator, policy).
- Don't change test expectations; align code with them.
- Focus on error handling and state blocking order (safety > cooldown > execution).

Files of interest:
- lib/feedback/index.ts
- lib/feedback/evaluator.ts
- tests/feedback/regression.spec.ts
- tests/feedback/regression.chain.spec.ts
- tests/feedback/integration.spec.ts

Output Format:
# Root Cause Summary
...

# Patch Suggestions (by file)
```ts
// file.ts
...
```
# Confidence: (percentage)
EOF
  echo "✅ Default Gemini prompt created at $PROMPT_FILE"
fi

# --- 2️⃣  Capture fresh vitest log ---
echo "🧪 Running vitest to capture current test state..."
pnpm test:run | tee "$LOG_FILE"

# --- 3️⃣  Run Gemini CLI analysis ---
echo "🤖 Running Gemini analysis..."
gemini prompt "$PROMPT_FILE"   --context "$LOG_FILE"   --context "lib/feedback/index.ts"   --context "lib/feedback/evaluator.ts"   --context "tests/feedback/regression*.spec.ts"   --context "tests/feedback/integration.spec.ts"   --output "$OUTPUT_FILE"

# --- 4️⃣  Display summary ---
echo ""
echo "===================================================="
echo "✅ Analysis complete!"
echo "📄 Report saved to: $OUTPUT_FILE"
echo "===================================================="
echo ""
cat "$OUTPUT_FILE" | head -n 40
