import paramiko

c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect('160.187.143.253', username='root', password=';ur7n)LC1BQ;')

def r(cmd):
    print(f"Executing: {cmd}")
    try:
        _, so, se = c.exec_command(cmd, timeout=30)
        stdout = so.read().decode('utf-8', 'replace').strip()
        stderr = se.read().decode('utf-8', 'replace').strip()
        if stdout: print(f"STDOUT:\n{stdout}")
        if stderr: print(f"STDERR:\n{stderr}")
        return stdout
    except Exception as e: 
        return str(e)

# 1. Check PostgreSQL Connections
r('sudo -u postgres psql -c "SELECT count(*) FROM pg_stat_activity;"')

# 2. Try the login via curl to see what the server responds and check PM2 logs simultaneously
r("""
curl -X POST http://127.0.0.1:3001/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"tsm@pc24.id","password":"123"}'
""")

# 3. Check what happens if I run the test_db.js directly on VPS
r("""
cat << 'EOF' > /var/www/iam/test_db.js
const postgres = require('postgres');
require('dotenv').config({ path: '.env.local' });
const client = postgres(process.env.DATABASE_URL);
client\`SELECT 1\`.then(()=>console.log('OK')).catch(e=>console.error(e)).finally(()=>client.end());
EOF
cd /var/www/iam && node test_db.js
""")

c.close()
