#!/bin/bash

# HACCPro Raspberry Pi Print Server Installer
# Voor Brother QL-820NWB label printer

echo "╔══════════════════════════════════════════════════════════╗"
echo "║            HACCPro Print Server Installer               ║"
echo "║                Raspberry Pi Setup                       ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo

# Check if running on Raspberry Pi
if ! grep -q "Raspberry Pi\|BCM" /proc/cpuinfo 2>/dev/null; then
    echo "⚠️  Waarschuwing: Dit lijkt geen Raspberry Pi te zijn"
    echo "   Script werkt ook op andere Linux systemen"
    echo
fi

echo "🔍 Systeem informatie:"
echo "   OS: $(lsb_release -d -s 2>/dev/null || echo "Linux")"
echo "   Kernel: $(uname -r)"
echo "   Hardware: $(grep "Model" /proc/cpuinfo 2>/dev/null | cut -d: -f2 | xargs || echo "Unknown")"
echo

# Update system
echo "📦 Systeem updaten..."
sudo apt update -qq
sudo apt upgrade -y -qq

# Install Python dependencies
echo "🐍 Python dependencies installeren..."
sudo apt install -y python3-pip python3-venv cups cups-client

# Install Python packages
echo "📚 Python packages installeren..."
pip3 install --user fastapi uvicorn python-multipart requests

# Setup Brother QL-820NWB printer
echo "🖨️  Brother QL-820NWB printer configureren..."

# Add user to lpadmin group
sudo usermod -a -G lpadmin $USER

# Install Brother QL drivers if not already installed
if ! lpstat -p | grep -q "Brother"; then
    echo "📥 Brother printer drivers installeren..."
    
    # Download Brother QL-820NWB drivers
    cd /tmp
    
    # Voor ARM (Raspberry Pi)
    if [ "$(uname -m)" = "armv7l" ] || [ "$(uname -m)" = "aarch64" ]; then
        echo "🔧 ARM drivers installeren..."
        # Manual driver installation voor ARM
        sudo apt install -y printer-driver-brlaser
    else
        # x86_64 drivers
        echo "🔧 x86_64 drivers installeren..."
        wget -q "https://download.brother.com/welcome/dlf103525/ql820nwbpdrv-3.3.0-1.i386.deb" -O brother-ql820-driver.deb
        sudo dpkg -i brother-ql820-driver.deb || sudo apt-get install -f -y
    fi
fi

# Create print server directory
echo "📁 Print server directory maken..."
PRINT_SERVER_DIR="/opt/haccpro-print-server"
sudo mkdir -p $PRINT_SERVER_DIR
sudo chown $USER:$USER $PRINT_SERVER_DIR

# Copy print server files
if [ -f "raspberry-print-server-web.py" ]; then
    cp raspberry-print-server-web.py $PRINT_SERVER_DIR/
    chmod +x $PRINT_SERVER_DIR/raspberry-print-server-web.py
    PRINT_SERVER_FILE="raspberry-print-server-web.py"
    echo "✅ Using Web Interface version (raspberry-print-server-web.py)"
elif [ -f "raspberry-print-server.py" ]; then
    cp raspberry-print-server.py $PRINT_SERVER_DIR/
    chmod +x $PRINT_SERVER_DIR/raspberry-print-server.py
    PRINT_SERVER_FILE="raspberry-print-server.py"
    echo "✅ Using Basic version (raspberry-print-server.py)"
else
    echo "❌ Geen print server files gevonden!"
    echo "   Zorg dat raspberry-print-server-web.py of raspberry-print-server.py in deze directory staat"
    exit 1
fi

# Create systemd service
echo "⚙️  Systemd service configureren..."
sudo tee /etc/systemd/system/haccpro-print-server.service > /dev/null << EOF
[Unit]
Description=HACCPro Print Server
After=network.target cups.service
Requires=network.target

[Service]
Type=simple
User=$USER
WorkingDirectory=$PRINT_SERVER_DIR
ExecStart=/usr/bin/python3 $PRINT_SERVER_FILE
Restart=always
RestartSec=10
Environment=PATH=/home/$USER/.local/bin:/usr/local/bin:/usr/bin:/bin

[Install]
WantedBy=multi-user.target
EOF

# Enable and start service
sudo systemctl daemon-reload
sudo systemctl enable haccpro-print-server
sudo systemctl start haccpro-print-server

# Wait a moment for service to start
sleep 3

