"""Model factory."""

from __future__ import annotations

import os
import sys

# Re-export from SDK
from krim_sdk.models.base import Model
from krim_sdk.models.claude import ClaudeModel
from krim_sdk.models.openai import OpenAIModel
from krim_sdk.models.vertex import VertexModel

DEFAULT_MODELS = {
    "claude": "claude-opus-4-6",
    "openai": "gpt-5.2",
    "vertex_ai": "claude-opus-4-6",
}

_API_KEY_ENV = {
    "claude": "ANTHROPIC_API_KEY",
    "openai": "OPENAI_API_KEY",
}

_API_KEY_URLS = {
    "claude": "https://console.anthropic.com/settings/keys",
    "openai": "https://platform.openai.com/api-keys",
}


class MissingAPIKeyError(Exception):
    """Raised when the required API key is not set."""
    pass


def check_api_key(provider: str) -> None:
    """Check if the API key for the given provider is set.

    Prints a helpful message and exits if not.
    """
    env_var = _API_KEY_ENV.get(provider)
    if not env_var:
        return

    if os.environ.get(env_var):
        return

    url = _API_KEY_URLS.get(provider, "")
    print(
        f"\n  API key not found.\n"
        f"\n"
        f"  {provider} requires the {env_var} environment variable.\n"
        f"\n"
        f"  Set it with:\n"
        f"    export {env_var}=\"your-api-key\"\n"
        f"\n"
        f"  Or add it to your shell profile (~/.bashrc, ~/.zshrc):\n"
        f"    echo 'export {env_var}=\"your-api-key\"' >> ~/.bashrc\n",
        file=sys.stderr,
    )
    if url:
        print(f"  Get your key at: {url}\n", file=sys.stderr)

    raise MissingAPIKeyError(f"{env_var} not set")


def create_model(provider: str, model: str | None = None, max_tokens: int = 16_384) -> Model:
    check_api_key(provider)
    model_name = model or DEFAULT_MODELS.get(provider, "gpt-5.2")
    if provider == "claude":
        return ClaudeModel(model_name, max_tokens=max_tokens)
    elif provider == "openai":
        return OpenAIModel(model_name, max_tokens=max_tokens)
    elif provider == "vertex_ai":
        return VertexModel(model_name, max_tokens=max_tokens)
    else:
        raise ValueError(f"unknown provider: {provider}")
