#!/usr/bin/env python3
import sys
import paramiko
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=40):
    _, o, e = c.exec_command(cmd, timeout=t)
    return (o.read() + e.read()).decode("utf-8", errors="replace")

tests = [
    "node /tmp/ug_mail_test.mjs '3HNF0C61gRWDYJFM3RqxtX5QP1t' 2>&1",
    "grep -r 'Email API error' /var/www/servidor/web/logs/ 2>/dev/null | tail -5",
    "cd /var/www/servidor/web && node -e \"require('dotenv').config({path:'.env.production'}); console.log(process.env.EMAIL_API_URL, process.env.EMAIL_API_HOST, process.env.EMAIL_API_KEY ? 'key_ok' : 'no_key');\" 2>&1",
]

# write node test if missing
run("""cat > /tmp/ug_mail_test.mjs << 'EOF'
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('with_host status', r.status, 'body', t.trim());
}).catch((e) => console.log('with_host error', e.message));

fetch('http://127.0.0.1/mail/send.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: new URLSearchParams({ key, email: 'unplayer3467@gmail.com', code: '123456', type: 'register' }),
}).then(async (r) => {
  const t = await r.text();
  console.log('no_host status', r.status, 'body', t.trim().slice(0,80));
}).catch((e) => console.log('no_host error', e.message));
EOF""")

for t in tests:
    out = run(t)
    sys.stdout.buffer.write(f"\n=== {t[:60]} ===\n".encode())
    sys.stdout.buffer.write(out.encode("utf-8", errors="replace"))

c.close()
