"""Authentication — login, tourist access, and account info.

In this example, we:
  - Log in with email and password
  - Use a pre-existing token to skip the login round-trip
  - Show tourist (anonymous) access as an alternative
  - Retrieve account information

All responses are wrapped in APIEnvelope. Use .value to access the data.
If the server returns no data, .value raises MissingDataError (seaart.exceptions).

Requires:
    SEAART_EMAIL and SEAART_PASSWORD environment variables, or
    SEAART_TOKEN for token-based authentication.
    No credentials needed for tourist_access().
"""

from __future__ import annotations

import os

from seaart import SyncClient


# ---------------------------------------------------------------------------
# Credentials
# ---------------------------------------------------------------------------


def login_with_credentials() -> None:
    """Log in using email and password."""
    # Use as a context manager to safely close the session on exit.
    with SyncClient() as client:
        session = client.auth.login(
            email=os.environ["SEAART_EMAIL"],
            password=os.environ["SEAART_PASSWORD"],
        )
        # After login, client.token is set automatically for all subsequent requests.
        print(f"Logged in: {session.value.account.email}")
        print(f"Token: {client.token[:20]}")  # type: ignore[index]

        info = client.account.me()
        print(f"Account ID: {info.value.id}")
        print(f"Nickname: {info.value.name}")


# ---------------------------------------------------------------------------
# Token
# ---------------------------------------------------------------------------


def login_with_token() -> None:
    """Use a pre-existing token.

    Pass the token directly to avoid a login round-trip.
    You can also configure timeout, proxy, impersonate, and other options here.
    """
    with SyncClient(token=os.environ["SEAART_TOKEN"]) as client:
        info = client.account.me()
        print(f"Account ID: {info.value.id}")
        print(f"Nickname: {info.value.name}")


# ---------------------------------------------------------------------------
# Tourist (no account)
# ---------------------------------------------------------------------------


def tourist_access() -> None:
    """Access the API without an account.

    SeaArt associates each tourist session with a device_id (UUID4).
    If you don't provide one, it is generated automatically.
    Please note that tourist accounts may have limmited access.
    """
    with SyncClient() as client:
        session = client.auth.login_as_tourist()
        print(f"Tourist ID: {session.value.account.id}")
        print(f"Nickname: {session.value.account.name}")


if __name__ == "__main__":
    login_with_credentials()