#!/usr/bin/env python3
"""Upload mail API, refresh Next.js cache, restart PM2 on production."""
import sys
from pathlib import Path

import paramiko
from scp import SCPClient

VPS_HOST = "65.75.210.95"
VPS_USER = "root"
VPS_PASS = "%8qd6oJx%PBB"
REMOTE_WEB = "/var/www/servidor/web"
REMOTE_MAIL = "/var/www/servidor/mail"
LOCAL_DIR = Path(__file__).resolve().parent.parent
MAIL_FILES = ["config.php", "template.php", "send.php", "smtp.php"]


def run(client, cmd: str, timeout: int = 60) -> tuple[str, str, int]:
    _, stdout, stderr = client.exec_command(cmd, timeout=timeout)
    out = stdout.read().decode("utf-8", errors="replace")
    err = stderr.read().decode("utf-8", errors="replace")
    code = stdout.channel.recv_exit_status()
    return out, err, code


def main() -> int:
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print(f"Connecting to {VPS_HOST}...")
    client.connect(VPS_HOST, username=VPS_USER, password=VPS_PASS, timeout=20)
    print("Connected.")

    mail_local = LOCAL_DIR / "Servidor" / "mail"
    run(client, f"mkdir -p {REMOTE_MAIL}", timeout=15)
    with SCPClient(client.get_transport()) as scp:
        for name in MAIL_FILES:
            local_file = mail_local / name
            if local_file.is_file():
                scp.put(str(local_file), f"{REMOTE_MAIL}/{name}")
                print(f"  mail uploaded: {name}")
    run(
        client,
        f"chown root:www-data {REMOTE_MAIL}/config.php && "
        f"chmod 640 {REMOTE_MAIL}/config.php && "
        f"chmod 644 {REMOTE_MAIL}/template.php {REMOTE_MAIL}/send.php {REMOTE_MAIL}/smtp.php",
        timeout=15,
    )

    print("Clearing Next.js cache...")
    out, err, code = run(
        client,
        f"cd {REMOTE_WEB} && rm -rf .next/cache && echo cache_cleared",
        timeout=30,
    )
    print(out.strip() or err.strip() or f"exit {code}")

    print("Restarting PM2 (reload env)...")
    out, err, code = run(
        client,
        f"cd {REMOTE_WEB} && pm2 restart urbangamers backup-pinger --update-env && pm2 save",
        timeout=60,
    )
    safe = out.strip()
    if safe:
        sys.stdout.buffer.write(
            (safe[-800:] if len(safe) > 800 else safe).encode("utf-8", errors="replace") + b"\n"
        )

    print("Resetting PHP opcache (mail)...")
    run(
        client,
        "php -r 'if (function_exists(\"opcache_reset\")) { opcache_reset(); echo \"opcache_reset\\n\"; } "
        "else { echo \"no_opcache\\n\"; }' 2>/dev/null || true",
        timeout=15,
    )

    print("Reloading nginx...")
    run(client, "nginx -t && systemctl reload nginx", timeout=20)

    out, _, _ = run(
        client,
        f"curl -sI https://urbangamers.es 2>&1 | head -5",
        timeout=20,
    )
    print(out.strip())

    client.close()
    print("Done: mail synced, cache cleared, PM2 restarted.")
    return 0


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