#!/bin/bash

# ByteLyst Dashboard Deployment Script
# Model: Following trading web deployment pattern with docker-compose

set -e

echo "🚀 ByteLyst Dashboard Deployment Script"
echo "======================================"

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

# Configuration
DEVOPS_DIR="/opt/bytelyst/learning_ai_devops_tools/dashboard"
PLATFORM_DIR="/opt/bytelyst/learning_ai_common_plat"

# Function to print colored output
print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

# Check prerequisites
check_prerequisites() {
    echo "Checking prerequisites..."

    if ! command -v docker &> /dev/null; then
        print_error "Docker is not installed"
        exit 1
    fi
    print_success "Docker is installed"

    if ! command -v docker compose &> /dev/null; then
        print_error "Docker Compose is not installed"
        exit 1
    fi
    print_success "Docker Compose is installed"

    if [ ! -f "$DEVOPS_DIR/backend/.env" ]; then
        print_error "backend/.env file not found in $DEVOPS_DIR"
        exit 1
    fi
    print_success "DevOps backend .env file found"

    if [ ! -f "$PLATFORM_DIR/.env" ]; then
        print_error ".env file not found in $PLATFORM_DIR"
        exit 1
    fi
    print_success "Platform .env file found"
}

# Check platform network
check_network() {
    echo "Checking platform network..."

    if docker network inspect learning_ai_common_plat_default &> /dev/null; then
        print_success "Platform network exists"
    else
        print_error "Platform network not found. Start the platform stack first:"
        print_error "  cd $PLATFORM_DIR && docker compose up -d"
        exit 1
    fi
}

# Deploy DevOps Dashboard
deploy_devops() {
    echo "Deploying DevOps Dashboard..."
    cd "$DEVOPS_DIR"

    # Get git metadata for build
    BYTELYST_COMMIT_SHA=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
    BYTELYST_COMMIT_SHA_FULL=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
    BYTELYST_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
    BYTELYST_BUILT_AT=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    BYTELYST_COMMIT_AUTHOR=$(git log -1 --pretty=format:'%an' 2>/dev/null || echo "unknown")
    BYTELYST_COMMIT_MESSAGE=$(git log -1 --pretty=format:'%s' 2>/dev/null || echo "unknown")

    export BYTELYST_COMMIT_SHA
    export BYTELYST_COMMIT_SHA_FULL
    export BYTELYST_BRANCH
    export BYTELYST_BUILT_AT
    export BYTELYST_COMMIT_AUTHOR
    export BYTELYST_COMMIT_MESSAGE
    export BYTELYST_DOCKER_IMAGE="devops-web:latest"

    docker compose down
    docker compose up -d --build

    print_success "DevOps Dashboard deployed"
}

# Deploy Admin Dashboard (via platform stack)
deploy_admin() {
    echo "Deploying Admin Dashboard via platform stack..."
    cd "$PLATFORM_DIR"

    # Get git metadata for build
    BYTELYST_COMMIT_SHA=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
    BYTELYST_COMMIT_SHA_FULL=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
    BYTELYST_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
    BYTELYST_BUILT_AT=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    BYTELYST_COMMIT_AUTHOR=$(git log -1 --pretty=format:'%an' 2>/dev/null || echo "unknown")
    BYTELYST_COMMIT_MESSAGE=$(git log -1 --pretty=format:'%s' 2>/dev/null || echo "unknown")

    export BYTELYST_COMMIT_SHA
    export BYTELYST_COMMIT_SHA_FULL
    export BYTELYST_BRANCH
    export BYTELYST_BUILT_AT
    export BYTELYST_COMMIT_AUTHOR
    export BYTELYST_COMMIT_MESSAGE
    export BYTELYST_DOCKER_IMAGE="admin-web:latest"

    # Start admin-web service
    docker compose up -d admin-web --build

    print_success "Admin Dashboard deployed"
}

# Health checks
health_checks() {
    echo "Running health checks..."

    # Wait for services to start
    sleep 15

    # Check DevOps Backend
    if curl -s http://localhost:4004/health > /dev/null; then
        print_success "DevOps Backend is healthy"
    else
        print_error "DevOps Backend health check failed"
    fi

    # Check DevOps Web
    if curl -s http://localhost:3049 > /dev/null; then
        print_success "DevOps Web is responding"
    else
        print_error "DevOps Web health check failed"
    fi

    # Check Admin Web
    if curl -s http://localhost:3001 > /dev/null; then
        print_success "Admin Web is responding"
    else
        print_error "Admin Web health check failed"
    fi
}

# Show deployment info
show_info() {
    echo ""
    echo "======================================"
    echo "Deployment Information"
    echo "======================================"
    echo "Local URLs:"
    echo "DevOps Dashboard: http://localhost:3049"
    echo "DevOps Backend: http://localhost:4004"
    echo "Admin Dashboard: http://localhost:3001"
    echo "Platform Service: http://localhost:4003"
    echo ""
    echo "Production URLs (via Traefik + DNS):"
    echo "DevOps Dashboard: https://devops.bytelyst.com"
    echo "Admin Dashboard: https://admin.bytelyst.com"
    echo "API Gateway: https://api.bytelyst.com"
    echo "  - Platform API: https://api.bytelyst.com/platform/api"
    echo "  - DevOps API: https://api.bytelyst.com/devops"
    echo ""
    echo "Deployment Model:"
    echo "- Following trading web docker-compose pattern"
    echo "- Multi-stage Docker builds with build metadata"
    echo "- Services connected via learning_ai_common_plat_default network"
    echo "- Health checks and automatic restarts configured"
    echo ""
    echo "Quick Updates (Hotcopy):"
    echo "- DevOps: cd $DEVOPS_DIR && ./scripts/deploy-hotcopy.sh"
    echo "- Admin: cd $PLATFORM_DIR && ./scripts/deploy-admin-hotcopy.sh"
    echo ""
    echo "Next steps:"
    echo "1. Configure DNS records for devops.bytelyst.com and admin.bytelyst.com"
    echo "2. Configure SSL certificates in Traefik"
    echo "3. Grant user access via platform-service memberships"
    echo ""
    echo "See DEPLOYMENT.md for detailed instructions"
}

# Main deployment flow
main() {
    check_prerequisites
    check_network
    deploy_devops
    deploy_admin
    health_checks
    show_info
}

# Run main function
main "$@"
