#!/usr/bin/env python3
"""Sync BotDiscord credentials to production .env and redeploy web."""
import sys
from pathlib import Path

import paramiko

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from deploy_vps import (  # noqa: E402
    REMOTE_DIR,
    VPS_HOST,
    VPS_PASS,
    VPS_USER,
    merge_production_env,
    upload_project,
    write_production_env,
)


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


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)

    print("Patching .env.production with BotDiscord bot...")
    write_production_env(client)

    print("Uploading code...")
    upload_project(client)

    print("Building and restarting PM2...")
    build_out = run(
        client,
        f"cd {REMOTE_DIR} && npm ci && npm run build && pm2 restart urbangamers --update-env",
        timeout=900,
    )
    print(build_out[-3000:])

    print("\nDiscord env (no secrets):")
    print(run(f"grep -E '^(NEXT_PUBLIC_DISCORD_CLIENT_ID|DISCORD_GUILD_ID|DISCORD_LINKED_ROLE_ID)=' {REMOTE_DIR}/.env.production"))
    print("\nRecent role grant logs:")
    print(run(f"grep -i 'linked Discord role' {REMOTE_DIR}/logs/error.log 2>/dev/null | tail -5 || true"))

    client.close()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
