#!/bin/bash
#
# Context Recall Test Script
# Tests all aspects of the context recall system
#
# Usage: bash scripts/test-context-recall.sh
#

set -e

echo "=========================================="
echo "Context Recall System Test"
echo "=========================================="
echo ""

# Detect project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
CONFIG_FILE="$PROJECT_ROOT/.claude/context-recall-config.env"

# Load configuration
if [ ! -f "$CONFIG_FILE" ]; then
    echo "[ERROR] ERROR: Configuration file not found: $CONFIG_FILE"
    echo ""
    echo "Please run setup first:"
    echo "  bash scripts/setup-context-recall.sh"
    echo ""
    exit 1
fi

source "$CONFIG_FILE"

echo "Configuration loaded:"
echo "  API URL: $CLAUDE_API_URL"
echo "  Project ID: $CLAUDE_PROJECT_ID"
echo "  Enabled: $CONTEXT_RECALL_ENABLED"
echo ""

# Test counter
TESTS_PASSED=0
TESTS_FAILED=0

# Test function
run_test() {
    local test_name="$1"
    local test_command="$2"

    echo -n "Testing: $test_name... "

    if eval "$test_command" >/dev/null 2>&1; then
        echo "[OK] PASS"
        ((TESTS_PASSED++))
        return 0
    else
        echo "[ERROR] FAIL"
        ((TESTS_FAILED++))
        return 1
    fi
}

# Test 1: API Connectivity
echo "[Test 1] API Connectivity"
run_test "API health endpoint" \
    "curl -s --max-time 3 '$CLAUDE_API_URL/health'"
echo ""

# Test 2: Authentication
echo "[Test 2] Authentication"
run_test "JWT token validity" \
    "curl -s --max-time 3 -H 'Authorization: Bearer $JWT_TOKEN' '$CLAUDE_API_URL/api/projects'"
echo ""

# Test 3: Project Access
echo "[Test 3] Project Access"
run_test "Get project by ID" \
    "curl -s --max-time 3 -H 'Authorization: Bearer $JWT_TOKEN' '$CLAUDE_API_URL/api/projects/$CLAUDE_PROJECT_ID'"
echo ""

# Test 4: Context Recall
echo "[Test 4] Context Recall"
RECALL_URL="$CLAUDE_API_URL/api/conversation-contexts/recall"
RECALL_PARAMS="project_id=$CLAUDE_PROJECT_ID&limit=5&min_relevance_score=0.0"

run_test "Recall contexts endpoint" \
    "curl -s --max-time 3 -H 'Authorization: Bearer $JWT_TOKEN' '$RECALL_URL?$RECALL_PARAMS'"

if [ $? -eq 0 ]; then
    RECALL_RESPONSE=$(curl -s --max-time 3 \
        -H "Authorization: Bearer $JWT_TOKEN" \
        "$RECALL_URL?$RECALL_PARAMS")

    CONTEXT_COUNT=$(echo "$RECALL_RESPONSE" | grep -o '"id"' | wc -l)
    echo "  Found $CONTEXT_COUNT existing contexts"
fi
echo ""

# Test 5: Context Saving
echo "[Test 5] Context Saving"

TEST_CONTEXT_PAYLOAD=$(cat <<EOF
{
    "project_id": "$CLAUDE_PROJECT_ID",
    "context_type": "test",
    "title": "Test Context - $(date +%s)",
    "dense_summary": "This is a test context created by test-context-recall.sh at $(date -u +"%Y-%m-%dT%H:%M:%SZ")",
    "relevance_score": 5.0,
    "metadata": {
        "test": true,
        "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
    }
}
EOF
)

run_test "Create test context" \
    "curl -s --max-time 5 -X POST '$CLAUDE_API_URL/api/conversation-contexts' \
        -H 'Authorization: Bearer $JWT_TOKEN' \
        -H 'Content-Type: application/json' \
        -d '$TEST_CONTEXT_PAYLOAD'"

if [ $? -eq 0 ]; then
    SAVE_RESPONSE=$(curl -s --max-time 5 -X POST "$CLAUDE_API_URL/api/conversation-contexts" \
        -H "Authorization: Bearer $JWT_TOKEN" \
        -H "Content-Type: application/json" \
        -d "$TEST_CONTEXT_PAYLOAD")

    TEST_CONTEXT_ID=$(echo "$SAVE_RESPONSE" | grep -o '"id":"[^"]*' | sed 's/"id":"//' | head -1)

    if [ -n "$TEST_CONTEXT_ID" ]; then
        echo "  Created test context: $TEST_CONTEXT_ID"
    fi
