#!/bin/bash
# Test suite for import_file tool
# Usage: ./test_import_file.sh [db_path]
# Default: ../db/test.duckdb (ALWAYS USE TEST DATABASE!)

# Get absolute paths before changing directory
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
DB_PATH="${1:-$PROJECT_DIR/db/test.duckdb}"

if [ ! -f "$DB_PATH" ]; then
    echo "Error: Database not found at $DB_PATH"
    exit 1
fi

echo "Testing import_file tool with database: $DB_PATH"
echo "================================================="
echo ""

# Navigate to the project directory where skraak_mcp binary is located
cd "$PROJECT_DIR" || exit 1

if [ ! -f "./skraak_mcp" ]; then
    echo "Error: skraak_mcp binary not found. Run 'go build' first."
    exit 1
fi

# Function to send MCP request
send_request() {
    local method="$1"
    local params="$2"

    (
        echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'
        sleep 0.2
        echo "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"$method\",\"params\":$params}"
        sleep 0.5
    ) | timeout 10 ./skraak_mcp "$DB_PATH" 2>&1 | grep '"id":2' | head -1
}

echo "Setup: Getting test IDs from database"
echo "--------------------------------------"

# Get test IDs using execute_sql
DATASET_RESULT=$(send_request "tools/call" '{"name":"execute_sql","arguments":{"query":"SELECT id, name FROM dataset WHERE active = true LIMIT 1"}}')
DATASET_ID=$(echo "$DATASET_RESULT" | jq -r '.result.structuredContent.rows[0].id // empty')
DATASET_NAME=$(echo "$DATASET_RESULT" | jq -r '.result.structuredContent.rows[0].name // empty')

if [ -z "$DATASET_ID" ]; then
    echo "✗ No active datasets found in database"
    exit 1
fi
echo "✓ Using dataset: $DATASET_NAME ($DATASET_ID)"

LOCATION_RESULT=$(send_request "tools/call" '{"name":"execute_sql","arguments":{"query":"SELECT id, name FROM location WHERE dataset_id = ? AND active = true LIMIT 1","parameters":["'"$DATASET_ID"'"]}}')
LOCATION_ID=$(echo "$LOCATION_RESULT" | jq -r '.result.structuredContent.rows[0].id // empty')
LOCATION_NAME=$(echo "$LOCATION_RESULT" | jq -r '.result.structuredContent.rows[0].name // empty')

if [ -z "$LOCATION_ID" ]; then
    echo "✗ No active locations found for dataset"
    exit 1
fi
echo "✓ Using location: $LOCATION_NAME ($LOCATION_ID)"

CLUSTER_RESULT=$(send_request "tools/call" '{"name":"execute_sql","arguments":{"query":"SELECT id, name FROM cluster WHERE location_id = ? AND active = true LIMIT 1","parameters":["'"$LOCATION_ID"'"]}}')
CLUSTER_ID=$(echo "$CLUSTER_RESULT" | jq -r '.result.structuredContent.rows[0].id // empty')
CLUSTER_NAME=$(echo "$CLUSTER_RESULT" | jq -r '.result.structuredContent.rows[0].name // empty')

if [ -z "$CLUSTER_ID" ]; then
    echo "✗ No active clusters found for location"
    exit 1
fi
echo "✓ Using cluster: $CLUSTER_NAME ($CLUSTER_ID)"
echo ""

echo "=== VALIDATION TESTS ==="
echo ""

# Test 1: Non-existent file
echo "Test 1: Import non-existent file (should fail)"
echo "-----------------------------------------------"
RESULT=$(send_request "tools/call" '{"name":"import_file","arguments":{"file_path":"/nonexistent/path/to/file.wav","dataset_id":"'"$DATASET_ID"'","location_id":"'"$LOCATION_ID"'","cluster_id":"'"$CLUSTER_ID"'"}}')
IS_ERROR=$(echo "$RESULT" | jq -r '.result.isError // .error.message // empty')
if [ -n "$IS_ERROR" ] && [ "$IS_ERROR" != "false" ]; then
    echo "✓ Correctly rejected non-existent file"
