#!/usr/bin/env bash
# Deploy Frontend Admin Console Container for DBIS Core Banking System

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"
source "$PROJECT_ROOT/dbis_core/scripts/utils/dbis-core-utils.sh" 2>/dev/null || true
source "$PROJECT_ROOT/smom-dbis-138-proxmox/lib/container-utils.sh" 2>/dev/null || true

# Load configuration
load_config

log_info "========================================="
log_info "DBIS Core - Frontend Deployment"
log_info "========================================="
log_info ""

check_root
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

# Ensure OS template exists
ensure_os_template "${DBIS_CONTAINER_OS_TEMPLATE:-${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}}" || {
    error_exit "OS template not available. Please download it first."
}

# Function to create Frontend container
create_frontend_container() {
    local vmid="$1"
    local hostname="$2"
    local ip_address="$3"
    
    log_info "Creating Frontend container: $hostname (VMID: $vmid, IP: $ip_address)"
    
    if container_exists "$vmid"; then
        log_warn "Container $vmid already exists, skipping creation"
    else
        log_info "Creating container $vmid..."
        pct create "$vmid" \
            "${DBIS_CONTAINER_OS_TEMPLATE:-${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}}" \
            --storage "${PROXMOX_STORAGE:-local-lvm}" \
            --hostname "$hostname" \
            --memory "${DBIS_FRONTEND_MEMORY:-4096}" \
            --cores "${DBIS_FRONTEND_CORES:-2}" \
            --rootfs "${PROXMOX_STORAGE:-local-lvm}:${DBIS_FRONTEND_DISK:-50}" \
            --net0 "bridge=${DBIS_NETWORK_BRIDGE:-vmbr0},name=eth0,ip=${ip_address}/24,gw=192.168.11.1,type=veth" \
            --unprivileged "${DBIS_CONTAINER_UNPRIVILEGED:-1}" \
            --swap "${DBIS_FRONTEND_SWAP:-512}" \
            --onboot "${DBIS_CONTAINER_ONBOOT:-1}" \
            --timezone "${DBIS_CONTAINER_TIMEZONE:-America/Los_Angeles}" \
            --features nesting=1,keyctl=1
        
        log_success "Container $vmid created"
    fi
    
    wait_for_container "$vmid"
    
    # Configure container
    log_info "Configuring container $vmid..."
    pct set "$vmid" --features nesting=1,keyctl=1
    
    # Start container and wait for readiness
    if ! start_container_and_wait "$vmid"; then
        log_error "Failed to start container $vmid"
        return 1
    fi
    
    # Verify container is ready
    if ! verify_container_ready "$vmid"; then
        log_error "Container $vmid is not ready for file operations"
        return 1
    fi
    
    # Configure locale
    pct exec "$vmid" -- bash -c "export LC_ALL=C; export LANG=C; echo 'export LC_ALL=C' >> /root/.bashrc; echo 'export LANG=C' >> /root/.bashrc; echo 'export LC_ALL=C' >> /etc/environment; echo 'export LANG=C' >> /etc/environment" 2>/dev/null || true
    
    # Update system
    log_info "Updating system packages..."
    pct exec "$vmid" -- bash -c "export DEBIAN_FRONTEND=noninteractive; apt-get update -qq && apt-get upgrade -y -qq" 2>&1 | grep -vE "(perl: warning|locale:)" || true
    
    # Install curl first (required for Node.js installation)
    log_info "Installing curl..."
    pct exec "$vmid" -- bash -c "export DEBIAN_FRONTEND=noninteractive; apt-get install -y -qq curl" 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Failed to install curl"
        return 1
    }
    
    # Remove conflicting Node.js packages BEFORE setup (must happen first)
    log_info "Removing conflicting Node.js packages..."
    pct exec "$vmid" -- bash -c "export DEBIAN_FRONTEND=noninteractive; apt-get remove -y -qq nodejs libnode72 nodejs-doc 2>/dev/null; apt-get autoremove -y -qq 2>/dev/null; apt-get update -qq" 2>&1 | grep -vE "(perl: warning|locale:)" || true
    
    # Install Node.js
    log_info "Installing Node.js ${DBIS_NODE_VERSION:-18}..."
    pct exec "$vmid" -- bash -c "curl -fsSL https://deb.nodesource.com/setup_${DBIS_NODE_VERSION:-18}.x | bash -" 2>&1 | grep -vE "(perl: warning|locale:)" || true
    pct exec "$vmid" -- bash -c "export DEBIAN_FRONTEND=noninteractive; apt-get install -y -qq nodejs build-essential" 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Failed to install Node.js"
        return 1
    }
    
    # Install Nginx
    log_info "Installing Nginx..."
    pct exec "$vmid" -- bash -c "export DEBIAN_FRONTEND=noninteractive; apt-get install -y -qq nginx" 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Failed to install Nginx"
        return 1
    }
    
    # Create application directory
    log_info "Setting up application directory..."
    pct exec "$vmid" -- bash -c "mkdir -p ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core}" 2>/dev/null || true
    
    # Copy dbis_core repository to container
    log_info "Copying DBIS Core repository to container..."
    if [[ -d "$PROJECT_ROOT/dbis_core" ]]; then
        # Use tar to copy files (pct push doesn't support recursive)
        log_info "Pushing repository files to container..."
        local temp_tar="/tmp/dbis_core_$$.tar.gz"
        tar czf "$temp_tar" -C "$PROJECT_ROOT" dbis_core 2>/dev/null
        if [[ -f "$temp_tar" ]]; then
            pct push "$vmid" "$temp_tar" /tmp/dbis_core.tar.gz 2>&1 | grep -vE "(perl: warning|locale:)" || true
            pct exec "$vmid" -- bash -c "cd /opt && tar xzf /tmp/dbis_core.tar.gz && mv dbis_core dbis-core 2>/dev/null && rm -f /tmp/dbis_core.tar.gz" 2>&1 | grep -vE "(perl: warning|locale:)" || {
                log_warn "Failed to extract repository, will clone instead"
                pct exec "$vmid" -- bash -c "cd ${DBIS_CORE_PROJECT_ROOT:-/opt} && git clone https://github.com/Order-of-Hospitallers/dbis_core.git dbis-core 2>/dev/null || true" || true
            }
            rm -f "$temp_tar" 2>/dev/null || true
        else
            log_warn "Failed to create tar archive, will clone instead"
            pct exec "$vmid" -- bash -c "cd ${DBIS_CORE_PROJECT_ROOT:-/opt} && git clone https://github.com/Order-of-Hospitallers/dbis_core.git dbis-core 2>/dev/null || true" || true
        fi
    else
        log_warn "Local repository not found, will need to clone from git"
        pct exec "$vmid" -- bash -c "cd ${DBIS_CORE_PROJECT_ROOT:-/opt} && git clone https://github.com/Order-of-Hospitallers/dbis_core.git dbis-core 2>/dev/null || true" || true
    fi
    
    # Install frontend dependencies
    log_info "Installing frontend dependencies..."
    pct exec "$vmid" -- bash -c "cd ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core}/frontend && npm ci 2>&1 | tail -20" 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_warn "npm ci failed, trying npm install"
        pct exec "$vmid" -- bash -c "cd ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core}/frontend && npm install 2>&1 | tail -20" 2>&1 | grep -vE "(perl: warning|locale:)" || true
    }
    
    # Create environment file for frontend
    log_info "Creating frontend environment configuration..."
    local api_url="http://${DBIS_API_PRIMARY_IP:-192.168.11.150}:${DBIS_API_PORT:-3000}"
    
    pct exec "$vmid" -- bash -c "cat > ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core}/frontend/.env <<EOF
