#!/usr/bin/env bash
# Skull AI Service Startup Script

set -euo pipefail

# Configuration
SKULL_ROOT="/opt/Skull"
APPS_DIR="${SKULL_ROOT}/apps"
VENV_DIR="${SKULL_ROOT}/venv"
CONFIG_DIR="${SKULL_ROOT}/config"
LOGS_DIR="${SKULL_ROOT}/logs"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging function
log() {
    local level=$1
    shift
    local message="$*"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    case $level in
        INFO)
            echo -e "${GREEN}[INFO]${NC} ${timestamp} - $message"
            ;;
        WARN)
            echo -e "${YELLOW}[WARN]${NC} ${timestamp} - $message"
            ;;
        ERROR)
            echo -e "${RED}[ERROR]${NC} ${timestamp} - $message"
            ;;
        DEBUG)
            if [[ "${DEBUG:-}" == "1" ]]; then
                echo -e "${BLUE}[DEBUG]${NC} ${timestamp} - $message"
            fi
            ;;
    esac
}

# Error handler
error_exit() {
    log ERROR "$1"
    exit 1
}

# Pre-flight checks
preflight_checks() {
    log INFO "Running pre-flight checks..."
    
    # Check directories
    for dir in "$APPS_DIR" "$CONFIG_DIR" "$LOGS_DIR"; do
        if [[ ! -d "$dir" ]]; then
            error_exit "Directory not found: $dir"
        fi
    done
    
    # Check Python virtual environment
    if [[ ! -f "${VENV_DIR}/bin/activate" ]]; then
        error_exit "Python virtual environment not found: ${VENV_DIR}"
    fi
    
    # Check if AI module exists
    if [[ ! -d "${APPS_DIR}/ai" ]]; then
        error_exit "AI module not found: ${APPS_DIR}/ai"
    fi
    
    # Check MQTT broker connectivity (optional warning)
    local mqtt_host=${MQTT_HOST:-127.0.0.1}
    local mqtt_port=${MQTT_PORT:-1883}
    
    if command -v nc >/dev/null 2>&1; then
        if ! nc -z "$mqtt_host" "$mqtt_port" 2>/dev/null; then
            log WARN "Cannot connect to MQTT broker at ${mqtt_host}:${mqtt_port}"
            log WARN "Service will retry connection automatically"
        else
            log INFO "MQTT broker connectivity OK (${mqtt_host}:${mqtt_port})"
        fi
    fi
    
    log INFO "Pre-flight checks completed"
}

# Setup environment
setup_environment() {
    log INFO "Setting up environment..."
    
    # Change to apps directory
    cd "$APPS_DIR"
    
    # Activate virtual environment
    # shellcheck source=/dev/null
    source "${VENV_DIR}/bin/activate"
    
    # Verify Python and packages
    python_version=$(python --version 2>&1)
    log INFO "Using Python: $python_version"
    
    # Check if required packages are available (basic check)
    if ! python -c "import asyncio, json, logging" 2>/dev/null; then
        error_exit "Required Python packages not available"
    fi
    
    # Load environment file if exists
    if [[ -f "${CONFIG_DIR}/ai.env" ]]; then
        log INFO "Loading environment configuration from ${CONFIG_DIR}/ai.env"
        # shellcheck source=/dev/null
        source "${CONFIG_DIR}/ai.env"
    fi
    
    # Set default environment variables
    export MQTT_HOST=${MQTT_HOST:-127.0.0.1}
    export MQTT_PORT=${MQTT_PORT:-1883}
    export AI_MODEL=${AI_MODEL:-gpt-5-mini}
    export AI_TIMEOUT_S=${AI_TIMEOUT_S:-12}
    export AI_MAX_TOKENS=${AI_MAX_TOKENS:-256}
    export AI_TEMPERATURE=${AI_TEMPERATURE:-0.7}
    export AI_TOP_P=${AI_TOP_P:-0.9}
    export AI_LANG=${AI_LANG:-fr}
    
    log INFO "Environment setup completed"
}

