"""Type definitions for the Fastn Auth SDK."""

from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Optional


class AuthStatus(str, Enum):
    """Status of the authentication session."""

    INACTIVE = "INACTIVE"
    ACTIVE = "ACTIVE"
    FAILED = "FAILED"


@dataclass
class FastnAuthConfig:
    """Configuration options for the FastnAuth client.

    Attributes:
        space_id: The space/workspace ID.
        api_key: API key for authentication.
        base_url: Base URL for the Fastn API (defaults to https://live.fastn.ai/api).
    """

    space_id: str
    api_key: str
    base_url: str = "https://live.fastn.ai/api"


@dataclass
class InitOptions:
    """Options for initializing a connector authentication flow.

    Attributes:
        connector_id: The connector ID (e.g., "google-sheets", "salesforce").
        org_id: Organization ID (optional).
        tenant_id: Tenant ID (optional).
        connection_id: Connection instance ID (defaults to "default").
    """

    connector_id: str
    org_id: Optional[str] = None
    tenant_id: Optional[str] = None
    connection_id: Optional[str] = None


@dataclass
class InitResponse:
    """Response from the connect init endpoint.

    Attributes:
        id: Unique identifier for the connection session.
        state_key: State key for OAuth flow.
        status: Current status of the connection.
        redirect_url: OAuth redirect URL.
    """

    id: str
    state_key: str
    status: AuthStatus
    redirect_url: Optional[str] = None


@dataclass
class StatusResponse:
    """Response from the status polling endpoint.

    Attributes:
        status: Current status of the connection.
        error_message: Error message if status is FAILED.
    """

    status: AuthStatus
    error_message: Optional[str] = None


@dataclass
class Credentials:
    """Credentials returned after successful activation.

    Attributes:
        access_token: Access token for the connector.
        refresh_token: Refresh token for the connector.
        expires_at: Token expiry timestamp.
        extra: Additional credential data.
    """

    access_token: Optional[str] = None
    refresh_token: Optional[str] = None
    expires_at: Optional[str] = None
    extra: dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> "Credentials":
        """Create a Credentials instance from a dictionary."""
        return cls(
            access_token=data.get("accessToken"),
            refresh_token=data.get("refreshToken"),
            expires_at=data.get("expiresAt"),
            extra={
                k: v
                for k, v in data.items()
                if k not in ("accessToken", "refreshToken", "expiresAt")
            },
        )


@dataclass
class AuthResult:
    """Result of a completed authentication session.

    Attributes:
        status: Final status of the authentication.
        credentials: Credentials if authentication was successful.
        error_message: Error message if authentication failed.
    """

    status: AuthStatus
    credentials: Optional[Credentials] = None
    error_message: Optional[str] = None


@dataclass
class PollOptions:
    """Options for polling the authentication status.

    Attributes:
        interval: Polling interval in seconds (default: 2.0).
        timeout: Maximum time to wait in seconds (default: 300 - 5 minutes).
    """

    interval: float = 2.0
    timeout: float = 300.0
