"""Configuration helpers for MongolChat payment SDK."""

import os

from .types import MongolChatConfig


def validate_config(config: MongolChatConfig) -> None:
    """Validate the client configuration, raising if any required field is missing."""
    if not config.endpoint:
        raise ValueError("MongolChatConfig: endpoint is required")
    if not config.api_key:
        raise ValueError("MongolChatConfig: api_key is required")
    if not config.worker_key:
        raise ValueError("MongolChatConfig: worker_key is required")
    if not config.app_secret:
        raise ValueError("MongolChatConfig: app_secret is required")
    if not config.branch_no:
        raise ValueError("MongolChatConfig: branch_no is required")


def load_config_from_env() -> MongolChatConfig:
    """Load MongolChat configuration from environment variables.

    +---------------------------+--------------+
    | Variable                  | Config field |
    +---------------------------+--------------+
    | MONGOLCHAT_ENDPOINT       | endpoint     |
    | MONGOLCHAT_API_KEY        | api_key      |
    | MONGOLCHAT_WORKER_KEY     | worker_key   |
    | MONGOLCHAT_APP_SECRET     | app_secret   |
    | MONGOLCHAT_BRANCH_NO      | branch_no    |
    +---------------------------+--------------+

    Returns:
        A fully populated MongolChatConfig.

    Raises:
        ValueError: If any required environment variable is missing.
    """
    endpoint = os.environ.get("MONGOLCHAT_ENDPOINT")
    api_key = os.environ.get("MONGOLCHAT_API_KEY")
    worker_key = os.environ.get("MONGOLCHAT_WORKER_KEY")
    app_secret = os.environ.get("MONGOLCHAT_APP_SECRET")
    branch_no = os.environ.get("MONGOLCHAT_BRANCH_NO")

    if not endpoint:
        raise ValueError("MONGOLCHAT_ENDPOINT environment variable is required")
    if not api_key:
        raise ValueError("MONGOLCHAT_API_KEY environment variable is required")
    if not worker_key:
        raise ValueError("MONGOLCHAT_WORKER_KEY environment variable is required")
    if not app_secret:
        raise ValueError("MONGOLCHAT_APP_SECRET environment variable is required")
    if not branch_no:
        raise ValueError("MONGOLCHAT_BRANCH_NO environment variable is required")

    return MongolChatConfig(
        endpoint=endpoint,
        api_key=api_key,
        worker_key=worker_key,
        app_secret=app_secret,
        branch_no=branch_no,
    )
