"""Translation backend router -- delegates to the configured provider."""

import os

from transduck.providers import get_provider
from transduck.providers.prompts import build_messages, build_plural_messages


def _check_api_key(config):
    """Check that the required API key/token is set before making API calls."""
    if config.provider == "claude_code":
        token = os.environ.get(config.token_env)
        if not token:
            raise RuntimeError(
                f"Missing API token: {config.token_env} environment variable is not set.\n"
                f"Run: export {config.token_env}=your-token-here"
            )
        return
    api_key = os.environ.get(config.api_key_env)
    if not api_key:
        raise RuntimeError(
            f"Missing API key: {config.api_key_env} environment variable is not set.\n"
            f"Run: export {config.api_key_env}=your-key-here\n"
            f"Or add it to your .env file."
        )


def translate(source_text, source_lang, target_lang, project_context, string_context, config):
    """Translate a single string using the configured provider."""
    _check_api_key(config)
    provider = get_provider(config)
    return provider.translate(source_text, source_lang, target_lang, project_context, string_context, config)


def translate_plural(one, other, source_lang, target_lang, project_context, string_context, config):
    """Translate plural forms using the configured provider."""
    _check_api_key(config)
    provider = get_provider(config)
    return provider.translate_plural(one, other, source_lang, target_lang, project_context, string_context, config)


def detect_language(text, config):
    """Detect the language of a text string. Returns an uppercase ISO 639-1 code."""
    _check_api_key(config)
    provider = get_provider(config)
    return provider.detect_language(text, config)


def supports_batch(config):
    """Check if the configured provider supports batch translation."""
    provider = get_provider(config)
    return getattr(provider, 'supports_batch', False)


def translate_batch(strings, source_lang, target_lang, project_context, config):
    """Translate multiple strings in one call. Only supported by some providers."""
    _check_api_key(config)
    provider = get_provider(config)
    return provider.translate_batch(strings, source_lang, target_lang, project_context, config)


def translate_plural_batch(plurals, source_lang, target_lang, project_context, config):
    """Translate multiple plural strings in one call. Only supported by some providers."""
    _check_api_key(config)
    provider = get_provider(config)
    return provider.translate_plural_batch(plurals, source_lang, target_lang, project_context, config)
