#!/usr/bin/env python3
"""Dump untranslated (or fuzzy) messages of a catalog as JSON, for translation.

    venv/bin/python scripts/po-export.py it --limit 150 > chunk.json

Output is a JSON list of objects:
    {"i": <index>, "id": "<msgid>"}                      # singular
    {"i": <index>, "id": ["<sing>", "<plur>"], "n": 2}   # plural (n msgstr slots)

`i` is the position in the catalog and is what po-merge.py matches on, so the
msgid never has to survive a round-trip through the model.
"""
import json
import sys
from babel.messages.pofile import read_po

lang = sys.argv[1]
limit = None
if "--limit" in sys.argv:
    limit = int(sys.argv[sys.argv.index("--limit") + 1])
offset = 0
if "--offset" in sys.argv:
    offset = int(sys.argv[sys.argv.index("--offset") + 1])

path = f"supporthub/app/translations/{lang}/LC_MESSAGES/messages.po"
with open(path, encoding="utf-8") as fh:
    catalog = read_po(fh)

out = []
for i, msg in enumerate(catalog):
    if not msg.id:
        continue
    done = all(msg.string) if isinstance(msg.id, (list, tuple)) else bool(msg.string)
    if done and "fuzzy" not in msg.flags:
        continue
    if isinstance(msg.id, (list, tuple)):
        out.append({"i": i, "id": list(msg.id), "n": len(msg.string) or 2})
    else:
        out.append({"i": i, "id": msg.id})

out = out[offset:]
if limit:
    out = out[:limit]
json.dump(out, sys.stdout, ensure_ascii=False, indent=1)
