#!/bin/bash

# Test script for bulk_file_import tool
# Creates a test CSV and validates the tool
# Usage: ./test_bulk_import.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 bulk_file_import tool"
echo "============================="
echo "Database: $DB_PATH"
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 "Step 1: Create test dataset and locations"
echo "------------------------------------------"

# Create a test dataset
echo -n "Creating test dataset... "
DATASET_RESULT=$(send_request "tools/call" '{"name":"create_or_update_dataset","arguments":{"name":"Bulk Import Test Dataset","type":"test","description":"Dataset for testing bulk import"}}')
DATASET_ID=$(echo "$DATASET_RESULT" | jq -r '.result.structuredContent.dataset.id // empty')
if [ -n "$DATASET_ID" ]; then
    echo "✓ Created dataset: $DATASET_ID"
else
    echo "✗ Failed to create dataset"
    echo "$DATASET_RESULT" | jq '.'
    exit 1
fi

# Create test location A
echo -n "Creating test location A... "
LOCATION_A_RESULT=$(send_request "tools/call" '{"name":"create_or_update_location","arguments":{"dataset_id":"'"$DATASET_ID"'","name":"Test Location A","latitude":-41.2865,"longitude":174.7762,"timezone_id":"Pacific/Auckland","description":"Test site A"}}')
LOCATION_A_ID=$(echo "$LOCATION_A_RESULT" | jq -r '.result.structuredContent.location.id // empty')
if [ -n "$LOCATION_A_ID" ]; then
    echo "✓ Created location A: $LOCATION_A_ID"
else
    echo "✗ Failed to create location A"
    echo "$LOCATION_A_RESULT" | jq '.'
    exit 1
fi

# Create test location B
echo -n "Creating test location B... "
LOCATION_B_RESULT=$(send_request "tools/call" '{"name":"create_or_update_location","arguments":{"dataset_id":"'"$DATASET_ID"'","name":"Test Location B","latitude":-36.8485,"longitude":174.7633,"timezone_id":"Pacific/Auckland","description":"Test site B"}}')
LOCATION_B_ID=$(echo "$LOCATION_B_RESULT" | jq -r '.result.structuredContent.location.id // empty')
if [ -n "$LOCATION_B_ID" ]; then
    echo "✓ Created location B: $LOCATION_B_ID"
else
    echo "✗ Failed to create location B"
    echo "$LOCATION_B_RESULT" | jq '.'
    exit 1
fi
echo ""

echo "Step 2: Create test CSV file"
echo "-----------------------------"

# Create test CSV with sample data
CSV_FILE="/tmp/test_bulk_import_$$.csv"
LOG_FILE="/tmp/test_bulk_import_$$.log"

cat > "$CSV_FILE" << EOF
location_name,location_id,directory_path,date_range,sample_rate,file_count
Test Location A,$LOCATION_A_ID,/nonexistent/path/a,2024-01,250000,0
Test Location B,$LOCATION_B_ID,/nonexistent/path/b,2024-02,384000,0
EOF

echo "✓ Created test CSV at $CSV_FILE"
echo "Contents:"
cat "$CSV_FILE"
echo ""

echo "Step 3: Test bulk_file_import tool"
echo "-----------------------------------"

# Note: This will fail because the directories don't exist, but it validates:
# - CSV parsing
# - Location ID validation
# - Cluster auto-creation logic
# - Error handling

echo "Calling bulk_file_import (expect directory errors)..."
IMPORT_RESULT=$(send_request "tools/call" "{\"name\":\"bulk_file_import\",\"arguments\":{\"dataset_id\":\"$DATASET_ID\",\"csv_path\":\"$CSV_FILE\",\"log_file_path\":\"$LOG_FILE\"}}")

echo ""
echo "Result:"
IS_ERROR=$(echo "$IMPORT_RESULT" | jq -r '.result.isError // empty')
if [ -n "$IS_ERROR" ] && [ "$IS_ERROR" != "false" ]; then
    ERROR_MSG=$(echo "$IMPORT_RESULT" | jq -r '.result.content[0].text // "Unknown error"')
    echo "✓ Tool executed (with expected directory errors)"
    echo "  Error: $ERROR_MSG"
else
    SUMMARY=$(echo "$IMPORT_RESULT" | jq -r '.result.structuredContent // empty')
    if [ -n "$SUMMARY" ]; then
        echo "✓ Tool executed successfully"
        echo "$IMPORT_RESULT" | jq '.result.structuredContent'
    else
        echo "✗ Unexpected response format"
        echo "$IMPORT_RESULT" | jq '.'
    fi
fi
echo ""

# Check if log file was created
if [ -f "$LOG_FILE" ]; then
    echo "✓ Log file created at $LOG_FILE"
    echo "Log contents:"
    cat "$LOG_FILE"
else
    echo "ℹ Log file not created (expected if directories don't exist)"
fi
echo ""

echo "Step 4: Test validation - invalid CSV path"
echo "-------------------------------------------"
INVALID_CSV=$(send_request "tools/call" "{\"name\":\"bulk_file_import\",\"arguments\":{\"dataset_id\":\"$DATASET_ID\",\"csv_path\":\"/nonexistent/file.csv\",\"log_file_path\":\"$LOG_FILE\"}}")
IS_ERROR=$(echo "$INVALID_CSV" | jq -r '.result.isError // .error.message // empty')
if [ -n "$IS_ERROR" ] && [ "$IS_ERROR" != "false" ]; then
    echo "✓ Correctly rejected non-existent CSV file"
else
    echo "✗ Should have rejected non-existent CSV"
fi
echo ""

echo "Step 5: Test validation - invalid dataset ID"
echo "---------------------------------------------"
INVALID_DATASET=$(send_request "tools/call" "{\"name\":\"bulk_file_import\",\"arguments\":{\"dataset_id\":\"INVALID_ID_123\",\"csv_path\":\"$CSV_FILE\",\"log_file_path\":\"$LOG_FILE\"}}")
IS_ERROR=$(echo "$INVALID_DATASET" | 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 ""

echo "=== TEST SUMMARY ==="
echo "Bulk import tool validation complete!"
echo "Note: Directory errors are expected (using non-existent paths)"
echo "The test validates CSV parsing and validation logic."
echo ""

# Cleanup
echo "Cleaning up test files..."
rm -f "$CSV_FILE" "$LOG_FILE"
echo "✓ Cleanup complete"
echo ""