#!/usr/bin/env bash
#
# NVIDIA OC Installer
#
# Sets up the nvidia-oc application including:
# - Python virtual environment and dependencies
# - Node.js frontend dependencies
# - Coolbits X11 configuration (required for overclocking)
# - Optional systemd service installation
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# Logging helpers
info() { echo -e "${BLUE}[INFO]${NC} $*"; }
success() { echo -e "${GREEN}[OK]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }

# Banner
echo -e "${CYAN}"
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║                    NVIDIA OC Installer                       ║"
echo "║                  GPU Overclocking Dashboard                  ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# =============================================================================
# Prerequisites Check
# =============================================================================

info "Checking prerequisites..."

# Check for NVIDIA driver
if ! command -v nvidia-smi &>/dev/null; then
    error "nvidia-smi not found. Please install NVIDIA drivers first."
fi
success "NVIDIA driver detected"

# Check for nvidia-settings
if ! command -v nvidia-settings &>/dev/null; then
    error "nvidia-settings not found. Please install nvidia-settings package."
fi
success "nvidia-settings detected"

# Check for Python (prefer uv)
if command -v uv &>/dev/null; then
    PYTHON_CMD="uv"
    success "uv detected (recommended)"
elif command -v python3 &>/dev/null; then
    PYTHON_CMD="python3"
    warn "uv not found, using python3 (consider installing uv for better dependency management)"
else
    error "Python 3 not found. Please install Python 3.11+ or uv."
fi

# Check for Node.js and pnpm
if ! command -v node &>/dev/null; then
    error "Node.js not found. Please install Node.js 18+."
fi
success "Node.js detected: $(node --version)"

if ! command -v pnpm &>/dev/null; then
    warn "pnpm not found. Installing via npm..."
    npm install -g pnpm || error "Failed to install pnpm"
fi
success "pnpm detected: $(pnpm --version)"

# =============================================================================
# Coolbits Configuration
# =============================================================================

echo ""
info "Checking Coolbits configuration..."

COOLBITS_CONFIGURED=false
XORG_CONF_DIR="/etc/X11/xorg.conf.d"
NVIDIA_CONF="$XORG_CONF_DIR/20-nvidia-coolbits.conf"

# Check if Coolbits is already configured
if grep -rq "Coolbits" /etc/X11/ 2>/dev/null; then
    success "Coolbits already configured"
    COOLBITS_CONFIGURED=true
else
    warn "Coolbits NOT configured - clock/fan control will not work!"
    echo ""
    echo -e "${YELLOW}Coolbits enables GPU overclocking and fan control.${NC}"
    echo -e "This requires creating an X11 configuration file."
    echo ""

    read -p "Configure Coolbits now? [Y/n] " -n 1 -r
    echo ""

    if [[ ! $REPLY =~ ^[Nn]$ ]]; then
        # Create Coolbits config
        COOLBITS_CONF='Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"

    # Coolbits bitmask:
    # Bit 0 (1)  = Allow clock frequency adjustment
    # Bit 1 (2)  = Allow clock frequency adjustment for SLI
    # Bit 2 (4)  = Allow clock offset adjustments
    # Bit 3 (8)  = Allow fan control
    # Bit 4 (16) = Allow voltage control (unsupported on modern GPUs)
    #
    # Value 12 = 4 + 8 = Clock offsets + Fan control
    # Value 28 = 4 + 8 + 16 = Full control (may not work on all GPUs)
    Option         "Coolbits" "12"
EndSection'

        echo ""
        info "Creating $NVIDIA_CONF ..."

        # Need sudo for /etc/X11
        if [[ $EUID -ne 0 ]]; then
            echo -e "${YELLOW}Sudo required to write X11 configuration${NC}"
            echo "$COOLBITS_CONF" | sudo tee "$NVIDIA_CONF" > /dev/null
        else
            echo "$COOLBITS_CONF" > "$NVIDIA_CONF"
        fi

        success "Coolbits configuration created"
        echo ""
        warn "You must restart your display manager or reboot for Coolbits to take effect!"
        echo -e "  ${CYAN}sudo systemctl restart gdm${NC}  (or your display manager)"
        echo ""
        COOLBITS_CONFIGURED=true
    else
        warn "Skipping Coolbits configuration. Clock/fan control will NOT work."
    fi
fi

# =============================================================================
# Python Dependencies
# =============================================================================

echo ""
info "Installing Python dependencies..."

cd "$SCRIPT_DIR/backend"

if [[ "$PYTHON_CMD" == "uv" ]]; then
    uv sync || error "Failed to install Python dependencies with uv"
else
    # Fallback to pip with venv
    if [[ ! -d ".venv" ]]; then
        python3 -m venv .venv
    fi
    source .venv/bin/activate
    pip install -e . || error "Failed to install Python dependencies"
fi

success "Python dependencies installed"

# =============================================================================
# Frontend Dependencies
# =============================================================================

echo ""
info "Installing frontend dependencies..."

cd "$SCRIPT_DIR/frontend"
pnpm install || error "Failed to install frontend dependencies"

success "Frontend dependencies installed"

# =============================================================================
# Build Frontend (optional for production)
# =============================================================================

read -p "Build frontend for production? [y/N] " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    info "Building frontend..."
    pnpm build || error "Frontend build failed"
    success "Frontend built"
fi

# =============================================================================
# Systemd Service Installation (optional)
# =============================================================================

echo ""
read -p "Install systemd service for auto-start? [y/N] " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    info "Installing systemd service..."

    # Update service file with correct paths
    SERVICE_FILE="$SCRIPT_DIR/systemd/nvidia-oc.service"

    if [[ $EUID -ne 0 ]]; then
        sudo cp "$SERVICE_FILE" /etc/systemd/system/
        sudo systemctl daemon-reload
        sudo systemctl enable nvidia-oc.service
    else
        cp "$SERVICE_FILE" /etc/systemd/system/
        systemctl daemon-reload
        systemctl enable nvidia-oc.service
    fi

    success "Systemd service installed and enabled"
    echo -e "  Start with: ${CYAN}sudo systemctl start nvidia-oc${NC}"
fi

# =============================================================================
# Summary
# =============================================================================

echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║                   Installation Complete!                      ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

if [[ "$COOLBITS_CONFIGURED" == true ]] && ! grep -rq "Coolbits" /etc/X11/ 2>/dev/null; then
    echo -e "${YELLOW}⚠ IMPORTANT: Restart your display manager or reboot for Coolbits!${NC}"
    echo ""
fi

echo -e "To start the application:"
echo -e "  ${CYAN}cd $SCRIPT_DIR && ./run${NC}"
echo ""
echo -e "Or with systemd (if installed):"
echo -e "  ${CYAN}sudo systemctl start nvidia-oc${NC}"
echo ""
echo -e "Dashboard will be available at:"
echo -e "  ${CYAN}http://localhost:3420${NC}"
echo ""