# Check service status
if systemctl is-active --quiet haccpro-print-server; then
    echo "✅ HACCPro Print Server is gestart!"
    echo
    echo "🌐 Service URL: http://$(hostname -I | awk '{print $1}'):8080"
    echo "📊 Status: http://$(hostname -I | awk '{print $1}'):8080"
    echo "🖨️  Test print: curl -X POST http://$(hostname -I | awk '{print $1}'):8080/test"
else
    echo "❌ Service start mislukt. Controleer logs:"
    echo "   sudo journalctl -u haccpro-print-server -f"
fi

# Configuration and Testing Section
echo
echo "╔══════════════════════════════════════════════════════════╗"
echo "║                CONFIGURATIE & TESTEN                    ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo

# Step 1: Configure Company ID and Location
echo "📋 STAP 1: Company Configuratie"
echo "=============================="
echo
echo "Voor de HACCPro dashboard integratie moet de print server"
echo "geconfigureerd worden met jouw company ID en locatie."
echo

# Get Company ID
echo "📝 Voer jouw HACCPro Company ID in:"
echo "   Voorbeelden: 18 (De Pauw van Warnsveld), 31, 68"
read -p "Company ID: " COMPANY_ID

while [[ -z "$COMPANY_ID" ]] || ! [[ "$COMPANY_ID" =~ ^[0-9]+$ ]]; do
    echo "❌ Ongeldige Company ID. Voer alleen cijfers in."
    read -p "Company ID: " COMPANY_ID
done

# Get Location
echo
echo "📍 Voer de locatie van deze print server in:"
echo "   Voorbeelden: Keuken, Cold Storage, Freezer"
read -p "Locatie: " LOCATION

while [[ -z "$LOCATION" ]]; do
    echo "❌ Locatie kan niet leeg zijn."
    read -p "Locatie: " LOCATION
done

# Save configuration
echo
echo "💾 Configuratie opslaan..."
cat > $PRINT_SERVER_DIR/config.json << EOF
{
    "company_id": "$COMPANY_ID",
    "location": "$LOCATION",
    "server_name": "$(hostname)-print-server",
    "ip_address": "$(hostname -I | awk '{print $1}')",
    "created": "$(date -Iseconds)"
}
EOF

echo "✅ Configuratie opgeslagen in $PRINT_SERVER_DIR/config.json"
echo "   Company ID: $COMPANY_ID"
echo "   Locatie: $LOCATION"

# Step 2: Test API Connection
echo
echo "📋 STAP 2: API Verbinding Testen"
echo "================================"
echo

PI_IP=$(hostname -I | awk '{print $1}')

# Test heartbeat to main API
echo "🔍 Testen van API verbinding naar HACCPro dashboard..."
HEARTBEAT_RESPONSE=$(curl -s -w "%{http_code}" -X POST \
  "https://api.haccpro.nl/api/v1/print-servers/status" \
  -H "Content-Type: application/json" \
  -d "{
    \"company_id\": \"$COMPANY_ID\",
    \"server_name\": \"$(hostname)-print-server\",
    \"location\": \"$LOCATION\",
    \"ip_address\": \"$PI_IP\",
    \"printer_status\": \"ready\",
    \"status\": \"online\",
    \"uptime\": \"$(uptime -s)\",
    \"version\": \"1.0.0\",
    \"connection_type\": \"wifi\",
    \"jobs_completed\": 0,
    \"success_rate\": 100
  }" \
  -o /tmp/heartbeat_response.txt)

HTTP_CODE="${HEARTBEAT_RESPONSE: -3}"

if [[ "$HTTP_CODE" == "200" ]]; then
    echo "✅ API verbinding succesvol!"
    echo "   Print server is geregistreerd in HACCPro dashboard"
    
    # Check if response contains success
    if grep -q "success\|ok" /tmp/heartbeat_response.txt 2>/dev/null; then
        echo "✅ Print server status bijgewerkt in dashboard"
    fi
else
    echo "⚠️  API verbinding fout (HTTP $HTTP_CODE)"
    echo "   Response: $(cat /tmp/heartbeat_response.txt 2>/dev/null)"
    echo "   Print server werkt lokaal, maar dashboard integratie kan beperkt zijn"
fi

# Step 3: Verify Dashboard Visibility
echo
echo "📋 STAP 3: Dashboard Controle"
echo "============================"
echo

echo "🔍 Controleren of print server zichtbaar is in dashboard..."
sleep 2

