"""Browser-based authentication flow."""

import webbrowser
from urllib.parse import unquote

from .config import get_environment_config, add_organization, Credentials


def perform_login(environment: str) -> Credentials | None:
    """Perform browser-based login flow.

    Args:
        environment: The environment to log in to ("development" or "production")

    Returns:
        Credentials dict if successful, None if failed or cancelled
    """
    # Import here to avoid circular imports
    from .server import CallbackServer

    env_config = get_environment_config(environment)
    server = CallbackServer()

    # Start local server
    port = server.start()

    try:
        # Build auth URL and open browser
        # The React app handles /cli/auth route and shows org selection
        auth_url = f"{env_config['auth_url']}/cli/auth?port={port}"
        webbrowser.open(auth_url)

        # Wait for callback
        result = server.wait_for_callback(timeout=300)

        if not result or result.get("error") or not result.get("token"):
            return None

        # Extract credential data
        org_id = result["org_id"]
        org_name = unquote(result["org_name"]) if result["org_name"] else ""
        user_email = unquote(result["email"]) if result["email"] else ""
        token = result["token"]

        # Save using new multi-org format
        add_organization(
            env=environment,
            org_id=org_id,
            name=org_name,
            token=token,
            user_email=user_email,
        )

        # Return legacy format for caller compatibility
        return {
            "token": token,
            "organization_id": org_id,
            "organization_name": org_name,
            "user_email": user_email,
        }

    finally:
        server.stop()
