#!/usr/bin/env bash
# Fix Frontend Deployment - Build and Deploy Frontend Application

set -euo pipefail

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

# Source utilities
source "$PROJECT_ROOT/dbis_core/scripts/utils/common.sh" 2>/dev/null || true

log_info "========================================="
log_info "Fix Frontend Deployment"
log_info "========================================="
log_info ""

# Check if running on Proxmox host
if command_exists pct; then
    FRONTEND_VMID="${VMID_DBIS_FRONTEND:-10130}"
    
    log_info "Detected Proxmox host - fixing frontend in container $FRONTEND_VMID"
    log_info ""
    
    # Check if container exists
    if ! pct status "$FRONTEND_VMID" &>/dev/null; then
        log_error "Container $FRONTEND_VMID not found"
        exit 1
    fi
    
    # Start container if not running
    if [ "$(pct status "$FRONTEND_VMID" 2>/dev/null | awk '{print $2}')" != "running" ]; then
        log_info "Starting container $FRONTEND_VMID..."
        pct start "$FRONTEND_VMID"
        sleep 5
    fi
    
    log_info "Building frontend application..."
    log_info ""
    
    # Install dependencies if needed
    log_info "Checking dependencies..."
    pct exec "$FRONTEND_VMID" -- bash -c "
        cd /opt/dbis-core/frontend || cd /opt/dbis-core/frontend || { echo 'Frontend directory not found'; exit 1; }
        
        if [ ! -d 'node_modules' ]; then
            echo 'Installing dependencies...'
            npm install
        else
            echo 'Dependencies already installed'
        fi
    " 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Failed to install dependencies"
        exit 1
    }
    
    # Build the application
    log_info "Building frontend..."
    pct exec "$FRONTEND_VMID" -- bash -c "
        cd /opt/dbis-core/frontend
        npm run build
    " 2>&1 | tail -30 | grep -vE "(perl: warning|locale:)" || {
        log_error "Build failed - check errors above"
        exit 1
    }
    
    # Verify build
    log_info "Verifying build..."
    if pct exec "$FRONTEND_VMID" -- test -f /opt/dbis-core/frontend/dist/index.html; then
        log_success "✅ Build successful!"
    else
        log_error "❌ Build failed - index.html not found"
        exit 1
    fi
    
    # Restart nginx
    log_info "Restarting nginx..."
    pct exec "$FRONTEND_VMID" -- systemctl restart nginx 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_warn "Nginx restart had issues, checking status..."
        pct exec "$FRONTEND_VMID" -- systemctl status nginx --no-pager -l || true
    }
    
    # Verify nginx is running
    if pct exec "$FRONTEND_VMID" -- systemctl is-active --quiet nginx; then
        log_success "✅ Nginx is running"
    else
        log_error "❌ Nginx is not running"
        exit 1
    fi
    
    log_success ""
    log_success "Frontend deployment fixed!"
    log_info ""
    log_info "Frontend should now be accessible at:"
    log_info "  http://${DBIS_FRONTEND_IP:-192.168.11.130}"
    log_info ""
    log_info "If you still see the placeholder message:"
    log_info "  1. Clear your browser cache (Ctrl+Shift+R or Cmd+Shift+R)"
    log_info "  2. Check browser console for errors"
    log_info "  3. Verify nginx is serving from: /opt/dbis-core/frontend/dist"
    
else
    # Running directly on the container
    log_info "Running directly on container - building frontend..."
    log_info ""
    
    FRONTEND_DIR="${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core}/frontend"
    
    if [ ! -d "$FRONTEND_DIR" ]; then
        log_error "Frontend directory not found: $FRONTEND_DIR"
        exit 1
    fi
    
    cd "$FRONTEND_DIR"
    
    # Install dependencies if needed
    if [ ! -d "node_modules" ]; then
        log_info "Installing dependencies..."
        npm install
    fi
    
    # Build
    log_info "Building frontend..."
    npm run build
    
    # Verify
    if [ -f "dist/index.html" ]; then
        log_success "✅ Build successful!"
    else
        log_error "❌ Build failed - index.html not found"
        exit 1
    fi
    
    # Restart nginx
    log_info "Restarting nginx..."
    systemctl restart nginx
    
    log_success ""
    log_success "Frontend deployment fixed!"
fi