# Check if print server shows up in dashboard
DASHBOARD_CHECK=$(curl -s "https://api.haccpro.nl/api/v1/print-servers?company_id=$COMPANY_ID")

if echo "$DASHBOARD_CHECK" | grep -q "$(hostname)-print-server" 2>/dev/null; then
    echo "✅ Print server gevonden in HACCPro dashboard!"
    echo "   Status: Online"
else
    echo "⚠️  Print server nog niet zichtbaar in dashboard"
    echo "   Dit kan enkele minuten duren of een configuratie probleem zijn"
fi

# Step 4: Test Print Functionality
echo
echo "📋 STAP 4: Print Test"
echo "==================="
echo

echo "🖨️  Testen van print functionaliteit..."

# Test local print server
if curl -s -f "http://$PI_IP:8080/health" > /dev/null; then
    echo "✅ Lokale print server reageert"
    
    # Attempt configuration test print
    echo "🧪 Configuration test print uitvoeren..."
    CONFIG_TEST_RESPONSE=$(curl -s -w "%{http_code}" -X POST \
      "http://$PI_IP:8080/test/config" \
      -H "Content-Type: application/json" \
      -o /tmp/config_test_response.txt)
    
    CONFIG_HTTP_CODE="${CONFIG_TEST_RESPONSE: -3}"
    
    if [[ "$CONFIG_HTTP_CODE" == "200" ]]; then
        echo "✅ Configuration test print succesvol verzonden naar printer"
        echo "   📋 Deze test print toont alle setup informatie:"
        echo "      • Server naam en locatie"
        echo "      • Company ID en IP adres" 
        echo "      • Dashboard verbinding status"
        echo "      • Setup datum en tijd"
        
        # Also do a basic test print
        echo
        echo "🖨️  Basis test print uitvoeren..."
        BASIC_TEST_RESPONSE=$(curl -s -w "%{http_code}" -X POST \
          "http://$PI_IP:8080/test" \
          -H "Content-Type: application/json" \
          -d '{"message": "HACCPro Setup Test"}' \
          -o /tmp/basic_test_response.txt)
        
        BASIC_HTTP_CODE="${BASIC_TEST_RESPONSE: -3}"
        
        if [[ "$BASIC_HTTP_CODE" == "200" ]]; then
            echo "✅ Basis test print ook succesvol"
        else
            echo "⚠️  Basis test print fout (HTTP $BASIC_HTTP_CODE)"
        fi
    else
        echo "⚠️  Configuration test print fout (HTTP $CONFIG_HTTP_CODE)"
        echo "   Controleer printer verbinding en CUPS configuratie"
        echo "   Response: $(cat /tmp/config_test_response.txt 2>/dev/null)"
    fi
else
    echo "❌ Lokale print server reageert niet"
    echo "   Controleer service status: sudo systemctl status haccpro-print-server"
fi

echo
echo "📋 Volgende stappen:"
echo "1. Sluit Brother QL-820NWB aan via USB"
echo "2. Ga naar HACCPro Dashboard: https://dashboard.haccpro.nl/settings"
echo "3. Klik op 'Apparaat Beheer' tab"
echo "4. Controleer dat jouw print server als 'Online' staat"
echo "5. Test printen vanuit het dashboard"
echo
echo "🖨️  Test Print Commands:"
echo "   • Configuration test: curl -X POST http://$PI_IP:8080/test/config"
echo "   • Basic test print:   curl -X POST http://$PI_IP:8080/test"
echo "   • Web interface:      http://$PI_IP:8080"
echo
echo "🔧 Brother printer instellen:"
echo "   - Ga naar CUPS: http://$(hostname -I | awk '{print $1}'):631"
echo "   - Voeg Brother QL-820NWB toe als nieuwe printer"
echo "   - Selecteer juiste driver en test page"
echo
echo "📝 Logs bekijken:"
echo "   sudo journalctl -u haccpro-print-server -f"
echo
echo "🔄 Service herstarten:"
echo "   sudo systemctl restart haccpro-print-server"
echo
echo "💡 TIP: De configuration test print toont alle setup informatie"
echo "   op het label voor eenvoudige verificatie van de installatie."
echo

# Show current IP for easy reference
PI_IP=$(hostname -I | awk '{print $1}')
echo "💡 Raspberry Pi IP adres: $PI_IP"
echo "   Gebruik dit adres in jouw HACCPro API configuratie"
echo