"""
translate_service.py — French → English / Spanish for product names (brief sheet 3: "French input only, the
back-office translates by itself, the EN / ES fields stay editable").

A machine translation can get a commercial name wrong, so the result only FILLS the fields: the admin sees them and
can correct them before saving. If no service answers the product is still saved and shown in French: `translate`
returns None, never raises.

Provider: MyMemory (api.mymemory.translated.net), free and with no key to manage — plenty for a handful of product names
(about 5,000 characters a day per server address). Only the product text leaves the server: no pupil, family or order data.
"""
import logging
from typing import Optional

import httpx

from core import config

log = logging.getLogger("meeconic.translate")

TARGETS = ("en", "es")
_cache: dict[tuple[str, str], str] = {}


def _mymemory(texts: list[str], lang: str) -> list[str]:
    out = []
    for text in texts:
        r = httpx.get("https://api.mymemory.translated.net/get", timeout=config.TRANSLATE_TIMEOUT_SECS,
                      params={"q": text, "langpair": f"fr|{lang}"})
        r.raise_for_status()
        data = r.json()
        translated = data["responseData"]["translatedText"]
        # Over the daily quota MyMemory still answers 200 with a warning IN the translated text: never store that.
        if data.get("responseStatus") not in (200, "200") or "MYMEMORY WARNING" in translated.upper():
            raise ValueError(f"MyMemory: {data.get('responseDetails') or translated[:60]}")
        out.append(translated)
    return out


def translate(texts: list[str]) -> Optional[dict[str, list[str]]]:
    """{"en": [...], "es": [...]} in the order of `texts` (empty texts stay empty), or None if unavailable."""
    texts = [" ".join((t or "").split()) for t in texts]
    todo = sorted({t for t in texts if t})
    if not todo:
        return {lang: ["" for _ in texts] for lang in TARGETS}
    try:
        for lang in TARGETS:
            missing = [t for t in todo if (t, lang) not in _cache]
            if missing:
                for src, dst in zip(missing, _mymemory(missing, lang)):
                    _cache[(src, lang)] = " ".join(str(dst).split())
        return {lang: [_cache[(t, lang)] if t else "" for t in texts] for lang in TARGETS}
    except Exception as exc:
        log.warning("Translation unavailable (%s): products stay in French", type(exc).__name__)
        return None
