#!/bin/bash
#
# SamCloud Advanced Dashboard Setup Script
# =======================================
# Automates the setup and deployment of the advanced home lab dashboard
#
# Author: GitHub Copilot for SamCloud
# Date: June 23, 2025

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="$SCRIPT_DIR/venv"
DASHBOARD_SCRIPT="$SCRIPT_DIR/advanced_homelab_dashboard.py"
REQUIREMENTS_FILE="$SCRIPT_DIR/advanced_requirements.txt"
LOG_FILE="$SCRIPT_DIR/dashboard.log"

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

print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

check_dependencies() {
    print_status "Checking system dependencies..."
    
    # Check Python 3
    if ! command -v python3 &> /dev/null; then
        print_error "Python 3 is required but not installed"
        exit 1
    fi
    
    python_version=$(python3 --version | cut -d' ' -f2 | cut -d'.' -f1,2)
    print_status "Found Python $python_version"
    
    # Check Docker
    if ! command -v docker &> /dev/null; then
        print_warning "Docker not found - container discovery will be limited"
    else
        print_status "Docker found"
    fi
    
    # Check Homebrew
    if ! command -v brew &> /dev/null; then
        print_warning "Homebrew not found - service discovery will be limited"
    else
        print_status "Homebrew found"
    fi
}

setup_virtual_environment() {
    print_status "Setting up Python virtual environment..."
    
    if [[ ! -d "$VENV_DIR" ]]; then
        python3 -m venv "$VENV_DIR"
        print_success "Virtual environment created"
    else
        print_status "Virtual environment already exists"
    fi
    
    # Activate virtual environment
    source "$VENV_DIR/bin/activate"
    
    # Upgrade pip
    pip install --upgrade pip > /dev/null 2>&1
    
    # Install requirements
    if [[ -f "$REQUIREMENTS_FILE" ]]; then
        print_status "Installing Python dependencies..."
        pip install -r "$REQUIREMENTS_FILE" > /dev/null 2>&1
        print_success "Dependencies installed"
    else
        print_error "Requirements file not found: $REQUIREMENTS_FILE"
        exit 1
    fi
}

check_ports() {
    print_status "Checking for port conflicts..."
    
    if lsof -i :5001 > /dev/null 2>&1; then
        print_warning "Port 5001 is already in use"
        print_status "Attempting to stop existing dashboard..."
        pkill -f "advanced_homelab_dashboard.py" || true
        sleep 2
    fi
    
    if lsof -i :5001 > /dev/null 2>&1; then
        print_error "Port 5001 is still in use after cleanup attempt"
        print_error "Please manually stop the process using port 5001"
        exit 1
    fi
}

start_dashboard() {
    print_status "Starting SamCloud Advanced Dashboard..."
    
    # Ensure virtual environment is activated
    source "$VENV_DIR/bin/activate"
    
    # Start dashboard in background
    nohup python "$DASHBOARD_SCRIPT" > "$LOG_FILE" 2>&1 &
    DASHBOARD_PID=$!
    
    # Wait a moment for startup
    sleep 3
    
    # Check if process is still running
    if ps -p $DASHBOARD_PID > /dev/null 2>&1; then
        print_success "Dashboard started successfully (PID: $DASHBOARD_PID)"
        print_success "Dashboard available at: http://localhost:5001"
        print_status "Logs available at: $LOG_FILE"
        
        # Save PID for later management
        echo $DASHBOARD_PID > "$SCRIPT_DIR/dashboard.pid"
        
        # Try to open in browser
        if command -v open &> /dev/null; then
            sleep 2
            open "http://localhost:5001" > /dev/null 2>&1 &
            print_status "Opening dashboard in default browser..."
        fi
    else
        print_error "Dashboard failed to start"
        print_error "Check logs at: $LOG_FILE"
        exit 1
    fi
}

stop_dashboard() {
    print_status "Stopping SamCloud Advanced Dashboard..."
    
    if [[ -f "$SCRIPT_DIR/dashboard.pid" ]]; then
        DASHBOARD_PID=$(cat "$SCRIPT_DIR/dashboard.pid")
        if ps -p $DASHBOARD_PID > /dev/null 2>&1; then
            kill $DASHBOARD_PID
            print_success "Dashboard stopped (PID: $DASHBOARD_PID)"
        else
            print_warning "Dashboard process not found"
        fi
        rm -f "$SCRIPT_DIR/dashboard.pid"
    else
        # Fallback: kill by process name
        pkill -f "advanced_homelab_dashboard.py" || true
        print_status "Attempted to stop dashboard by process name"
    fi
}

status_dashboard() {
    if [[ -f "$SCRIPT_DIR/dashboard.pid" ]]; then
        DASHBOARD_PID=$(cat "$SCRIPT_DIR/dashboard.pid")
        if ps -p $DASHBOARD_PID > /dev/null 2>&1; then
            print_success "Dashboard is running (PID: $DASHBOARD_PID)"
            print_status "Dashboard URL: http://localhost:5001"
            print_status "Log file: $LOG_FILE"
            return 0
        else
            print_warning "Dashboard PID file exists but process not found"
            rm -f "$SCRIPT_DIR/dashboard.pid"
        fi
    fi
    
    if pgrep -f "advanced_homelab_dashboard.py" > /dev/null; then
        print_warning "Dashboard process found but PID file missing"
        return 0
    fi
    
    print_status "Dashboard is not running"
    return 1
}

show_help() {
    echo "SamCloud Advanced Dashboard Management Script"
    echo ""
    echo "Usage: $0 [command]"
    echo ""
    echo "Commands:"
    echo "  setup      - Set up virtual environment and dependencies"
    echo "  start      - Start the dashboard"
    echo "  stop       - Stop the dashboard"
    echo "  restart    - Restart the dashboard"
    echo "  status     - Show dashboard status"
    echo "  logs       - Show dashboard logs"
    echo "  help       - Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 setup      # Initial setup"
    echo "  $0 start      # Start dashboard"
    echo "  $0 status     # Check if running"
}

show_logs() {
    if [[ -f "$LOG_FILE" ]]; then
        echo "=== Dashboard Logs ==="
        tail -50 "$LOG_FILE"
    else
        print_warning "Log file not found: $LOG_FILE"
    fi
}

# Main script logic
case "${1:-start}" in
    setup)
        print_status "Setting up SamCloud Advanced Dashboard..."
        check_dependencies
        setup_virtual_environment
        print_success "Setup completed successfully!"
        print_status "Run '$0 start' to start the dashboard"
        ;;
    
    start)
        if status_dashboard > /dev/null 2>&1; then
            print_warning "Dashboard is already running"
            print_status "Dashboard URL: http://localhost:5001"
            exit 0
        fi
        
        check_dependencies
        setup_virtual_environment
        check_ports
        start_dashboard
        ;;
    
    stop)
        stop_dashboard
        ;;
    
    restart)
        print_status "Restarting dashboard..."
        stop_dashboard
        sleep 2
        check_dependencies
        setup_virtual_environment
        check_ports
        start_dashboard
        ;;
    
    status)
        status_dashboard
        ;;
    
    logs)
        show_logs
        ;;
    
    help|--help|-h)
        show_help
        ;;
    
    *)
        print_error "Unknown command: $1"
        show_help
        exit 1
        ;;
esac
