"""Auth operations — login, logout, whoami."""

from __future__ import annotations

from typing import Any

from kodara.cloud.client import (
    clear_session,
    get_client,
    is_authenticated,
    load_session,
    save_session,
)


def request_otp(email: str) -> None:
    """
    Send a magic-link / OTP to *email* via Supabase.

    Uses ``client.auth.sign_in_with_otp({"email": email})``.
    The user will receive a 6-digit code in their inbox.
    """
    client = get_client()
    client.auth.sign_in_with_otp({"email": email})


def verify_otp(email: str, token: str) -> dict:
    """
    Verify the 6-digit OTP code and persist the resulting session.

    Uses ``client.auth.verify_otp({"email": email, "token": token, "type": "email"})``.

    Returns:
        dict with at least ``{"email": ..., "id": ...}`` from the Supabase user object.
    """
    client = get_client()
    response = client.auth.verify_otp({"email": email, "token": token, "type": "email"})

    # Supabase Python SDK v2 returns an AuthResponse with .session and .user
    session = getattr(response, "session", None) or response
    save_session(session)

    user = getattr(response, "user", None)
    if user is None:
        # Fallback: session may carry user info
        user = getattr(session, "user", None)

    if user is not None:
        return {
            "email": getattr(user, "email", email),
            "id": getattr(user, "id", ""),
        }
    return {"email": email}


def logout() -> None:
    """Sign out from Supabase and clear ~/.kodara/auth.json."""
    try:
        client = get_client()
        client.auth.sign_out()
    except Exception:
        pass  # Even if remote sign-out fails, clear local session
    finally:
        clear_session()


def get_current_user() -> dict | None:
    """
    Return current user info from the stored session.

    Returns None if the user is not logged in (no session or expired).
    """
    if not is_authenticated():
        return None
    session = load_session()
    if not session:
        return None
    email = session.get("email", "")
    return {"email": email} if email else None
