#!/bin/bash

echo ""
echo "=============================================="
echo "  AEGIS CYBER: Sovereign Deployment System"
echo "  Uganda Banking Infrastructure v1.0"
echo "=============================================="
echo ""

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Step 1: Environment Validation
echo -e "${CYAN}[1/6]${NC} Validating Security Secrets..."
sleep 0.5

if [ -z "$DATABASE_URL" ]; then
    echo -e "${RED}   CRITICAL: DATABASE_URL not configured${NC}"
    exit 1
else
    echo -e "${GREEN}   DATABASE_URL configured${NC}"
fi

if [ -z "$SESSION_SECRET" ]; then
    echo -e "${YELLOW}   WARNING: SESSION_SECRET not set, using default${NC}"
else
    echo -e "${GREEN}   SESSION_SECRET configured${NC}"
fi

echo -e "${GREEN}   Environment validation complete${NC}"
echo ""

# Step 2: Database Migration
echo -e "${CYAN}[2/6]${NC} Running Database Migrations..."
sleep 0.5
npm run db:push 2>&1 | tail -5
if [ $? -ne 0 ]; then
    echo -e "${RED}   Database migration failed${NC}"
    exit 1
fi
echo -e "${GREEN}   Schema synchronized with PostgreSQL${NC}"
echo ""

# Step 3: Seed Demo Data
echo -e "${CYAN}[3/6]${NC} Seeding Demo Data..."
sleep 0.5
npx tsx scripts/seed.ts 2>&1 | tail -10
echo -e "${GREEN}   Demo users and threat data initialized${NC}"
echo ""

# Step 4: Pre-Flight Check (Commercial-Grade)
echo -e "${CYAN}[4/6]${NC} Running Commercial-Grade Pre-Flight Check..."
sleep 0.5
npx tsx scripts/pre-flight-check.ts
if [ $? -ne 0 ]; then
    echo -e "${RED}   Pre-flight check failed - BLOCKED${NC}"
    exit 1
fi
echo ""

# Step 5: Build Frontend (Production)
if [ "$NODE_ENV" = "production" ]; then
    echo -e "${CYAN}[5/6]${NC} Compiling React Production Build..."
    npm run build
    echo -e "${GREEN}   Frontend assets compiled${NC}"
else
    echo -e "${CYAN}[5/6]${NC} Development mode - skipping production build"
fi
echo ""

# Step 6: Launch Services
echo -e "${CYAN}[6/6]${NC} Starting AEGIS Services..."
echo ""
echo "=============================================="
echo -e "${GREEN}  AEGIS CYBER ONLINE${NC}"
echo "  Threat Detection: ACTIVE"
echo "  Bio-Vault Monitoring: ACTIVE"
echo "  PDPO Compliance: ENFORCED"
echo "  WebSocket Feed: STREAMING"
echo "=============================================="
echo ""
echo -e "${YELLOW}  Demo Credentials:${NC}"
echo "  Admin:        admin / admin123"
echo "  CISO:         ciso / ciso123"
echo "  Auditor:      auditor / auditor123"
echo ""

# Start the application
exec npm run dev
