import paramiko
import time
import sys

# MULTIVERSE TRIPLE-NODE DEPLOYMENT ENGINE v1.0
# Deploying to Alpha, Beta, Gamma nodes for JUMPA.ID IAM

NODES = [
    {
        "name": "ALPHA (Primary Mesh)",
        "ip": "160.187.143.253",
        "root": ";ur7n)LC1BQ;",
        "path": "/var/www/iam"
    },
    {
        "name": "BETA (Secondary Mesh)",
        "ip": "160.187.143.133",
        "root": "jKLfGaB2Yx5Y",
        "path": "/var/www/iam"
    },
    {
        "name": "GAMMA (Forge & Archive)",
        "ip": "160.187.143.172",
        "root": "OREa%d=j2s(T",
        "path": "/var/www/iam"
    }
]

def deploy_to_node(node):
    print(f"\n[DEPLOYING TO {node['name']}] at {node['ip']}")
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(node['ip'], username='root', password=node['root'], timeout=30)
        
        # Ensure git is initialized and pulling correctly
        git_init_cmd = f"""
        cd {node['path']}
        if [ ! -d .git ]; then
            git init
            git remote add origin http://supreme_commander:XCU_Forge_2026!@160.187.143.130/supreme_commander/multiverse.git
        fi
        git fetch origin master
        git reset --hard origin/master
        # Clean up interfering ghost directories
        rm -rf jumpa.id xcom-ultra
        """
        
        commands = [
            git_init_cmd,
            f"cd {node['path']} && npm install --prefer-offline",
            f"cd {node['path']} && npm run build",
            "pm2 restart iam || pm2 start npm --name 'iam' -- run start"
        ]
        
        for cmd in commands:
            print(f"  > {cmd}")
            stdin, stdout, stderr = ssh.exec_command(cmd)
            # Wait for command to finish
            exit_status = stdout.channel.recv_exit_status()
            out = stdout.read().decode().strip()
            err = stderr.read().decode().strip()
            
            if exit_status != 0:
                print(f"  FAILED ({exit_status}): {err}")
                if "npm run build" in cmd: # Build failure is critical
                   ssh.close()
                   return False
            else:
                if out: print(f"  OK")
                
        ssh.close()
        print(f"[SUCCESS] {node['name']} is now running the ULTRA codebase.")
        return True
    except Exception as e:
        print(f"  CRITICAL FAILURE: {str(e)}")
        return False

if __name__ == "__main__":
    print("JUMPA.ID MULTIVERSE PROPAGATION ENGINE")
    print("===========================================")
    
    success_count = 0
    for node in NODES:
        if deploy_to_node(node):
            success_count += 1
            
    print("\n===========================================")
    print(f"PROPAGATION COMPLETE: {success_count}/{len(NODES)} nodes synchronized.")
    if success_count == len(NODES):
        print("THE MULTIVERSE IS NOW IN SYNC")
    else:
        print("SOME NODES FAILED. CHECK LOGS.")
