#!/usr/bin/env python3
"""Check Discord OAuth env on VPS without printing secrets."""
import sys
from pathlib import Path

import paramiko

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from deploy_vps import REMOTE_DIR, VPS_HOST, VPS_PASS, VPS_USER, write_production_env


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


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(run(client, f"grep -E '^(NEXT_PUBLIC_DISCORD_CLIENT_ID|DISCORD_GUILD_ID|DISCORD_LINKED_ROLE_ID)=' {REMOTE_DIR}/.env.production"))
    print(
        run(
            client,
            f"python3 - <<'PY'\n"
            f"from pathlib import Path\n"
            f"env = Path('{REMOTE_DIR}/.env.production').read_text()\n"
            f"keys = ['DISCORD_BOT_TOKEN', 'DISCORD_CLIENT_SECRET']\n"
            f"for line in env.splitlines():\n"
            f"  for key in keys:\n"
            f"    if line.startswith(key + '='):\n"
            f"      value = line.split('=', 1)[1]\n"
            f"      print(key + '=' + ('set' if value and value != 'PENDING' else 'MISSING'))\n"
            f"PY",
        )
    )

    if "--repair-env" in sys.argv:
        print("\nRepairing .env.production (preserve remote Discord OAuth)...")
        write_production_env(client)
        print("Done.")

    client.close()
    return 0


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