"""Shared initialization logic for sync/async SDKRouter clients."""

from __future__ import annotations

import logging
import os
from typing import Optional

from .._config import SDKConfig
from .._constants import (
    DEFAULT_API_URL,
    DEFAULT_AUDIO_URL,
    DEFAULT_LLM_URL,
    DEFAULT_MAX_RETRIES,
    DEFAULT_TIMEOUT,
    DEV_API_URL,
    DEV_AUDIO_URL,
    DEV_LLM_URL,
    DEV_TELEGRAM_URL,
    ENV_API_KEY,
    ENV_AUDIO_URL,
    ENV_OPENROUTER_KEY,
    ENV_TELEGRAM_URL,
    OPENROUTER_URL,
)

logger = logging.getLogger(__name__)


def resolve_init_params(
    *,
    api_key: Optional[str],
    llm_url: Optional[str],
    api_url: Optional[str],
    audio_url: Optional[str],
    dev: bool,
    use_self_hosted: bool,
    openrouter_api_key: Optional[str],
    provider: Optional[str],
    timeout: float,
    max_retries: int,
) -> tuple[str, str, str, str, SDKConfig]:
    """Resolve all constructor params → (resolved_key, openai_base_url, resolved_api_url, resolved_audio_url, sdk_config).

    Shared between SDKRouter (sync) and AsyncSDKRouter (async).
    """
    # Dev mode
    if dev:
        llm_url = llm_url or DEV_LLM_URL
        api_url = api_url or DEV_API_URL
        audio_url = audio_url or DEV_AUDIO_URL
        os.environ.setdefault(ENV_TELEGRAM_URL, DEV_TELEGRAM_URL)

    # Resolve API key
    resolved_key = (
        api_key
        or os.getenv(ENV_API_KEY)
        or openrouter_api_key
        or os.getenv(ENV_OPENROUTER_KEY)
    )
    if not resolved_key:
        raise ValueError(
            "API key required. Set SDKROUTER_API_KEY environment variable "
            "or pass api_key= parameter."
        )

    # Resolve URLs
    resolved_audio_url = audio_url or os.getenv(ENV_AUDIO_URL) or DEFAULT_AUDIO_URL
    if use_self_hosted:
        resolved_llm_url = llm_url or os.getenv("SDKROUTER_LLM_URL") or DEFAULT_LLM_URL
        resolved_api_url = api_url or os.getenv("SDKROUTER_API_URL") or DEFAULT_API_URL
    else:
        resolved_llm_url = llm_url or OPENROUTER_URL
        resolved_api_url = api_url or DEFAULT_API_URL

    # OpenAI base URL (needs /v1)
    openai_base_url = resolved_llm_url.rstrip("/")
    if not openai_base_url.endswith("/v1"):
        openai_base_url += "/v1"

    logger.debug(
        "SDKRouter: llm=%s api=%s audio=%s self_hosted=%s",
        resolved_llm_url, resolved_api_url, resolved_audio_url, use_self_hosted,
    )

    config = SDKConfig(
        api_key=resolved_key,
        llm_url=resolved_llm_url,
        api_url=resolved_api_url,
        audio_url=resolved_audio_url,
        use_self_hosted=use_self_hosted,
        timeout=timeout,
        max_retries=max_retries,
        provider=provider,
    )

    return resolved_key, openai_base_url, resolved_api_url, resolved_audio_url, config
