#!/usr/bin/env bash

set -euo pipefail

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

# Main preparation process
main() {
    log "Starting integration test preparation..."
    
    # Check prerequisites
    if ! check_prerequisites; then
        log_error "Prerequisites check failed"
        exit 1
    fi

    # Setup cleanup trap
    trap 'cleanup' INT TERM
    
    # Prepare dataset
    if ! prepare_dataset; then
        log_error "Failed to prepare dataset"
        exit 1
    fi
    
    # Start MinIO
    if ! start_minio; then
        log_error "Failed to start MinIO"
        exit 1
    fi
    
    # Prepare playground arguments
    local PLAYGROUND_ARGS="--tiflash 0"
    if [ -n "${DB_BINPATH:-}" ]; then
        PLAYGROUND_ARGS+=" --db.binpath $DB_BINPATH"
    fi
    
    # Start TiDB playground
    if ! start_playground "" "nightly" "$PLAYGROUND_ARGS"; then
        log_error "Failed to start TiDB playground"
        exit 1
    fi
    
    log "integration test environment prepared successfully!"
    log "Services running:"
    log "  - TiDB: 127.0.0.1:${DEFAULT_TIDB_PORT}"
    log "  - PD: 127.0.0.1:${DEFAULT_PD_PORT}"
    log "  - TiCDC: 127.0.0.1:${DEFAULT_CDC_PORT}"
    log "  - MinIO: 127.0.0.1:${DEFAULT_MINIO_PORT}"
    log "  - MinIO Console: 127.0.0.1:${DEFAULT_MINIO_ADMIN_PORT}"
    log ""
    log "Logs are available in: ${TEST_OUTPUT_DIR}/log/"
    log "Ready to run integration tests!"
}

# Run main function
main "$@"

# Handle command line arguments
if [ "$#" -gt 0 ]; then
    case $1 in
        --help|-h)
            echo "Usage: $0"
            echo "Prepare the environment for integration tests."
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help or -h for usage information."
            exit 1
            ;;
    esac
fi
