#!/usr/bin/env python3
"""Fill empty msgstr in es_ES / fr_FR PO files using deep-translator (Google), batched."""

from __future__ import annotations

import sys
import time
from pathlib import Path

import polib
from deep_translator import GoogleTranslator

ROOT = Path(__file__).resolve().parents[1]
DOMAIN = "etchenet-reviews-for-google-business"
BATCH = 20


def translate_batch_safe(tr: GoogleTranslator, texts: list[str]) -> list[str]:
    if not texts:
        return []
    try:
        out = tr.translate_batch(texts)
        if len(out) != len(texts):
            raise ValueError("length mismatch")
        time.sleep(0.35)
        return out
    except Exception:
        out = []
        for t in texts:
            out.append(tr.translate(t))
            time.sleep(0.2)
        return out


def fill_locale(locale: str, target: str) -> None:
    path = ROOT / "languages" / f"{DOMAIN}-{locale}.po"
    po = polib.pofile(str(path))
    tr = GoogleTranslator(source="en", target=target)

    singles: list[tuple[polib.POEntry, str]] = []
    plural_bits: list[tuple[polib.POEntry, str, int]] = []

    for e in po:
        if not e.msgid:
            continue
        if e.msgid_plural:
            if not (e.msgstr_plural.get(0) or "").strip():
                plural_bits.append((e, e.msgid, 0))
            if not (e.msgstr_plural.get(1) or "").strip():
                plural_bits.append((e, e.msgid_plural, 1))
        else:
            if not (e.msgstr or "").strip():
                singles.append((e, e.msgid))

    for i in range(0, len(singles), BATCH):
        chunk = singles[i : i + BATCH]
        texts = [t for _, t in chunk]
        done = translate_batch_safe(tr, texts)
        for (ent, _), trs in zip(chunk, done):
            ent.msgstr = trs

    for i in range(0, len(plural_bits), BATCH):
        chunk = plural_bits[i : i + BATCH]
        texts = [t for _, t, _ in chunk]
        done = translate_batch_safe(tr, texts)
        for (ent, _, idx), trs in zip(chunk, done):
            ent.msgstr_plural[idx] = trs

    po.metadata["Last-Translator"] = "Etchenet (auto, deep-translator batch)"
    po.save(str(path))
    print(f"{locale}: filled {len(singles)} singular + {len(plural_bits)} plural bits -> {path}")


def main() -> None:
    if len(sys.argv) > 1:
        loc = sys.argv[1]
        tgt = "es" if loc.startswith("es") else "fr"
        fill_locale(loc, tgt)
        return
    fill_locale("es_ES", "es")
    fill_locale("fr_FR", "fr")


if __name__ == "__main__":
    main()
