"""Configuration management for Influ2 MCP server."""

from __future__ import annotations

import os
from functools import lru_cache

from pydantic_settings import BaseSettings, SettingsConfigDict


class Influ2Config(BaseSettings):
    """Influ2 MCP server configuration, loaded from environment variables."""

    model_config = SettingsConfigDict(env_prefix="INFLU2_")

    api_key: str = ""
    client_id: str | None = None
    base_url: str = "https://v2-api.influ2.com"
    poll_timeout: int = 120


@lru_cache
def get_config() -> Influ2Config:
    """Get the singleton configuration instance."""
    return Influ2Config()


def resolve_client_id(explicit: str | None = None) -> str:
    """Resolve client_id from explicit parameter, env var, or raise an error.

    Priority:
    1. Explicit parameter passed by the LLM
    2. INFLU2_CLIENT_ID environment variable
    3. Error with guidance to call influ2_list_clients
    """
    if explicit:
        return explicit

    config = get_config()
    if config.client_id:
        return config.client_id

    from influ2_mcp.errors import Influ2Error

    raise Influ2Error(
        message=(
            "No client_id provided and INFLU2_CLIENT_ID is not configured. "
            "Call influ2_list_clients to discover available client IDs, then pass "
            "the client_id parameter explicitly."
        ),
        suggestion="Call influ2_list_clients first to get your client_id.",
    )
