#!/usr/bin/env bash

set -euo pipefail

# Source common functions
SCRIPT_DIR=$(cd $(dirname $0);pwd)
source "${SCRIPT_DIR}/common.sh"

# Test configuration
INTEGRATION_TEST_FEATURES="openssl-vendored testexport failpoints"

# Run a specific integration test
run_integration_test() {
    local test_name=$1
    local threads=$2
    local extra_args=${3:-""}
    
    log "Running integration test: $test_name"
    
    cd "${PROJECT_ROOT}"
    
    export RUST_BACKTRACE=1
    if cargo test \
        -p tici_integration_tests \
        --features "${INTEGRATION_TEST_FEATURES}" \
        -- "$test_name" \
        $(if [[ -n "${threads:-}" && "$threads" != "0" ]]; then echo "--test-threads $threads"; fi) \
        $extra_args; then
        log "✓ Test $test_name passed"
        return 0
    else
        local exit_code=$?
        log_error "✗ Test $test_name failed with exit code $exit_code"
        return $exit_code
    fi
}

# Run all integration tests
run_all_tests() {
    log "Starting integration tests..."
    
    local failed_tests=()
    local total_tests=0
    local passed_tests=0
    
    create_changefeed
    
    # List of tests to run
    local tests=(
        "sequential"
        "e2e"
    )
    local parallel_tests=(
        "meta"
        "new_reader"
        "import"
        "status_server"
    )
    local mixed_tests=(
        "sequential::long_term"
    )
    
    # Run each test
    for test in "${tests[@]}"; do
        ((total_tests++))
        log ""
        log "==================== Test $total_tests: $test ===================="
        
        if run_integration_test "$test" "1"; then
            ((passed_tests++))
        else
            failed_tests+=("$test")
        fi
    done

    # Run each parallel test
    for test in "${parallel_tests[@]}"; do
        ((total_tests++))
        log ""
        log "==================== Test $total_tests: $test ===================="
        
        if run_integration_test "$test" "0"; then
            ((passed_tests++))
        else
            failed_tests+=("$test")
        fi
    done

    # Run each mixed test
    ORI_INTEGRATION_TEST_FEATURES=INTEGRATION_TEST_FEATURES
    INTEGRATION_TEST_FEATURES+=" get_manifest_from_writer"
    echo "INTEGRATION_TEST_FEATURES: $INTEGRATION_TEST_FEATURES"
    for test in "${mixed_tests[@]}"; do
        ((total_tests++))
        log ""
        log "==================== Test $total_tests: $test ===================="
        
        if run_integration_test "$test" "0"; then
            ((passed_tests++))
        else
            failed_tests+=("$test")
        fi
    done
    INTEGRATION_TEST_FEATURES=ORI_INTEGRATION_TEST_FEATURES
    echo "INTEGRATION_TEST_FEATURES: $INTEGRATION_TEST_FEATURES"
    
    # Report results
    log ""
    log "==================== Test Results ===================="
    log "Total tests: $total_tests"
    log "Passed tests: $passed_tests"
    log "Failed tests: $((total_tests - passed_tests))"
    
    if [ ${#failed_tests[@]} -gt 0 ]; then
        log_error "Failed tests:"
        for test in "${failed_tests[@]}"; do
            log_error "  - $test"
        done
        return 1
    else
        log "All tests passed! 🎉"
        return 0
    fi
}

# Display test environment information
show_test_info() {
    log "Test Environment Information:"
    log "  Project root: ${PROJECT_ROOT}"
    log "  Test output: ${TEST_OUTPUT_DIR}"
    log "  Asset directory: ${ASSET_DIR}"
    log "  Test features: ${INTEGRATION_TEST_FEATURES}"
    log ""
}

# Main test execution
main() {
    log "Starting integration test execution..."
    
    # Setup cleanup trap
    trap 'cleanup $?' ERR
    trap 'cleanup' EXIT INT TERM
    
    # Show test information
    show_test_info
    
    # Run all tests
    if run_all_tests; then
        log "All integration tests completed successfully! 🎉"
        exit 0
    else
        log_error "Some integration tests failed"
        exit 1
    fi
}

# Handle command line arguments
case "${1:-}" in
    --help|-h)
        echo "Usage: $0 [options]"
        echo ""
        echo "Options:"
        echo "  --help, -h    Show this help message"
        echo ""
        echo "Environment variables:"
        echo "  TEST_OUTPUT_DIR   Directory for test outputs (default: ${SCRIPT_DIR}/output)"
        echo "  ASSET_DIR         Directory containing test assets (default: ${PROJECT_ROOT})"
        exit 0
        ;;
    "")
        # Run main function with no arguments
        main
        ;;
    *)
        log_error "Unknown option: $1"
        echo "Use --help for usage information"
        exit 1
        ;;
esac
