#!/bin/bash

# HACCPro Print Server - Direct Brother Communication Deployment
# Simplified deployment without CUPS complexity

set -e  # Exit on any error

echo "╔══════════════════════════════════════════════════════════╗"
echo "║      HACCPro Print Server - Direct Communication         ║"
echo "║            Simplified Raspberry Pi Deploy                ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo

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

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 Raspberry Pi
check_raspberry_pi() {
    if ! grep -q "Raspberry Pi\|BCM" /proc/cpuinfo 2>/dev/null; then
        print_warning "This doesn't appear to be a Raspberry Pi"
        print_warning "Script will continue but may not work as expected"
        read -p "Continue anyway? (y/N): " -n 1 -r
        echo
        [[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
    fi
    print_success "Raspberry Pi detected"
}

# System info
show_system_info() {
    print_status "System Information:"
    echo "   OS: $(lsb_release -d -s 2>/dev/null || echo "Linux")"
    echo "   Hardware: $(grep "Model" /proc/cpuinfo 2>/dev/null | cut -d: -f2 | xargs || echo "Unknown")"
    echo "   User: $(whoami)"
    echo
}

# Update system
update_system() {
    print_status "Updating system packages..."
    sudo apt update -qq
    sudo apt upgrade -y -qq
    print_success "System updated"
}

# Install minimal dependencies (NO CUPS!)
install_dependencies() {
    print_status "Installing minimal dependencies for direct communication..."
    sudo apt install -y \
        python3-pip \
        python3-venv \
        git \
        curl \
        wget \
        htop \
        ufw
    
    print_success "Dependencies installed (CUPS-free setup)"
}

# Setup USB permissions for direct printer access
setup_printer_permissions() {
    print_status "Configuring USB printer permissions..."
    
    # Add user to groups for USB printer access
    sudo usermod -a -G lp,dialout $USER
    
    # Create udev rule for Brother printers
    sudo tee /etc/udev/rules.d/99-brother-printer.rules > /dev/null << 'EOF'
# Brother QL-820NWB Direct Access
SUBSYSTEM=="usb", ATTRS{idVendor}=="04f9", ATTRS{idProduct}=="209d", MODE="0666", GROUP="lp"
KERNEL=="lp*", MODE="0666", GROUP="lp"
EOF

    # Reload udev rules
    sudo udevadm control --reload-rules
    sudo udevadm trigger
    
    print_success "Printer permissions configured"
}

# Create application directory
create_app_directory() {
    print_status "Creating application directory..."
    
    sudo mkdir -p /opt/haccpro-print-server
    sudo chown $USER:$USER /opt/haccpro-print-server
    
    print_success "Application directory: /opt/haccpro-print-server"
}

# Setup Python environment
setup_python_env() {
    print_status "Setting up Python environment..."
    
    cd /opt/haccpro-print-server
    
    # Virtual environment
    python3 -m venv venv
    source venv/bin/activate
    
    # Minimal packages for direct communication
    pip install --upgrade pip
    pip install \
        fastapi \
        uvicorn \
        python-multipart \
        requests \
        aiohttp \
        psutil
    
    print_success "Python environment configured"
}

# Copy print server files
setup_print_server_files() {
    print_status "Setting up print server files..."
    
    cd /opt/haccpro-print-server
    
    # Check for files
    if [ ! -f "raspberry-print-server-web.py" ]; then
        print_warning "Print server files not found"
        print_status "Please copy raspberry-print-server-web.py to /opt/haccpro-print-server/"
        read -p "Press Enter when file is copied, or Ctrl+C to exit..."
    fi
    
    chmod +x raspberry-print-server-web.py 2>/dev/null || true
    
    print_success "Print server files ready"
}

# Create systemd service for direct communication
create_systemd_service() {
    print_status "Creating systemd service..."
    
    sudo tee /etc/systemd/system/haccpro-print-server.service > /dev/null << EOF
[Unit]
Description=HACCPro Print Server - Direct Brother Communication
After=network.target
Requires=network.target

[Service]
Type=simple
User=$USER
Group=$USER
WorkingDirectory=/opt/haccpro-print-server
Environment=PATH=/opt/haccpro-print-server/venv/bin:/usr/local/bin:/usr/bin:/bin
Environment=PYTHONPATH=/opt/haccpro-print-server
ExecStart=/opt/haccpro-print-server/venv/bin/python3 raspberry-print-server-web.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

# USB printer access groups
SupplementaryGroups=dialout lp

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    print_success "Systemd service created"
}

# Configure minimal firewall
configure_firewall() {
    print_status "Configuring firewall..."
    
    sudo ufw default deny incoming
    sudo ufw default allow outgoing
    sudo ufw allow ssh
    sudo ufw allow 8080/tcp
    sudo ufw --force enable
    
    print_success "Firewall configured"
}

# Test Brother printer detection
test_printer_detection() {
    print_status "Testing Brother printer detection..."
    
    # USB detection
    if lsusb | grep -i brother > /dev/null; then
        print_success "Brother printer detected via USB"
        lsusb | grep -i brother
    else
        print_warning "No Brother printer detected via USB"
        print_status "Please connect Brother QL-820NWB via USB"
    fi
    
    # USB device check
    if ls /dev/usb/lp* > /dev/null 2>&1; then
        print_success "USB printer device found:"
        ls -la /dev/usb/lp*
    else
        print_warning "No USB printer device found"
    fi
}

# Test installation
test_installation() {
    print_status "Testing installation..."
    
    cd /opt/haccpro-print-server
    
    # Python environment test
    if source venv/bin/activate && python3 -c "import fastapi, uvicorn; print('Dependencies OK')"; then
        print_success "Python environment OK"
    else
        print_error "Python environment test failed"
        return 1
    fi
    
    # Print server file check
    if [ -f "raspberry-print-server-web.py" ]; then
        print_success "Print server file found"
    else
        print_error "Print server file missing"
        return 1
    fi
    
    print_success "Installation tests passed"
}

# Start services
start_services() {
    print_status "Starting HACCPro Print Server..."
    
    sudo systemctl enable haccpro-print-server
    sudo systemctl start haccpro-print-server
    
    sleep 3
    
    if sudo systemctl is-active --quiet haccpro-print-server; then
        print_success "HACCPro Print Server is running!"
    else
        print_error "Service failed to start"
        print_status "Check logs: sudo journalctl -u haccpro-print-server -f"
        return 1
    fi
}

# Test API endpoints
test_api() {
    print_status "Testing API endpoints..."
    local PI_IP=$(hostname -I | awk '{print $1}')
    
    # Status endpoint
    if curl -f http://localhost:8080/api/status > /dev/null 2>&1; then
        print_success "API status endpoint working"
    else
        print_warning "API status endpoint not responding"
    fi
    
    # Printer status
    if curl -f http://localhost:8080/printer/status > /dev/null 2>&1; then
        print_success "Printer status endpoint working"
    else
        print_warning "Printer status endpoint not responding"
    fi
}

# Show completion
show_completion() {
    local PI_IP=$(hostname -I | awk '{print $1}')
    
    echo
    print_success "🎉 HACCPro Print Server deployment completed!"
    echo
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║              Direct Communication Setup                  ║"
    echo "╠══════════════════════════════════════════════════════════╣"
    echo "║  🌐 Web Interface: http://$PI_IP:8080                "
    echo "║  📊 API Status:    http://$PI_IP:8080/api/status     "
    echo "║  🖨️  Printer Test:  curl -X POST http://$PI_IP:8080/api/test"
    echo "║  🔧 SSH Access:    ssh $USER@$PI_IP                  "
    echo "╚══════════════════════════════════════════════════════════╝"
    echo
    echo "🔌 Brother Printer Setup:"
    echo "1. Connect Brother QL-820NWB via USB cable"
    echo "2. Test detection: lsusb | grep -i brother"
    echo "3. Test print: curl -X POST http://$PI_IP:8080/api/test"
    echo
    echo "⚙️  Dashboard Integration:"
    echo "1. Go to: https://dashboard.haccpro.nl/settings"
    echo "2. Enable Print Server: On"
    echo "3. IP Address: $PI_IP"
    echo "4. Port: 8080"
    echo "5. Location: Keuken"
    echo
    echo "🔍 Monitoring:"
    echo "   sudo systemctl status haccpro-print-server"
    echo "   sudo journalctl -u haccpro-print-server -f"
    echo "   curl http://$PI_IP:8080/api/status"
    echo
    echo "📋 Key Advantages of Direct Communication:"
    echo "   ✅ No CUPS complexity"
    echo "   ✅ Direct Brother QL-820NWB control"
    echo "   ✅ Faster response times"
    echo "   ✅ Fewer dependencies"
    echo "   ✅ More reliable operation"
    echo
    print_success "Ready for production use! 🚀"
}

# Main function
main() {
    echo "Starting Direct Communication deployment..."
    echo
    
    # Root check
    if [ "$EUID" -eq 0 ]; then
        print_error "Please run as regular user (pi), not root"
        exit 1
    fi
    
    # Deployment steps
    check_raspberry_pi
    show_system_info
    update_system
    install_dependencies
    setup_printer_permissions
    create_app_directory
    setup_python_env
    setup_print_server_files
    create_systemd_service
    configure_firewall
    test_printer_detection
    test_installation
    start_services
    test_api
    show_completion
}

# Execute main function
main "$@"