#!/usr/bin/env python3
"""Merge a new POT into a locale PO: keep translations where msgid matches; else empty msgstr."""

import sys
from datetime import datetime, timezone
from pathlib import Path

import polib

ROOT = Path(__file__).resolve().parents[1]
POT = ROOT / "languages" / "etchenet-reviews-for-google-business.pot"


def merge(locale: str, language_team: str, last_translator: str = "") -> None:
    pot = polib.pofile(str(POT))
    old_path = ROOT / "languages" / f"etchenet-reviews-for-google-business-{locale}.po"
    old = polib.pofile(str(old_path)) if old_path.exists() else polib.POFile()

    new_po = polib.POFile()
    new_po.metadata = pot.metadata.copy()
    new_po.metadata["Project-Id-Version"] = "Etchenet Reviews for Google Business"
    new_po.metadata["POT-Creation-Date"] = pot.metadata.get("POT-Creation-Date", "")
    new_po.metadata["PO-Revision-Date"] = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M+0000")
    new_po.metadata["Last-Translator"] = last_translator
    new_po.metadata["Language-Team"] = language_team
    new_po.metadata["Language"] = locale
    if locale.startswith("es"):
        new_po.metadata["Plural-Forms"] = "nplurals=2; plural=(n != 1);"
    elif locale.startswith("fr"):
        new_po.metadata["Plural-Forms"] = "nplurals=2; plural=(n > 1);"
    else:
        new_po.metadata["Plural-Forms"] = "nplurals=2; plural=(n != 1);"
    new_po.metadata["MIME-Version"] = "1.0"
    new_po.metadata["Content-Type"] = "text/plain; charset=UTF-8"
    new_po.metadata["Content-Transfer-Encoding"] = "8bit"
    new_po.metadata["X-Domain"] = "etchenet-reviews-for-google-business"

    for e in pot:
        prev = old.find(e.msgid, msgctxt=e.msgctxt)
        ne = polib.POEntry(
            msgid=e.msgid,
            msgctxt=e.msgctxt,
            occurrences=e.occurrences,
            comment=e.comment,
            tcomment=e.tcomment,
        )
        if e.msgid_plural:
            ne.msgid_plural = e.msgid_plural
            if prev and prev.msgstr_plural:
                ne.msgstr_plural = prev.msgstr_plural.copy()
            else:
                ne.msgstr_plural = {0: "", 1: ""}
        else:
            if prev and prev.msgstr and not prev.obsolete:
                ne.msgstr = prev.msgstr
            else:
                ne.msgstr = ""
        new_po.append(ne)

    out = ROOT / "languages" / f"etchenet-reviews-for-google-business-{locale}.po"
    new_po.save(str(out))
    print(f"Wrote {out} ({len(new_po)} entries)")


def main() -> None:
    if not POT.exists():
        print("Missing POT; run: php tools/build-pot.php", file=sys.stderr)
        sys.exit(1)
    merge("es_ES", "Spanish (Spain)")
    merge("fr_FR", "French (France)")
    merge("en_US", "English (United States)")


if __name__ == "__main__":
    main()
