#!/bin/bash
# Phase 1 Test — 12 Prompts against RepoPilot
# Usage: ./scripts/test-12-prompts.sh [REPO_ID]

set -euo pipefail

REPO_ID="${1:-aceffc31-0518-4f68-b58a-8b2f89b06e87}"
API_URL="http://localhost:3000/api/agent"
RESULTS_DIR="scripts/test-results-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$RESULTS_DIR"

declare -a PROMPTS=(
  "What does class JKKHakkoSODCC do? Give me an overview of its role and responsibilities."
  "List all methods in class JKKHakkoSODCC.java with their signatures and lines of code."
  "Explain what method adchgFixOdrCtrl() does step by step."
  "What are all the SC (Service Component) calls in JKKHakkoSODCC? Group them by SC code prefix (EKK, EZM, EDK, etc.) and tell me what each group does."
  "Generate a CRUD Matrix for JKKHakkoSODCC. For each SC call, classify it as Create/Read/Update/Delete based on the Javadoc comments (照会=Read, 登録=Create, 更新=Update, 削除=Delete)."
  "Which classes call into JKKHakkoSODCC (upstream callers)? And which services does JKKHakkoSODCC call (downstream)?"
  "Analyze method callEKK0341B002SC() — what does it do, what are its parameters, and what CRUD type is it?"
  "Analyze method adchgFixOdrCtrl() in detail — what are ALL the conditional branches (if/else), what constant values are checked, and what methods are called in each branch?"
  "Analyze method opSetOdrCtrl() — this is the largest method (about 2,900 lines). Describe its main processing steps and key decision points."
  "How many methods, fields, and lines of code does class JKKHakkoSODCC have?"
  "What is the value and business meaning of constant IDO_DIV_ADCHGFIX? Which file defines it?"
  "What is the relationship between JKKHakkoSODCC and the CBSMsg classes like EKK0341B002CBSMsg? How are they used together?"
)

send_prompt() {
  local idx=$1
  local prompt=$2
  local thread_id
  thread_id=$(python3 -c "import uuid; print(uuid.uuid4())")
  local run_id
  run_id=$(python3 -c "import uuid; print(uuid.uuid4())")
  local msg_id
  msg_id=$(python3 -c "import uuid; print(uuid.uuid4())")
  local outfile="$RESULTS_DIR/prompt-$(printf '%02d' $idx).txt"

  echo "=== Prompt $idx ===" > "$outfile"
  echo "$prompt" >> "$outfile"
  echo "" >> "$outfile"
  echo "=== Response ===" >> "$outfile"

  # Build JSON payload
  local payload
  payload=$(python3 -c "
import json, sys
print(json.dumps({
    'threadId': '$thread_id',
    'runId': '$run_id',
    'repositoryId': '$REPO_ID',
    'messages': [{
        'id': '$msg_id',
        'role': 'user',
        'content': sys.argv[1]
    }],
    'tools': [],
    'context': [],
    'state': {},
    'forwardedProps': {}
}))
" "$prompt")

  # Send request and extract text content from SSE stream
  curl -s -X POST "$API_URL" \
    -H "Content-Type: application/json" \
    -H "Accept: text/event-stream" \
    -d "$payload" \
    --max-time 600 2>/dev/null | \
    grep '^data: ' | \
    sed 's/^data: //' | \
    python3 -c "
import sys, json
text_parts = []
tool_calls = []
for line in sys.stdin:
    line = line.strip()
    if not line or line == '[DONE]':
        continue
    try:
        evt = json.loads(line)
        if evt.get('type') == 'TEXT_MESSAGE_CONTENT':
            text_parts.append(evt.get('delta', ''))
        elif evt.get('type') == 'TOOL_CALL_START':
            tool_calls.append(evt.get('toolCallName', 'unknown'))
    except:
        pass
print(''.join(text_parts))
if tool_calls:
    print()
    print(f'[Tool calls: {\", \".join(tool_calls)}]')
" >> "$outfile" 2>/dev/null

  echo "" >> "$outfile"
  echo "Prompt $idx done → $outfile"
}

echo "========================================"
echo "  RepoPilot Phase 1 — 12 Prompt Test"
echo "  Repo: $REPO_ID"
echo "  Results: $RESULTS_DIR/"
echo "========================================"
echo ""

for i in $(seq 1 12); do
  idx=$((i - 1))
  echo "[$(date +%H:%M:%S)] Sending Prompt $i/12..."
  send_prompt "$i" "${PROMPTS[$idx]}"
done

echo ""
echo "========================================"
echo "  All 12 prompts complete."
echo "  Results in: $RESULTS_DIR/"
echo "========================================"
