"""Login flow for cube-agent — saves API key locally."""

from __future__ import annotations

import asyncio
import logging
import secrets
import webbrowser

import httpx

from cube_agent.auth.keystore import save_key, delete_key, has_key
from cube_agent.config import get_cloud_url

logger = logging.getLogger(__name__)


def login(api_key: str) -> str:
    """Store the provided API key (for service accounts / CI)."""
    save_key(api_key)
    return "API key saved. cube-agent is authenticated."


async def login_browser() -> str:
    """Browser-based login: open sign-in page, poll for API key.

    1. Generate a random session_id
    2. Open browser to {cloud_url}/auth/login?session_id={session_id}
    3. Poll {cloud_url}/auth/session/{session_id} every 2s (max 60s)
    4. On success: save the API key locally
    """
    cloud_url = get_cloud_url().rstrip("/")
    session_id = secrets.token_urlsafe(32)

    login_url = f"{cloud_url}/auth/login?session_id={session_id}"
    poll_url = f"{cloud_url}/auth/session/{session_id}"

    # Open the browser
    webbrowser.open(login_url)

    # Poll for the API key
    async with httpx.AsyncClient() as client:
        for _ in range(30):  # 30 * 2s = 60s max
            await asyncio.sleep(2)
            try:
                resp = await client.get(poll_url, timeout=10)
                if resp.status_code == 200:
                    data = resp.json()
                    if data.get("status") == "ready":
                        api_key = data["api_key"]
                        save_key(api_key)
                        return "Login successful! API key saved."
            except Exception as e:
                logger.debug("Poll error (will retry): %s", e)

    return "Login timed out. Try again or use `agent_login` with an API key."


def logout() -> str:
    """Remove the stored API key."""
    if delete_key():
        return "API key removed."
    return "No API key was stored."


def status() -> str:
    """Check authentication status."""
    if has_key():
        return "Authenticated (API key stored)."
    return "Not authenticated. Run cube-agent login <api-key> to configure."
