#!/usr/bin/env bash
# Deploy Sankofa API to r630-01
# VMID: 7800, IP: 10.160.0.10

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SANKOFA_PROJECT="${SANKOFA_PROJECT:-/home/intlc/projects/Sankofa}"
source "$SCRIPT_DIR/env.r630-01.example" 2>/dev/null || true

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Configuration
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.11}"
VMID="${VMID_SANKOFA_API:-7800}"
CONTAINER_IP="${SANKOFA_API_IP:-10.160.0.10}"
DB_HOST="${DB_HOST:-10.160.0.13}"
DB_PORT="${DB_PORT:-5432}"
DB_NAME="${DB_NAME:-sankofa}"
DB_USER="${DB_USER:-sankofa}"
DB_PASSWORD="${DB_PASSWORD:-}"
KEYCLOAK_URL="${KEYCLOAK_URL:-http://10.160.0.12:8080}"
KEYCLOAK_REALM="${KEYCLOAK_REALM:-master}"
KEYCLOAK_CLIENT_ID="${KEYCLOAK_CLIENT_ID_API:-sankofa-api}"
KEYCLOAK_CLIENT_SECRET="${KEYCLOAK_CLIENT_SECRET_API:-}"
JWT_SECRET="${JWT_SECRET:-$(openssl rand -base64 32)}"
NODE_VERSION="18"

# SSH function
ssh_r630_01() {
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" "$@"
}

# Execute command in container
exec_container() {
    ssh_r630_01 "pct exec $VMID -- $*"
}

main() {
    echo ""
    log_info "========================================="
    log_info "Sankofa API Deployment"
    log_info "========================================="
    echo ""
    log_info "Container VMID: $VMID"
    log_info "Container IP: $CONTAINER_IP"
    echo ""
    
    # Check if container exists and is running
    log_info "Checking container status..."
    if ! ssh_r630_01 "pct status $VMID >/dev/null 2>&1"; then
        log_error "Container $VMID does not exist. Please run deploy-sankofa-r630-01.sh first."
        exit 1
    fi
    
    local status=$(ssh_r630_01 "pct status $VMID" 2>/dev/null | awk '{print $2}' || echo "stopped")
    if [[ "$status" != "running" ]]; then
        log_info "Starting container $VMID..."
        ssh_r630_01 "pct start $VMID"
        sleep 5
    fi
    log_success "Container is running"
    echo ""
    
    # Install Node.js
    log_info "Installing Node.js $NODE_VERSION..."
    exec_container bash -c "export DEBIAN_FRONTEND=noninteractive && \
        curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION}.x | bash - && \
        apt-get install -y -qq nodejs"
    
    # Install pnpm
    log_info "Installing pnpm..."
    exec_container bash -c "npm install -g pnpm"
    
    log_success "Node.js and pnpm installed"
    echo ""
    
    # Copy project files
    log_info "Copying Sankofa API project files..."
    if [[ ! -d "$SANKOFA_PROJECT/api" ]]; then
        log_error "Sankofa project not found at $SANKOFA_PROJECT"
        log_info "Please ensure the Sankofa project is available"
        exit 1
    fi
    
    # Create app directory
    exec_container bash -c "mkdir -p /opt/sankofa-api"
    
    # Copy API directory
    log_info "Copying files to container..."
    ssh_r630_01 "pct push $VMID $SANKOFA_PROJECT/api /opt/sankofa-api --recursive"
    
    log_success "Project files copied"
    echo ""
    
    # Install dependencies
    log_info "Installing dependencies..."
    exec_container bash -c "cd /opt/sankofa-api && pnpm install --frozen-lockfile"
    
    log_success "Dependencies installed"
    echo ""
    
    # Create environment file
    log_info "Creating environment configuration..."
    exec_container bash -c "cat > /opt/sankofa-api/.env << EOF
# Database
DB_HOST=$DB_HOST
DB_PORT=$DB_PORT
DB_NAME=$DB_NAME
DB_USER=$DB_USER
DB_PASSWORD=$DB_PASSWORD

# Keycloak
KEYCLOAK_URL=$KEYCLOAK_URL
KEYCLOAK_REALM=$KEYCLOAK_REALM
KEYCLOAK_CLIENT_ID=$KEYCLOAK_CLIENT_ID
KEYCLOAK_CLIENT_SECRET=$KEYCLOAK_CLIENT_SECRET
KEYCLOAK_MULTI_REALM=false

# API
API_PORT=4000
JWT_SECRET=$JWT_SECRET
NODE_ENV=production

# Multi-Tenancy
ENABLE_MULTI_TENANT=true

# Billing
BILLING_GRANULARITY=SECOND
BLOCKCHAIN_BILLING_ENABLED=false
BLOCKCHAIN_IDENTITY_ENABLED=false
EOF"
    
    log_success "Environment configured"
    echo ""
    
    # Run database migrations
    log_info "Running database migrations..."
    exec_container bash -c "cd /opt/sankofa-api && pnpm db:migrate" || log_warn "Migrations may have failed - check database connection"
    echo ""
    
    # Build API
    log_info "Building API..."
    exec_container bash -c "cd /opt/sankofa-api && pnpm build"
    
    log_success "API built"
    echo ""
    
    # Create systemd service
    log_info "Creating systemd service..."
    exec_container bash -c "cat > /etc/systemd/system/sankofa-api.service << 'EOF'
[Unit]
Description=Sankofa API Server
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/sankofa-api
Environment=\"NODE_ENV=production\"
EnvironmentFile=/opt/sankofa-api/.env
ExecStart=/usr/bin/node /opt/sankofa-api/dist/server.js
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF"
    
    # Start service
    log_info "Starting API service..."
    exec_container bash -c "systemctl daemon-reload && \
        systemctl enable sankofa-api && \
        systemctl start sankofa-api"
    
    sleep 5
    
    # Check service status
    if exec_container bash -c "systemctl is-active --quiet sankofa-api"; then
        log_success "API service is running"
    else
        log_error "API service failed to start"
        exec_container bash -c "journalctl -u sankofa-api -n 50 --no-pager"
        exit 1
    fi
    echo ""
    
    # Test API health
    log_info "Testing API health endpoint..."
    sleep 5
    if exec_container bash -c "curl -s -f http://localhost:4000/health >/dev/null 2>&1"; then
        log_success "API health check passed"
    else
        log_warn "API health check failed - service may still be starting"
    fi
    echo ""
    
    # Summary
    log_success "========================================="
    log_success "Sankofa API Deployment Complete"
    log_success "========================================="
    echo ""
    log_info "API Configuration:"
    echo "  URL: http://$CONTAINER_IP:4000"
    echo "  GraphQL: http://$CONTAINER_IP:4000/graphql"
    echo "  Health: http://$CONTAINER_IP:4000/health"
    echo ""
    log_info "Next steps:"
    echo "  1. Verify API is accessible: curl http://$CONTAINER_IP:4000/health"
    echo "  2. Run: ./scripts/deploy-portal-r630-01.sh"
    echo ""
}

main "$@"