fi
echo ""

# Test 6: Hook Files
echo "[Test 6] Hook Files"

run_test "user-prompt-submit exists" \
    "test -f '$PROJECT_ROOT/.claude/hooks/user-prompt-submit'"

run_test "user-prompt-submit is executable" \
    "test -x '$PROJECT_ROOT/.claude/hooks/user-prompt-submit'"

run_test "task-complete exists" \
    "test -f '$PROJECT_ROOT/.claude/hooks/task-complete'"

run_test "task-complete is executable" \
    "test -x '$PROJECT_ROOT/.claude/hooks/task-complete'"
echo ""

# Test 7: Hook Execution
echo "[Test 7] Hook Execution"

# Test user-prompt-submit hook
echo -n "Testing: user-prompt-submit hook execution... "
HOOK_OUTPUT=$("$PROJECT_ROOT/.claude/hooks/user-prompt-submit" 2>&1)
if [ $? -eq 0 ]; then
    echo "[OK] PASS"
    ((TESTS_PASSED++))

    if echo "$HOOK_OUTPUT" | grep -q "Previous Context"; then
        echo "  Hook produced context output"
    else
        echo "  Hook ran successfully (no context to display)"
    fi
else
    echo "[ERROR] FAIL"
    ((TESTS_FAILED++))
    echo "  Output: $HOOK_OUTPUT"
fi

# Test task-complete hook
echo -n "Testing: task-complete hook execution... "
export TASK_SUMMARY="Test task summary from test script"
export TASK_FILES="test_file1.py,test_file2.py"

HOOK_OUTPUT=$("$PROJECT_ROOT/.claude/hooks/task-complete" 2>&1)
if [ $? -eq 0 ]; then
    echo "[OK] PASS"
    ((TESTS_PASSED++))
    echo "  Hook completed successfully"
else
    echo "[ERROR] FAIL"
    ((TESTS_FAILED++))
    echo "  Output: $HOOK_OUTPUT"
fi
echo ""

# Test 8: Project State
echo "[Test 8] Project State"

PROJECT_STATE_PAYLOAD=$(cat <<EOF
{
    "project_id": "$CLAUDE_PROJECT_ID",
    "state_data": {
        "test": true,
        "test_timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
    },
    "state_type": "test"
}
EOF
)

run_test "Update project state" \
    "curl -s --max-time 5 -X POST '$CLAUDE_API_URL/api/project-states' \
        -H 'Authorization: Bearer $JWT_TOKEN' \
        -H 'Content-Type: application/json' \
        -d '$PROJECT_STATE_PAYLOAD'"
echo ""

# Test 9: Cleanup Test Data
echo "[Test 9] Cleanup"

if [ -n "$TEST_CONTEXT_ID" ]; then
    echo -n "Cleaning up test context... "
    curl -s --max-time 3 -X DELETE "$CLAUDE_API_URL/api/conversation-contexts/$TEST_CONTEXT_ID" \
        -H "Authorization: Bearer $JWT_TOKEN" >/dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo "[OK] Cleaned"
    else
        echo "[WARNING] Failed (manual cleanup may be needed)"
    fi
fi
echo ""

# Summary
echo "=========================================="
echo "Test Summary"
echo "=========================================="
echo ""
echo "Tests Passed: $TESTS_PASSED"
echo "Tests Failed: $TESTS_FAILED"
echo ""

if [ $TESTS_FAILED -eq 0 ]; then
    echo "[OK] All tests passed! Context recall system is working correctly."
    echo ""
    echo "You can now use Claude Code with automatic context recall:"
    echo "  1. Start a Claude Code conversation"
    echo "  2. Context will be automatically injected before each message"
    echo "  3. Context will be automatically saved after task completion"
    echo ""
    exit 0
else
    echo "[ERROR] Some tests failed. Please check the output above."
    echo ""
    echo "Common issues:"
    echo "  - API not running: Start with 'uvicorn api.main:app --reload'"
    echo "  - Invalid JWT token: Run 'bash scripts/setup-context-recall.sh' again"
    echo "  - Hooks not executable: Run 'chmod +x .claude/hooks/*'"
    echo ""
    echo "For detailed troubleshooting, see:"
    echo "  .claude/hooks/README.md"
    echo ""
    exit 1
fi
