"""Shared prompt templates for all translation providers."""

import json as _json


_SYSTEM_TEMPLATE = (
    "You are a professional translator. Translate the given text from {source_lang} "
    "to {target_lang}. Return ONLY the translated text, nothing else. "
    "Do NOT add quotation marks, brackets, or any wrapper characters that are not in the original. "
    "Preserve any placeholders like {{name}}, {{{{count}}}}, %s, ${{value}} exactly as they appear. "
    "Preserve brand names. Match the tone and formality of the original.\n\n"
    "Project context: {project_context}"
)

_USER_TEMPLATE = 'Translate the following text:\n{source_text}\n\nString context: {string_context}'

_PLURAL_SYSTEM_TEMPLATE = (
    "You are a professional translator. You will be given two plural forms "
    "(one and other) in {source_lang}. Generate ALL plural forms needed in "
    "{target_lang} according to CLDR plural rules. Return ONLY a JSON object "
    "mapping plural categories to translated strings. Do not include explanation.\n\n"
    "CRITICAL: Placeholders like {count}, {name}, %s, ${value} are SOFTWARE VARIABLES "
    "that will be replaced by code at runtime. You MUST include them exactly as written "
    "in EVERY plural form, even for zero, one, and two categories where the language "
    "would not normally use a numeral. For example, for Arabic zero: use \"{count} ...\" "
    "not \"لا توجد ...\". For Arabic one: use \"{count} ...\" not \"واحدة ...\".\n\n"
    "Preserve brand names. Match the tone and formality of the original.\n\n"
    "CLDR plural categories are: zero, one, two, few, many, other.\n"
    "Only include categories that {target_lang} actually uses.\n\n"
    "Project context: {project_context}"
)

_PLURAL_USER_TEMPLATE = (
    'Source one form: "{one}"\n'
    'Source other form: "{other}"\n'
    'String context: {string_context}'
)


def _safe_render(template: str, **kwargs) -> str:
    """Render a template using safe string replacement (not str.format)."""
    result = template
    for key, value in kwargs.items():
        result = result.replace(f"{{{key}}}", str(value))
    return result


def build_messages(
    source_text: str,
    source_lang: str,
    target_lang: str,
    project_context: str,
    string_context: str | None,
) -> list[dict]:
    """Build system + user messages for chat-based providers (OpenAI, Claude API)."""
    system_msg = _SYSTEM_TEMPLATE.format(
        source_lang=source_lang,
        target_lang=target_lang,
        project_context=project_context,
    )
    user_msg = _USER_TEMPLATE.format(
        source_text=source_text,
        string_context=string_context or "none",
    )
    return [
        {"role": "system", "content": system_msg},
        {"role": "user", "content": user_msg},
    ]


def build_plural_messages(
    one: str,
    other: str,
    source_lang: str,
    target_lang: str,
    project_context: str,
    string_context: str | None,
) -> list[dict]:
    """Build system + user messages for plural chat-based providers."""
    system_msg = _safe_render(
        _PLURAL_SYSTEM_TEMPLATE,
        source_lang=source_lang,
        target_lang=target_lang,
        project_context=project_context,
    )
    user_msg = _safe_render(
        _PLURAL_USER_TEMPLATE,
        one=one,
        other=other,
        string_context=string_context or "none",
    )
    return [
        {"role": "system", "content": system_msg},
        {"role": "user", "content": user_msg},
    ]


def build_single_prompt(
    source_text: str,
    source_lang: str,
    target_lang: str,
    project_context: str,
    string_context: str | None,
) -> str:
    """Build a single combined prompt for non-chat providers (Claude Code)."""
    messages = build_messages(source_text, source_lang, target_lang, project_context, string_context)
    return messages[0]["content"] + "\n\n" + messages[1]["content"]


def build_plural_single_prompt(
    one: str,
    other: str,
    source_lang: str,
    target_lang: str,
    project_context: str,
    string_context: str | None,
) -> str:
    """Build a single combined plural prompt for non-chat providers."""
    messages = build_plural_messages(one, other, source_lang, target_lang, project_context, string_context)
    return messages[0]["content"] + "\n\n" + messages[1]["content"]
