#!/bin/bash

# Gitea Webhook Ambassador (Python) - Devbox Script
# This script mimics the Go version's devbox functionality

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_NAME="gitea-webhook-ambassador"
PID_FILE="$SCRIPT_DIR/service.pid"
LOG_FILE="$SCRIPT_DIR/logs/service.log"

# Create logs directory
mkdir -p "$SCRIPT_DIR/logs"

# Function to show usage
show_usage() {
    echo "Usage: $0 {start|stop|restart|status|logs|follow|init|install|help}"
    echo ""
    echo "Commands:"
    echo "  start   - Start the service in background"
    echo "  stop    - Stop the service"
    echo "  restart - Restart the service"
    echo "  status  - Show service status"
    echo "  logs    - Show latest logs"
    echo "  follow  - Follow logs in real-time"
    echo "  init    - Initialize database"
    echo "  install - Install dependencies"
    echo "  help    - Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 start    # Start service"
    echo "  $0 status   # Check status"
    echo "  $0 logs     # View logs"
}

# Function to check if virtual environment exists
check_venv() {
    if [ ! -d "$SCRIPT_DIR/venv" ]; then
        echo "❌ Virtual environment not found. Run '$0 install' first."
        exit 1
    fi
}

# Function to activate virtual environment
activate_venv() {
    source "$SCRIPT_DIR/venv/bin/activate"
}

# Function to start service
start_service() {
    echo "🚀 Starting $APP_NAME (Python Version)..."
    echo "🐍 Version: Python Enhanced with Web UI"
    
    check_venv
    
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p $PID > /dev/null 2>&1; then
            echo "❌ Service is already running (PID: $PID)"
            return 1
        else
            echo "⚠️  Found stale PID file, cleaning up..."
            rm -f "$PID_FILE"
        fi
    fi
    
    # Activate virtual environment and start service
    cd "$SCRIPT_DIR"
    activate_venv
    
    # Start the service in background
    nohup python -m uvicorn app.main_enhanced:app --host 0.0.0.0 --port 8000 > "$LOG_FILE" 2>&1 &
    PID=$!
    echo $PID > "$PID_FILE"
    
    # Wait a moment for service to start
    sleep 3
    
    if ps -p $PID > /dev/null 2>&1; then
        echo "✅ Python Service started successfully (PID: $PID)"
        echo "📝 Log file: $LOG_FILE"
        echo "🌐 Access: http://localhost:8000"
        echo "📊 Dashboard: http://localhost:8000/dashboard"
        echo "🔑 Admin key: admin-secret-key-change-in-production"
        echo "🐍 Python Version Features: Web UI, Database, JWT Auth"
    else
        echo "❌ Service failed to start"
        rm -f "$PID_FILE"
        return 1
    fi
}

# Function to stop service
stop_service() {
    echo "🛑 Stopping $APP_NAME..."
    
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p $PID > /dev/null 2>&1; then
            kill $PID
            echo "✅ Service stopped (PID: $PID)"
        else
            echo "⚠️  Service not running"
        fi
        rm -f "$PID_FILE"
    else
        echo "⚠️  No PID file found"
    fi
}

# Function to restart service
restart_service() {
    echo "🔄 Restarting $APP_NAME..."
    stop_service
    sleep 2
    start_service
}

# Function to show status
show_status() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p $PID > /dev/null 2>&1; then
            echo "✅ $APP_NAME (Python Version) is running (PID: $PID)"
            echo "🐍 Version: Python Enhanced with Web UI"
            echo "📝 Log file: $LOG_FILE"
            echo "🌐 Access: http://localhost:8000"
            echo "📊 Dashboard: http://localhost:8000/dashboard"
        else
            echo "❌ $APP_NAME is not running (PID file exists but process not found)"
            rm -f "$PID_FILE"
        fi
    else
        echo "❌ $APP_NAME is not running"
    fi
}

# Function to show logs
show_logs() {
    if [ -f "$LOG_FILE" ]; then
        echo "📝 Latest logs (last 50 lines):"
        echo "----------------------------------------"
        tail -n 50 "$LOG_FILE"
        echo "----------------------------------------"
        echo "Full log file: $LOG_FILE"
    else
        echo "❌ No log file found"
    fi
}

# Function to follow logs
follow_logs() {
    if [ -f "$LOG_FILE" ]; then
        echo "📝 Following logs (Ctrl+C to exit):"
        tail -f "$LOG_FILE"
    else
        echo "❌ No log file found"
    fi
}

# Function to initialize database
init_database() {
    echo "🗄️  Initializing database..."
    check_venv
    cd "$SCRIPT_DIR"
    activate_venv
    python -c "from app.models.database import create_tables; create_tables(); print('Database initialized successfully')"
}

# Function to install dependencies
install_dependencies() {
    echo "📦 Installing dependencies..."
    cd "$SCRIPT_DIR"
    
    if [ -d "venv" ]; then
        echo "⚠️  Virtual environment already exists. Removing..."
        rm -rf venv
    fi
    
    python3 -m venv venv
    activate_venv
    pip install -r requirements.txt
    echo "✅ Dependencies installed successfully"
}

# Main logic
case "$1" in
    start)
        start_service
        ;;
    stop)
        stop_service
        ;;
    restart)
        restart_service
        ;;
    status)
        show_status
        ;;
    logs)
        show_logs
        ;;
    follow)
        follow_logs
        ;;
    init)
        init_database
        ;;
    install)
        install_dependencies
        ;;
    help|--help|-h)
        show_usage
        ;;
    *)
        echo "❌ Unknown command: $1"
        echo ""
        show_usage
        exit 1
        ;;
esac 