# Health check before start
health_check() {
    log INFO "Performing health check..."
    
    # Check if logs directory is writable
    if ! touch "${LOGS_DIR}/ai.log" 2>/dev/null; then
        error_exit "Cannot write to logs directory: ${LOGS_DIR}"
    fi
    
    # Check default prompt file
    local prompt_file="${CONFIG_DIR}/prompt.txt"
    if [[ ! -f "$prompt_file" ]]; then
        log WARN "Default prompt file not found, creating: $prompt_file"
        echo "Tu es un crâne joyeux, poli, humour léger. Évite politique, santé, argent." > "$prompt_file"
    fi
    
    # Test Python module import
    if ! python -c "import ai.main" 2>/dev/null; then
        error_exit "Cannot import AI module - check Python path and dependencies"
    fi
    
    log INFO "Health check passed"
}

# Signal handlers
cleanup() {
    local exit_code=$?
    log INFO "Cleaning up (exit code: $exit_code)..."
    
    # Kill any child processes
    if [[ -n "${AI_PID:-}" ]] && kill -0 "$AI_PID" 2>/dev/null; then
        log INFO "Terminating AI service (PID: $AI_PID)..."
        kill -TERM "$AI_PID" 2>/dev/null || true
        
        # Wait for graceful shutdown
        local count=0
        while kill -0 "$AI_PID" 2>/dev/null && [[ $count -lt 30 ]]; do
            sleep 1
            ((count++))
        done
        
        # Force kill if still running
        if kill -0 "$AI_PID" 2>/dev/null; then
            log WARN "Force killing AI service..."
            kill -KILL "$AI_PID" 2>/dev/null || true
        fi
    fi
    
    log INFO "Cleanup completed"
    exit $exit_code
}

# Set up signal handlers
trap cleanup EXIT INT TERM

# Main execution
main() {
    log INFO "Starting Skull AI Service..."
    
    # Run checks and setup
    preflight_checks
    setup_environment
    health_check
    
    log INFO "Launching AI service module..."
    log DEBUG "Working directory: $(pwd)"
    log DEBUG "Python path: $PYTHONPATH"
    log DEBUG "Environment: MQTT_HOST=${MQTT_HOST}, AI_MODEL=${AI_MODEL}"
    
    # Start the AI service and capture PID
    python -m ai.main &
    AI_PID=$!
    
    log INFO "AI service started with PID: $AI_PID"
    
    # Wait for the process and handle signals
    wait "$AI_PID"
}

# Help message
show_help() {
    cat << EOF
Skull AI Service Startup Script

Usage: $0 [OPTIONS]

OPTIONS:
    -h, --help      Show this help message
    -d, --debug     Enable debug logging
    --check-only    Run checks only, don't start service
    --version       Show version information

ENVIRONMENT VARIABLES:
    MQTT_HOST       MQTT broker hostname (default: 127.0.0.1)
    MQTT_PORT       MQTT broker port (default: 1883)
    AI_MODEL        AI model to use (default: gpt-5-mini)
    AI_TIMEOUT_S    Request timeout in seconds (default: 12)
    AI_MAX_TOKENS   Maximum tokens per response (default: 256)
    DEBUG           Enable debug output (1/0)

EXAMPLES:
    $0                          # Start normally
    DEBUG=1 $0 --debug         # Start with debug output
    $0 --check-only            # Run pre-flight checks only

EOF
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -d|--debug)
            DEBUG=1
            log DEBUG "Debug mode enabled"
            shift
            ;;
        --check-only)
            log INFO "Running checks only..."
            preflight_checks
            health_check
            log INFO "All checks passed!"
            exit 0
            ;;
        --version)
            echo "Skull AI Service v1.0.0"
            echo "Part of Skull Pi project"
            exit 0
            ;;
        *)
            log ERROR "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Run main function
main "$@"