"""Claude API translation provider."""

import json
import os

from transduck.providers.prompts import build_messages, build_plural_messages


def _get_client(config):
    try:
        import anthropic
    except ImportError:
        raise ImportError("Install the required package: pip install transduck[claude]")
    api_key = os.environ.get(config.api_key_env)
    if not api_key:
        raise RuntimeError(f"Set {config.api_key_env} environment variable")
    return anthropic.Anthropic(api_key=api_key)


def translate(source_text, source_lang, target_lang, project_context, string_context, config):
    """Translate a single string using Claude API."""
    client = _get_client(config)
    messages = build_messages(source_text, source_lang, target_lang, project_context, string_context)
    response = client.messages.create(
        model=config.backend_model,
        max_tokens=1024,
        temperature=0.3,
        system=messages[0]["content"],
        messages=[{"role": "user", "content": messages[1]["content"]}],
    )
    return response.content[0].text.strip()


def detect_language(text, config):
    """Detect the language of a text string. Returns an uppercase ISO 639-1 code."""
    client = _get_client(config)
    response = client.messages.create(
        model=config.backend_model,
        max_tokens=16,
        temperature=0.0,
        system="What language is this text written in? Return only the uppercase ISO 639-1 code.",
        messages=[{"role": "user", "content": text}],
    )
    return response.content[0].text.strip().upper()


def translate_plural(one, other, source_lang, target_lang, project_context, string_context, config):
    """Translate plural forms using Claude API. Returns {category: translation}."""
    client = _get_client(config)
    messages = build_plural_messages(one, other, source_lang, target_lang, project_context, string_context)
    response = client.messages.create(
        model=config.backend_model,
        max_tokens=2048,
        temperature=0.3,
        system=messages[0]["content"],
        messages=[{"role": "user", "content": messages[1]["content"]}],
    )
    raw = response.content[0].text.strip()
    return json.loads(raw)
