"""OpenAI translation provider."""

import json
import os

import openai

from transduck.providers.prompts import build_messages, build_plural_messages


def translate(source_text, source_lang, target_lang, project_context, string_context, config):
    """Translate a single string using OpenAI."""
    api_key = os.environ.get(config.api_key_env)
    client = openai.OpenAI(api_key=api_key, timeout=config.backend_timeout, max_retries=config.backend_max_retries)
    messages = build_messages(source_text, source_lang, target_lang, project_context, string_context)
    response = client.chat.completions.create(model=config.backend_model, messages=messages, temperature=0.3)
    return response.choices[0].message.content.strip()


def translate_plural(one, other, source_lang, target_lang, project_context, string_context, config):
    """Translate plural forms using OpenAI. Returns {category: translation}."""
    api_key = os.environ.get(config.api_key_env)
    client = openai.OpenAI(api_key=api_key, timeout=config.backend_timeout, max_retries=config.backend_max_retries)
    messages = build_plural_messages(one, other, source_lang, target_lang, project_context, string_context)
    response = client.chat.completions.create(model=config.backend_model, messages=messages, temperature=0.3)
    raw = response.choices[0].message.content.strip()
    return json.loads(raw)
