import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('152.136.232.83', port=22, username='root', password='Jianhua105', timeout=10)

def run(cmd):
    print(f"\n>>> {cmd[:120]}")
    stdin, stdout, stderr = client.exec_command(cmd, timeout=20)
    out = stdout.read().decode('utf-8', errors='replace').strip()
    err = stderr.read().decode('utf-8', errors='replace').strip()
    if out: print(out[-800:])
    if err: print(f"ERR: {err[-200:]}")
    return out

# Check error log
run("tail -30 /root/.pm2/logs/ai-video-error.log")

# Which port is each app on?
run("grep -n 'PORT\\|listen' /www/wwwroot/zhinengtiapp/index.js | head -5")
run("grep -n 'PORT\\|listen' /www/wwwroot/aihuitu/server/index.cjs | head -5")

# Check .env PORT
run("grep PORT /www/wwwroot/zhinengtiapp/.env")
run("grep PORT /www/wwwroot/aihuitu/server/.env")

# What's listening on 3001/3002?
run("ss -tlnp | grep -E '3001|3002|3003'")

# Fix: restart ai-video from zhinengtiapp dir
run("cd /www/wwwroot/zhinengtiapp && pm2 delete ai-video 2>/dev/null; pm2 start index.js --name ai-video 2>&1")
run("sleep 3 && pm2 list")

# Test the endpoint
run("curl -s http://localhost:3001/api/system/config/public 2>/dev/null || curl -s http://localhost:3002/api/system/config/public 2>/dev/null")

client.close()
