#!/usr/bin/env python3
import paramiko
import re

c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("65.75.210.95", username="root", password="%8qd6oJx%PBB", timeout=20)

def run(cmd, t=30):
    _, o, e = c.exec_command(cmd, timeout=t)
    return (o.read() + e.read()).decode("utf-8", errors="replace")

env = run("grep -E '^EMAIL_' /var/www/servidor/web/.env.production")
print("ENV:\n", env)

key_m = re.search(r"EMAIL_API_KEY=(.+)", env)
env_key = key_m.group(1).strip() if key_m else ""
cfg = run("grep api_key /var/www/servidor/mail/config.php")
print("CONFIG:", cfg.strip())

print("\n=== curl internal (like web should) ===")
print(run(
    f"curl -sS -m 30 -w '\\nhttp=%{{http_code}}\\n' "
    f"-H 'Host: models.hostlanty.com' "
    f"-X POST 'http://127.0.0.1/mail/send.php' "
    f"-d 'key={env_key}&email=unplayer3467@gmail.com&code=123456&type=register'"
))

print("\n=== PM2 logs (email) ===")
print(run("grep -i 'Email API' /var/www/servidor/web/logs/error.log 2>/dev/null | tail -10"))
print(run("pm2 logs urbangamers --lines 15 --nostream 2>&1 | tail -20"))

print("\n=== nginx/php errors ===")
print(run("grep -E 'UG-MAIL|mail/send|Permission denied' /var/log/nginx/error.log 2>/dev/null | tail -8"))

print("\n=== node fetch test ===")
node_script = r'''
const key = process.argv[1];
fetch('http://127.0.0.1/mail/send.php', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    Host: 'models.hostlanty.com',
  },
  body: new URLSearchParams({ key, email: 'unplayer3467@gmail.com', code: '123456', type: 'register' }),
}).then(async (r) => {
  const t = await r.text();
  console.log('status', r.status, 'body', t.trim());
}).catch((e) => console.log('error', e.message));
'''
run(f"cat > /tmp/ug_mail_test.mjs << 'EOF'\n{node_script}\nEOF")
print(run(f"node /tmp/ug_mail_test.mjs '{env_key}' 2>&1", t=30))

c.close()