VITE_API_BASE_URL=${api_url}
VITE_APP_NAME=DBIS Admin Console
VITE_REAL_TIME_UPDATE_INTERVAL=5000
EOF
" 2>/dev/null || true
    
    # Build frontend
    log_info "Building frontend application..."
    pct exec "$vmid" -- bash -c "cd ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core}/frontend && npm run build 2>&1 | tail -30" 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Frontend build failed"
        return 1
    }
    
    # Configure Nginx
    log_info "Configuring Nginx..."
    pct exec "$vmid" -- bash -c "cat > /etc/nginx/sites-available/dbis-frontend <<EOF
server {
    listen 80;
    server_name ${ip_address};
    root ${DBIS_CORE_PROJECT_ROOT:-/opt/dbis-core}/frontend/dist;
    index index.html;

    # Gzip compression
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # Security headers
    add_header X-Frame-Options \"SAMEORIGIN\" always;
    add_header X-Content-Type-Options \"nosniff\" always;
    add_header X-XSS-Protection \"1; mode=block\" always;

    # SPA routing
    location / {
        try_files \$uri \$uri/ /index.html;
    }

    # API proxy (optional)
    location /api {
        proxy_pass ${api_url};
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$remote_addr;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    # Cache static assets
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control \"public, immutable\";
    }
}
EOF
" 2>/dev/null || true
    
    # Enable site
    pct exec "$vmid" -- bash -c "ln -sf /etc/nginx/sites-available/dbis-frontend /etc/nginx/sites-enabled/" 2>/dev/null || true
    pct exec "$vmid" -- bash -c "rm -f /etc/nginx/sites-enabled/default" 2>/dev/null || true
    
    # Test and reload Nginx
    log_info "Testing Nginx configuration..."
    pct exec "$vmid" -- nginx -t 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Nginx configuration test failed"
        return 1
    }
    
    log_info "Starting Nginx..."
    pct exec "$vmid" -- systemctl restart nginx 2>/dev/null || true
    pct exec "$vmid" -- systemctl enable nginx 2>/dev/null || true
    
    # Configure firewall
    if pct exec "$vmid" -- command -v ufw >/dev/null 2>&1; then
        log_info "Configuring firewall..."
        pct exec "$vmid" -- bash -c "ufw allow 80/tcp comment 'HTTP'" 2>/dev/null || true
        pct exec "$vmid" -- bash -c "ufw allow 443/tcp comment 'HTTPS'" 2>/dev/null || true
    fi
    
    log_success "Frontend container $hostname (VMID: $vmid) deployed successfully"
    return 0
}

# Deploy Frontend
log_info "Deploying Frontend Admin Console..."
create_frontend_container \
    "${VMID_DBIS_FRONTEND:-10130}" \
    "dbis-frontend" \
    "${DBIS_FRONTEND_IP:-192.168.11.130}"

log_success "Frontend deployment completed!"
log_info ""
log_info "Deployment Summary:"
log_info "  Frontend: http://${DBIS_FRONTEND_IP:-192.168.11.130}"
log_info "  API: http://${DBIS_API_PRIMARY_IP:-192.168.11.150}:${DBIS_API_PORT:-3000}"
log_info ""
log_info "Next steps:"
log_info "1. Check service status: ./scripts/management/status.sh"
log_info "2. Run database migrations: ./scripts/deployment/configure-database.sh"
log_info "3. Test API health: curl http://${DBIS_API_PRIMARY_IP:-192.168.11.150}:${DBIS_API_PORT:-3000}/health"

