#!/bin/bash
# Simplified Deployment Status Check
# Shows what containers are deployed and their status

set +e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/load-env.sh"
load_env_file

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
PROXMOX_PORT="${PROXMOX_PORT:-8006}"

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║           Deployment Status - ${PROXMOX_HOST}                    ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Get first node
NODES_RESPONSE=$(curl -k -s -m 10 \
    -H "Authorization: PVEAPIToken=${PROXMOX_USER}!${PROXMOX_TOKEN_NAME}=${PROXMOX_TOKEN_VALUE}" \
    "https://${PROXMOX_HOST}:${PROXMOX_PORT}/api2/json/nodes" 2>&1)

FIRST_NODE=$(echo "$NODES_RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin)['data'][0]['node'])" 2>/dev/null)

# Get containers
CONTAINERS_RESPONSE=$(curl -k -s -m 10 \
    -H "Authorization: PVEAPIToken=${PROXMOX_USER}!${PROXMOX_TOKEN_NAME}=${PROXMOX_TOKEN_VALUE}" \
    "https://${PROXMOX_HOST}:${PROXMOX_PORT}/api2/json/nodes/${FIRST_NODE}/lxc" 2>&1)

# Parse and display
echo "$CONTAINERS_RESPONSE" | python3 << 'PYEOF'
import sys, json

try:
    data = json.load(sys.stdin)['data']
    
    if len(data) == 0:
        print("No containers found")
        sys.exit(0)
    
    # Categorize containers
    validators = []
    sentries = []
    rpc_nodes = []
    services = []
    monitoring = []
    explorer = []
    hyperledger = []
    other = []
    
    for container in data:
        vmid = container['vmid']
        name = container.get('name', 'N/A')
        status = container.get('status', 'unknown')
        
        if 106 <= vmid <= 109:
            validators.append((vmid, name, status))
        elif 110 <= vmid <= 114:
            sentries.append((vmid, name, status))
        elif 115 <= vmid <= 119:
            rpc_nodes.append((vmid, name, status))
        elif 120 <= vmid <= 129:
            services.append((vmid, name, status))
        elif 130 <= vmid <= 139:
            monitoring.append((vmid, name, status))
        elif 140 <= vmid <= 149:
            explorer.append((vmid, name, status))
        elif 150 <= vmid <= 153:
            hyperledger.append((vmid, name, status))
        else:
            other.append((vmid, name, status))
    
    # Display by category
    def print_category(title, containers, color_code):
        if containers:
            print(f"\n{title} ({len(containers)}):")
            print(f"  {'VMID':<6} {'Name':<30} {'Status':<10}")
            print("  " + "-" * 48)
            for vmid, name, status in sorted(containers):
                status_display = f"\033[32m{status}\033[0m" if status == "running" else f"\033[31m{status}\033[0m" if status == "stopped" else f"\033[33m{status}\033[0m"
                print(f"  {vmid:<6} {name:<30} {status_display}")
    
    print_category("Validators", validators, 36)
    print_category("Sentries", sentries, 34)
    print_category("RPC Nodes", rpc_nodes, 32)
    print_category("Services", services, 33)
    print_category("Monitoring", monitoring, 36)
    print_category("Explorer", explorer, 34)
    print_category("Hyperledger", hyperledger, 32)
    
    if other:
        print(f"\nOther Containers ({len(other)}):")
        for vmid, name, status in sorted(other):
            status_display = f"\033[32m{status}\033[0m" if status == "running" else f"\033[31m{status}\033[0m" if status == "stopped" else f"\033[33m{status}\033[0m"
            print(f"  VMID {vmid}: {name} ({status_display})")
    
    # Summary
    print("\n" + "=" * 60)
    print("Summary")
    print("=" * 60)
    print(f"Total Containers: {len(data)}")
    
    running = sum(1 for c in data if c.get('status') == 'running')
    stopped = sum(1 for c in data if c.get('status') == 'stopped')
    print(f"  Running: {running}")
    print(f"  Stopped: {stopped}")
    
    print(f"\nSMOM-DBIS-138 Deployment:")
    print(f"  Validators: {len(validators)}/4")
    print(f"  Sentries: {len(sentries)}/3")
    print(f"  RPC Nodes: {len(rpc_nodes)}/3")
    print(f"  Services: {len(services)}")
    print(f"  Monitoring: {len(monitoring)}")
    print(f"  Explorer: {len(explorer)}")
    print(f"  Hyperledger: {len(hyperledger)}")
    
    if len(validators) == 0 and len(sentries) == 0 and len(rpc_nodes) == 0:
        print("\n⚠️  No SMOM-DBIS-138 containers found")
        print("To deploy: ./scripts/deploy-to-proxmox-host.sh")
    else:
        print("\n✅ SMOM-DBIS-138 deployment found")
        
except Exception as e:
    print(f"Error: {e}")
    sys.exit(1)
PYEOF

