#!/usr/bin/env python3
"""
Elestio SSH Key Retriever
Automated browser login to Elestio dashboard to download SSH key for 152.53.201.221
"""

import os
import sys
from pathlib import Path
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout

# Set LD_LIBRARY_PATH for WSL2
LIBS_PATH = "/mnt/e/genesis-system/.venvs/playwright-libs/usr/lib/x86_64-linux-gnu"
if LIBS_PATH not in os.environ.get("LD_LIBRARY_PATH", ""):
    os.environ["LD_LIBRARY_PATH"] = f"{LIBS_PATH}:{os.environ.get('LD_LIBRARY_PATH', '')}"

TARGET_IP = "152.53.201.221"
SSH_KEY_OUTPUT = Path.home() / ".ssh" / "sunaiva_elestio.pem"

def get_ssh_key():
    """Log into Elestio dashboard and retrieve SSH key for the VPS."""

    print(f"[INFO] Starting Elestio SSH key retrieval for {TARGET_IP}")
    print(f"[INFO] Output will be saved to: {SSH_KEY_OUTPUT}")

    # We need Elestio login credentials
    # Check credentials file
    creds_file = Path("/mnt/e/genesis-system/Credentials/Genesis Credentials additions.txt")

    # For now, try to navigate to the admin URL we have
    # Admin UI: https://openclaw-genesis-u50607.vm.elestio.app?token=64634c4a6aa0de3524f61496fdcceab99df1701e206083ba7b58dd8b0f0d52b0
    # But this is for openclaw service, not the Sunaiva VPS

    # We'll need to navigate to app.elestio.app and log in
    # But we don't have the email/password for Elestio account

    print("[ERROR] Elestio account credentials not found in credentials file")
    print("[ERROR] We have admin tokens for individual services, but not account login")
    print("")
    print("[SOLUTION] Kinan needs to either:")
    print("  1. Provide Elestio account email/password so we can automate login")
    print("  2. Manually download the SSH key from https://app.elestio.app")
    print("     - Log into Elestio")
    print("     - Find service with IP 152.53.201.221")
    print("     - Download SSH private key")
    print("     - Save to ~/.ssh/sunaiva_elestio.pem")
    print("     - Run: chmod 600 ~/.ssh/sunaiva_elestio.pem")
    print("")
    print("[ALTERNATIVE] Try using Elestio API with service token")

    return False

if __name__ == "__main__":
    success = get_ssh_key()
    sys.exit(0 if success else 1)
