"""
Neural LAB SDK - Authentication Resource.
OAuth and token management via Neural LAB Gateway.

Author: Anderson Henrique da Silva
Location: Minas Gerais, Brasil
Created: 2026-01-24
"""

from typing import Literal


class AuthResource:
    """
    Authentication resource for Neural LAB API.

    Provides centralized OAuth login via Neural LAB Gateway.
    Products (Hipocrates, Mercurius, Polis) can delegate auth to the gateway.

    Usage:
        client = NeuralLabClient(api_key="nl_xxx")

        # Get OAuth URL for GitHub/Google login
        oauth = client.auth.get_oauth_url("github")
        # Redirect user to: oauth["url"]

        # Exchange code for tokens (after callback)
        tokens = client.auth.exchange_code(code)

        # Refresh tokens
        new_tokens = client.auth.refresh(refresh_token)

        # Get current user
        user = client.auth.me(access_token)

        # Validate token
        is_valid = client.auth.validate(access_token)
    """

    def __init__(self, client):
        self._client = client

    def signup(
        self,
        email: str,
        password: str,
        full_name: str | None = None,
    ) -> dict:
        """
        Register a new user with email/password.

        Args:
            email: User email address
            password: User password (min 6 characters)
            full_name: Optional full name

        Returns:
            {
                "access_token": "...",
                "refresh_token": "...",
                "expires_in": 3600,
                "user": {...}
            }
        """
        return self._client.post(
            "/api/auth/signup",
            json={
                "email": email,
                "password": password,
                "full_name": full_name,
            },
        )

    def login(self, email: str, password: str) -> dict:
        """
        Login with email/password.

        Args:
            email: User email
            password: User password

        Returns:
            {
                "access_token": "...",
                "refresh_token": "...",
                "expires_in": 3600,
                "user": {...}
            }
        """
        return self._client.post(
            "/api/auth/login",
            json={"email": email, "password": password},
        )

    def get_oauth_url(
        self,
        provider: Literal["github", "google"],
        redirect_uri: str | None = None,
    ) -> dict:
        """
        Get OAuth login URL for the specified provider.

        Args:
            provider: OAuth provider ("github" or "google")
            redirect_uri: Optional custom redirect URI after auth

        Returns:
            {
                "url": "https://github.com/login/oauth/...",
                "provider": "github"
            }
        """
        params = {}
        if redirect_uri:
            params["redirect_uri"] = redirect_uri

        return self._client.get(
            f"/api/auth/login/{provider}",
            params=params if params else None,
        )

    def exchange_code(self, code: str) -> dict:
        """
        Exchange OAuth code for tokens.

        This is typically called by the OAuth callback endpoint.

        Args:
            code: OAuth authorization code from provider callback

        Returns:
            {
                "access_token": "...",
                "refresh_token": "...",
                "expires_in": 3600,
                "user": {...}
            }
        """
        return self._client.post(
            "/api/auth/exchange",
            json={"code": code},
        )

    def refresh(self, refresh_token: str) -> dict:
        """
        Refresh access token using refresh token.

        Args:
            refresh_token: Valid refresh token

        Returns:
            {
                "access_token": "...",
                "refresh_token": "...",
                "expires_in": 3600,
                "user": {...}
            }
        """
        return self._client.post(
            "/api/auth/refresh",
            json={"refresh_token": refresh_token},
        )

    def me(self, access_token: str | None = None) -> dict:
        """
        Get current authenticated user.

        Args:
            access_token: Optional access token (uses client token if not provided)

        Returns:
            {
                "id": "uuid",
                "email": "user@example.com",
                "full_name": "John Doe",
                "avatar_url": "https://...",
                "provider": "github",
                "role": "user"
            }
        """
        headers = {}
        if access_token:
            headers["Authorization"] = f"Bearer {access_token}"

        return self._client.get("/api/auth/me", headers=headers)

    def validate(self, access_token: str) -> dict:
        """
        Validate an access token.

        Args:
            access_token: Token to validate

        Returns:
            {
                "valid": true,
                "user_id": "uuid",
                "expires_at": "2026-01-25T00:00:00Z"
            }
        """
        return self._client.post(
            "/api/auth/validate",
            json={"token": access_token},
        )

    def logout(self) -> dict:
        """
        Logout current user (invalidate session).

        Returns:
            {"message": "Logged out successfully"}
        """
        return self._client.post("/api/auth/logout")
