"""Configuration management for ArthHub MCP Server."""

# Import built-in modules
import os
from typing import Any

# Import third-party modules
from arthub_api import OpenAPI
from arthub_api import api_config_qq
from loguru import logger

# Import local modules
from arthub_mcp_server.errors import ArthubError
from arthub_mcp_server.errors import ErrorCode

# Global OpenAPI instance
_open_api_instance: OpenAPI | None = None


def get_open_api() -> OpenAPI:
    """Get or create OpenAPI instance.

    Returns:
        OpenAPI: Authenticated OpenAPI instance

    Raises:
        ArthubError: If authentication fails or configuration is missing

    """
    global _open_api_instance

    if _open_api_instance is not None:
        return _open_api_instance

    # Get API configuration
    api_config_name = os.getenv("ARTHUB_API_CONFIG", "api_config_qq")
    api_config = _get_api_config(api_config_name)

    # Create OpenAPI instance
    _open_api_instance = OpenAPI(api_config)

    # Authenticate
    _authenticate(_open_api_instance)

    logger.info("ArthHub OpenAPI initialized successfully")
    return _open_api_instance


def _get_api_config(config_name: str) -> Any:
    """Get API configuration by name.

    Args:
        config_name: Name of the API configuration

    Returns:
        Any: API configuration object

    Raises:
        ArthubError: If configuration is not found

    """
    # Currently only support api_config_qq
    if config_name == "api_config_qq":
        return api_config_qq

    error_msg = f"Unsupported API config: {config_name}"
    logger.error(error_msg)
    raise ArthubError(error_msg, ErrorCode.CONFIG_ERROR)


def _authenticate(open_api: OpenAPI) -> None:
    """Authenticate with ArthHub.

    Args:
        open_api: OpenAPI instance to authenticate

    Raises:
        ArthubError: If authentication fails

    """
    # Method 1: Try public token authentication
    public_token = os.getenv("ARTHUB_PUBLIC_TOKEN")
    if public_token:
        logger.info("Authenticating with public token")
        open_api.set_public_token(public_token)
        return

    # Method 2: Try email/password authentication
    email = os.getenv("ARTHUB_EMAIL")
    password = os.getenv("ARTHUB_PASSWORD")
    public_key = os.getenv("ARTHUB_PUBLIC_KEY")

    if not all([email, password, public_key]):
        error_msg = (
            "ArthHub authentication not configured. Please set either:\n"
            "1. ARTHUB_PUBLIC_TOKEN, or\n"
            "2. ARTHUB_EMAIL, ARTHUB_PASSWORD, and ARTHUB_PUBLIC_KEY"
        )
        logger.error(error_msg)
        raise ArthubError(error_msg, ErrorCode.CONFIG_ERROR)

    logger.info(f"Authenticating with email: {email}")
    res = open_api.login(
        account_name=email,
        password=password,
        login_public_keys=public_key
    )

    if not res.is_succeeded():
        error_msg = f"ArthHub login failed: {res.error_message()}"
        logger.error(error_msg)
        raise ArthubError(error_msg, ErrorCode.AUTH_ERROR)

    logger.info("ArthHub authentication successful")


def reset_open_api() -> None:
    """Reset OpenAPI instance (useful for testing)."""
    global _open_api_instance
    _open_api_instance = None

