from dataclasses import dataclass
from typing import Optional

from .logger import Logger


class ProviderResolutionError(Exception):
    pass


OPENAI_MODELS = {
    "gpt-5",
    "gpt-5.1",
    "gpt-5.1-codex",
    "gpt5-nano",
}


@dataclass
class ProviderConfig:
    model: str
    provider: str
    base_url: Optional[str]
    api_key: Optional[str]
    api_mode: str  # "responses" or "completion"


def resolve_provider(env: dict, logger: Optional[Logger] = None) -> ProviderConfig:
    log = logger or Logger()

    model = env.get("MODEL")
    if not model:
        raise ProviderResolutionError("MODEL is not set; unable to determine provider.")

    openai_api_key = env.get("OPENAI_API_KEY")
    openai_base_url = env.get("OPENAI_BASE_URL")
    lmstudio_base = env.get("LMSTUDIO_BASE_URL")
    ollama_base = env.get("OLLAMA_BASE_URL")

    if model in OPENAI_MODELS:
        if not openai_api_key:
            raise ProviderResolutionError(
                "OPENAI_API_KEY is required for OpenAI models but is missing."
            )
        log.info("Using OpenAI provider", to_stdout=False)
        return ProviderConfig(
            model=model,
            provider="openai",
            base_url=openai_base_url,
            api_key=openai_api_key,
            api_mode="responses",
        )

    if lmstudio_base:
        log.info("Using LMStudio provider", to_stdout=False)
        return ProviderConfig(
            model=model,
            provider="lmstudio",
            base_url=lmstudio_base,
            api_key=None,
            api_mode="completion",
        )

    if ollama_base:
        log.info("Using Ollama provider", to_stdout=False)
        return ProviderConfig(
            model=model,
            provider="ollama",
            base_url=ollama_base,
            api_key=None,
            api_mode="completion",
        )

    raise ProviderResolutionError(
        "Unable to determine provider. Set LMSTUDIO_BASE_URL or OLLAMA_BASE_URL "
        "for non-OpenAI models, or provide a supported OpenAI model with OPENAI_API_KEY."
    )
