#!/usr/bin/env python3
"""Diagnose email API from production VPS (no secrets printed)."""
import sys

import paramiko

VPS_HOST = "65.75.210.95"
VPS_USER = "root"
VPS_PASS = "%8qd6oJx%PBB"
REMOTE_MAIL = "/var/www/servidor/mail"
REMOTE_WEB = "/var/www/servidor/web"


def run(client, cmd: str, timeout: int = 30) -> str:
    _, stdout, stderr = client.exec_command(cmd, timeout=timeout)
    out = stdout.read().decode("utf-8", errors="replace")
    err = stderr.read().decode("utf-8", errors="replace")
    return (out + err).strip()


def parse_env(text: str) -> dict[str, str]:
    values: dict[str, str] = {}
    for line in text.splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, _, value = line.partition("=")
        values[key.strip()] = value.strip()
    return values


def main() -> int:
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(VPS_HOST, username=VPS_USER, password=VPS_PASS, timeout=20)

    env_text = run(client, f"cat {REMOTE_WEB}/.env.production 2>/dev/null")
    env = parse_env(env_text)
    api_url = env.get("EMAIL_API_URL", "(missing)")
    has_key = "yes" if env.get("EMAIL_API_KEY") else "no"

    print("=== ENV ===")
    print(f"EMAIL_API_URL={api_url}")
    print(f"EMAIL_API_KEY set: {has_key}")

    print("\n=== DNS ===")
    print(run(client, "getent hosts models.hostlanty.com 2>&1 || nslookup models.hostlanty.com 2>&1 | head -8"))

    print("\n=== CURL external HTTPS ===")
    print(
        run(
            client,
            "curl -sS -m 15 -o /tmp/ug_mail_body.txt -w 'http_code=%{http_code} time=%{time_total}s\\n' "
            "-X POST 'https://models.hostlanty.com/mail/send.php' "
            "-d 'key=invalid&email=test@example.com&code=123456&type=register' 2>&1; "
            "echo body:; cat /tmp/ug_mail_body.txt 2>/dev/null",
        )
    )

    print("\n=== CURL local file via php ===")
    print(
        run(
            client,
            f"php -r \"echo is_file('{REMOTE_MAIL}/send.php') ? 'send.php exists\\n' : 'send.php missing\\n';\"",
        )
    )

    print("\n=== CURL localhost mail path ===")
    for url in [
        "http://127.0.0.1/mail/send.php",
        "http://127.0.0.1:80/mail/send.php",
        "https://models.hostlanty.com/mail/send.php",
    ]:
        print(f"-- {url}")
        print(
            run(
                client,
                f"curl -sS -m 10 -o /tmp/ug_mail2.txt -w 'http_code=%{{http_code}}\\n' "
                f"-X POST '{url}' -d 'key=invalid&email=test@example.com&code=123456&type=register' 2>&1; "
                "cat /tmp/ug_mail2.txt 2>/dev/null; echo",
            )
        )

    print("\n=== nginx sites ===")
    print(run(client, "ls -la /etc/nginx/sites-enabled/ 2>&1"))

    print("\n=== PM2 recent mail errors ===")
    print(run(client, f"grep -i 'Email API' {REMOTE_WEB}/logs/error.log 2>/dev/null | tail -5"))

    client.close()
    return 0


if __name__ == "__main__":
    sys.exit(main())
