from __future__ import annotations

from plytix.api import PlytixApiClient
from plytix.auth import fetch_plytix_api_token
from settings import PlytixApiConfig, load_plytix_api_config


def build_plytix_client(cfg: PlytixApiConfig | None = None) -> PlytixApiClient:
    """Authenticated Plytix client — fetches bearer token when key/password are set."""
    cfg = cfg or load_plytix_api_config()
    token = str(cfg.api_token or "").strip()
    if not token and cfg.api_key and cfg.api_password:
        token = fetch_plytix_api_token(cfg.api_key, cfg.api_password)
    if not token and not cfg.api_key:
        raise ValueError("PLYTIX_API_TOKEN or PLYTIX_API_KEY is required")
    return PlytixApiClient(
        base_url=cfg.base_url,
        api_key=cfg.api_key,
        api_password=cfg.api_password,
        api_token=token,
    )