else
    echo "✗ Should have rejected non-existent file"
fi
echo ""

# Test 2: Non-WAV file
echo "Test 2: Import non-WAV file (should fail)"
echo "------------------------------------------"
RESULT=$(send_request "tools/call" '{"name":"import_file","arguments":{"file_path":"/etc/passwd","dataset_id":"'"$DATASET_ID"'","location_id":"'"$LOCATION_ID"'","cluster_id":"'"$CLUSTER_ID"'"}}')
IS_ERROR=$(echo "$RESULT" | jq -r '.result.isError // .error.message // empty')
if [ -n "$IS_ERROR" ] && [ "$IS_ERROR" != "false" ]; then
    echo "✓ Correctly rejected non-WAV file"
else
    echo "✗ Should have rejected non-WAV file"
fi
echo ""

# Test 3: Invalid dataset ID
echo "Test 3: Import with invalid dataset_id (should fail)"
echo "-----------------------------------------------------"
RESULT=$(send_request "tools/call" '{"name":"import_file","arguments":{"file_path":"/tmp/test.wav","dataset_id":"INVALID_ID_123","location_id":"'"$LOCATION_ID"'","cluster_id":"'"$CLUSTER_ID"'"}}')
IS_ERROR=$(echo "$RESULT" | jq -r '.result.isError // .error.message // empty')
if [ -n "$IS_ERROR" ] && [ "$IS_ERROR" != "false" ]; then
    echo "✓ Correctly rejected invalid dataset_id"
else
    echo "✗ Should have rejected invalid dataset_id"
fi
echo ""

# Test 4: Invalid cluster ID
echo "Test 4: Import with invalid cluster_id (should fail)"
echo "-----------------------------------------------------"
RESULT=$(send_request "tools/call" '{"name":"import_file","arguments":{"file_path":"/tmp/test.wav","dataset_id":"'"$DATASET_ID"'","location_id":"'"$LOCATION_ID"'","cluster_id":"INVALID_ID_123"}}')
IS_ERROR=$(echo "$RESULT" | jq -r '.result.isError // .error.message // empty')
if [ -n "$IS_ERROR" ] && [ "$IS_ERROR" != "false" ]; then
    echo "✓ Correctly rejected invalid cluster_id"
else
    echo "✗ Should have rejected invalid cluster_id"
fi
echo ""

echo "=== QUERY EXISTING FILES ==="
echo ""

# Query existing files in the cluster
echo "Querying existing files in cluster..."
FILES_RESULT=$(send_request "tools/call" '{"name":"execute_sql","arguments":{"query":"SELECT file_name, xxh64_hash, duration FROM file WHERE cluster_id = ? AND active = true ORDER BY created_at DESC LIMIT 3","parameters":["'"$CLUSTER_ID"'"]}}')
FILE_COUNT=$(echo "$FILES_RESULT" | jq -r '.result.structuredContent.row_count // 0')

if [ "$FILE_COUNT" -gt 0 ]; then
    echo "✓ Found $FILE_COUNT file(s) in cluster:"
    echo "$FILES_RESULT" | jq -r '.result.structuredContent.rows[] | "  - \(.file_name) (hash: \(.xxh64_hash), duration: \(.duration)s)"'
else
    echo "ℹ No existing files found in cluster"
fi
echo ""

echo "=== TEST SUMMARY ==="
echo "Validation tests complete!"
echo ""
echo "Note: This test validates error handling."
echo "To test actual file import, you would need:"
echo "  1. A real WAV file path"
echo "  2. Proper dataset/location/cluster IDs"
echo "  3. File system access to the WAV file"
echo ""
echo "Example import command:"
echo '  {"name":"import_file","arguments":{"file_path":"/path/to/file.wav","dataset_id":"'$DATASET_ID'","location_id":"'$LOCATION_ID'","cluster_id":"'$CLUSTER_ID'"}}'
echo ""