"""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 detect_language(text, config):
    """Detect the language of a text string. Returns an uppercase ISO 639-1 code."""
    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 = [
        {"role": "system", "content": "What language is this text written in? Return only the uppercase ISO 639-1 code."},
        {"role": "user", "content": text},
    ]
    response = client.chat.completions.create(model=config.backend_model, messages=messages, temperature=0.0)
    return response.choices[0].message.content.strip().upper()


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,
        response_format={"type": "json_object"},
    )
    raw = (response.choices[0].message.content or "").strip()
    if raw.startswith("```"):
        raw = raw.split("\n", 1)[-1].rsplit("```", 1)[0].strip()
    if not raw:
        raise ValueError(f"Empty response from OpenAI for plural translation: '{one}' / '{other}' → {target_lang}")
    return json.loads(raw)
