#!/usr/bin/env python3
"""Clean Bezalel Evennia setup - all-in-one script."""
import subprocess, os, sys, time

def ssh(cmd):
    r = subprocess.run(['ssh', '-o', 'ConnectTimeout=5', '-o', 'StrictHostKeyChecking=no',
                        'root@104.131.15.18', cmd],
                       capture_output=True, text=True, timeout=60)
    return r.stdout, r.stderr

def write_script(remote_path, content):
    """Write content to remote file via heredoc."""
    import tempfile
    with tempfile.NamedTemporaryFile(mode='w', suffix='.sh', delete=False) as f:
        f.write(content)
        tmppath = f.name
    subprocess.run(['scp', tmppath, f'root@104.131.15.18:{remote_path}'],
                   capture_output=True, timeout=30)
    os.unlink(tmppath)

# Script to fix Evennia on Bezalel
script = r'''#!/bin/bash
set -ex

cd /root/wizards/bezalel/evennia/bezalel_world

# Kill old processes
pkill -9 twistd 2>/dev/null || true
pkill -9 evennia 2>/dev/null || true
sleep 2

# Delete DB
rm -f server/evennia.db3

# Migrate
/root/wizards/bezalel/evennia/venv/bin/evennia migrate 2>&1 | tail -5

# Create superuser non-interactively
echo 'from evennia.accounts.accounts import AccountDB; AccountDB.objects.create_superuser("Timmy","timmy@tower.world","timmy123")' > /tmp/create_user.py

# Need to set DJANGO_SETTINGS_MODULE
export DJANGO_SETTINGS_MODULE=server.conf.settings
cd /root/wizards/bezalel/evennia/bezalel_world
/root/wizards/bezalel/evennia/venv/bin/python << PYEOF
import sys
sys.setrecursionlimit(5000)
import os
os.chdir("/root/wizards/bezalel/evennia/bezalel_world")
os.environ["DJANGO_SETTINGS_MODULE"] = "server.conf.settings"
import django
django.setup()
from evennia.accounts.accounts import AccountDB
try:
    AccountDB.objects.create_superuser("Timmy", "timmy@tower.world", "timmy123")
    print("Created superuser Timmy")
except Exception as e:
    print(f"Warning: {e}")
PYEOF

# Start Evennia
/root/wizards/bezalel/evennia/venv/bin/evennia start

# Wait for startup
for i in $(seq 1 10); do
    sleep 1
    if ss -tlnp 2>/dev/null | grep -q "400[0-2]"; then
        echo "Evennia is up after ${i}s"
        break
    fi
done

# Final status check
echo "=== Ports ==="
ss -tlnp 2>/dev/null | grep -E "400[0-2]" || echo "No Evennia ports"

echo "=== Processes ==="
ps aux | grep [t]wistd | head -3 || echo "No twistd processes"

echo "=== DB exists ==="
ls -la server/evennia.db3 2>/dev/null || echo "No DB"

echo "DONE"
'''

write_script('/tmp/bez_final_setup.sh', script)

# Execute it
print("Executing final setup on Bezalel...")
stdout, stderr = ssh('bash /tmp/bez_final_setup.sh 2>&1')
print("STDOUT:", stdout[-3000:] if len(stdout) > 3000 else stdout)
if stderr:
    print("STDERR:", stderr[-500:] if len(stderr) > 500 else stderr)
