#!/usr/bin/env python3
"""
Sync missing WordPress i18n strings into all locale .po files.

- Extract msgids from PHP translation wrappers for text domain `accessibility-assistant`
- Add missing entries to each .po
- Fill blank msgstr values using:
  1) existing en_US translation (if available)
  2) optional machine translation (deep-translator)
  3) fallback to msgid
- Compile .mo files for each updated .po
"""

from __future__ import annotations

import argparse
import re
from pathlib import Path
from typing import Dict, List, Optional, Set

import polib

WRAPPER_RE = re.compile(
    r"""(?x)
    (?:
      __|_e|esc_html__|esc_html_e|esc_attr__|esc_attr_e
    )
    \(
      \s*(['"])(?P<msgid>(?:\\.|(?!\1).)*?)\1
      \s*,\s*
      (['"])accessibility-assistant\3
    \)
    """
)

DEFAULT_EXCLUDE = {
    "node_modules",
    ".git",
    ".cursor",
    "vendor",
}


def unescape_php_string(raw: str) -> str:
    return bytes(raw, "utf-8").decode("unicode_escape")


def normalize_msgid(text: str) -> str:
    normalized = re.sub(r"\s+", " ", text.strip().lower())
    normalized = re.sub(r"[^\w\s%]", "", normalized)
    return normalized


def extract_msgids_from_php(root: Path) -> Set[str]:
    msgids: Set[str] = set()
    for php_file in root.rglob("*.php"):
        if any(part in DEFAULT_EXCLUDE for part in php_file.parts):
            continue
        try:
            content = php_file.read_text(encoding="utf-8", errors="ignore")
        except OSError:
            continue
        for m in WRAPPER_RE.finditer(content):
            msgid = unescape_php_string(m.group("msgid")).strip()
            if msgid:
                msgids.add(msgid)
    return msgids


def locale_from_po_path(po_path: Path, languages_root: Path) -> str:
    rel = po_path.relative_to(languages_root)
    return rel.parts[0]


def locale_to_lang(locale: str) -> str:
    special = {
        "zh_TW": "zh-TW",
        "zh_CN": "zh-CN",
        "pt_BR": "pt",
        "pt_PT": "pt",
        "fil_PH": "tl",
    }
    if locale in special:
        return special[locale]
    return locale.split("_", 1)[0].lower()


def get_translator(enable_mt: bool):
    if not enable_mt:
        return None
    try:
        from deep_translator import GoogleTranslator  # type: ignore
    except Exception:
        return None
    return GoogleTranslator


def machine_translate(
    translator_cls,
    msgid: str,
    target_lang: str,
    cache: Dict[str, str],
) -> Optional[str]:
    if translator_cls is None or not target_lang:
        return None
    key = f"{target_lang}::{msgid}"
    if key in cache:
        return cache[key]
    try:
        translated = translator_cls(source="en", target=target_lang).translate(msgid)
        if translated and isinstance(translated, str):
            translated = translated.strip()
            cache[key] = translated
            return translated
    except Exception:
        return None
    return None


def machine_translate_batch(
    translator_cls,
    msgids: List[str],
    target_lang: str,
    cache: Dict[str, str],
) -> Dict[str, str]:
    results: Dict[str, str] = {}
    if translator_cls is None or not target_lang or not msgids:
        return results
    pending: List[str] = []
    for msgid in msgids:
        key = f"{target_lang}::{msgid}"
        if key in cache:
            results[msgid] = cache[key]
        else:
            pending.append(msgid)
    if not pending:
        return results
    try:
        translator = translator_cls(source="en", target=target_lang)
        translated_list = translator.translate_batch(pending)
        if translated_list and len(translated_list) == len(pending):
            for src, dst in zip(pending, translated_list):
                if isinstance(dst, str) and dst.strip():
                    val = dst.strip()
                    if val != src:
                        cache[f"{target_lang}::{src}"] = val
                        results[src] = val
                    else:
                        single = machine_translate(translator_cls, src, target_lang, cache)
                        if single and single != src:
                            results[src] = single
    except Exception:
        for msgid in pending:
            single = machine_translate(translator_cls, msgid, target_lang, cache)
            if single:
                results[msgid] = single
    return results


def sync_po_file(
    po_path: Path,
    required_msgids: Set[str],
    en_us_map: Dict[str, str],
    translator_cls,
    mt_cache: Dict[str, str],
    dry_run: bool,
    retranslate_identical: bool,
    do_not_translate: Set[str],
    family_map: Dict[str, Dict[str, str]],
) -> bool:
    try:
        po = polib.pofile(str(po_path))
    except Exception as exc:
        print(f"Skipped (invalid PO): {po_path} - {exc}")
        return False
    locale = po_path.parent.name
    lang = locale_to_lang(locale)
    changed = False

    existing = {entry.msgid: entry for entry in po if not entry.obsolete}
    normalized_translations: Dict[str, str] = {}
    family_key = locale.split("_", 1)[0].lower()
    for existing_entry in po:
        if existing_entry.obsolete:
            continue
        existing_msgstr = (existing_entry.msgstr or "").strip()
        if not existing_msgstr:
            continue
        if existing_msgstr == existing_entry.msgid:
            continue
        normalized_key = normalize_msgid(existing_entry.msgid)
        if normalized_key and normalized_key not in normalized_translations:
            normalized_translations[normalized_key] = existing_msgstr

    pending_for_batch: List[str] = []
    for msgid in sorted(required_msgids):
        entry = existing.get(msgid)
        current_msgstr = (entry.msgstr or "").strip() if entry else ""
        needs_value = False
        if entry is None:
            needs_value = True
        elif not current_msgstr:
            needs_value = True
        elif retranslate_identical and not (locale.startswith("en_") or locale == "en") and current_msgstr == msgid and msgid not in do_not_translate:
            needs_value = True
        if needs_value and not (locale.startswith("en_") or locale == "en"):
            pending_for_batch.append(msgid)

    batch_translations = machine_translate_batch(translator_cls, pending_for_batch, lang, mt_cache)

    for msgid in sorted(required_msgids):
        entry = existing.get(msgid)
        if entry is None:
            entry = polib.POEntry(msgid=msgid, msgstr="")
            po.append(entry)
            existing[msgid] = entry
            changed = True

        current_msgstr = entry.msgstr.strip()
        if current_msgstr:
            if not retranslate_identical or locale.startswith("en_") or locale == "en":
                continue
            if current_msgstr != msgid:
                continue
            if msgid in do_not_translate:
                continue

        if locale.startswith("en_") or locale == "en":
            new_msgstr = msgid
        else:
            translated = batch_translations.get(msgid) or machine_translate(translator_cls, msgid, lang, mt_cache)
            if translated:
                new_msgstr = translated
            elif normalize_msgid(msgid) in normalized_translations:
                new_msgstr = normalized_translations[normalize_msgid(msgid)]
            elif family_key in family_map and normalize_msgid(msgid) in family_map[family_key]:
                new_msgstr = family_map[family_key][normalize_msgid(msgid)]
            elif en_us_map.get(msgid):
                new_msgstr = en_us_map[msgid]
            else:
                new_msgstr = msgid

        if new_msgstr != entry.msgstr:
            entry.msgstr = new_msgstr
            changed = True

    if changed and not dry_run:
        po.save(str(po_path))
        po.save_as_mofile(str(po_path.with_suffix(".mo")))

    return changed


def build_en_us_map(po_files: List[Path]) -> Dict[str, str]:
    out: Dict[str, str] = {}
    en_candidates = [p for p in po_files if p.parent.name in {"en_US", "en_GB", "en"}]
    for p in en_candidates:
        try:
            po = polib.pofile(str(p))
        except Exception:
            continue
        for entry in po:
            if entry.obsolete:
                continue
            val = (entry.msgstr or "").strip()
            if val:
                out[entry.msgid] = val
    return out


def build_family_map(po_files: List[Path]) -> Dict[str, Dict[str, str]]:
    result: Dict[str, Dict[str, str]] = {}
    for p in po_files:
        locale = p.parent.name
        family = locale.split("_", 1)[0].lower()
        if family == "en":
            continue
        try:
            po = polib.pofile(str(p))
        except Exception:
            continue
        result.setdefault(family, {})
        for entry in po:
            if entry.obsolete:
                continue
            val = (entry.msgstr or "").strip()
            if not val or val == entry.msgid:
                continue
            key = normalize_msgid(entry.msgid)
            if key and key not in result[family]:
                result[family][key] = val
    return result


def main() -> int:
    parser = argparse.ArgumentParser(description="Sync translation msgids and compile .mo files.")
    parser.add_argument("--root", default=".", help="Plugin root path")
    parser.add_argument("--machine-translate", action="store_true", help="Enable Google machine translation for missing msgstr")
    parser.add_argument("--dry-run", action="store_true", help="Scan only, do not write files")
    parser.add_argument("--retranslate-identical", action="store_true", help="Retranslate entries where msgstr equals msgid for non-English locales")
    parser.add_argument("--admin-partials-only", action="store_true", help="Extract msgids only from admin/partials")
    parser.add_argument("--target-msgids-file", help="Optional text file (one msgid per line) to limit sync scope")
    parser.add_argument("--locales", help="Optional comma-separated locale folders to process (e.g. en_US,es_ES,fr_FR)")
    args = parser.parse_args()

    plugin_root = Path(args.root).resolve()
    admin_root = plugin_root / "admin"
    includes_root = plugin_root / "includes"
    public_root = plugin_root / "public"
    main_php = plugin_root / "accessibility-assistant.php"
    languages_root = plugin_root / "languages"

    required_msgids: Set[str] = set()
    if args.target_msgids_file:
        msgids_path = Path(args.target_msgids_file).resolve()
        if msgids_path.exists():
            for line in msgids_path.read_text(encoding="utf-8", errors="ignore").splitlines():
                value = line.strip()
                if value:
                    required_msgids.add(value)
    elif args.admin_partials_only:
        partials_root = admin_root / "partials"
        if partials_root.exists():
            required_msgids |= extract_msgids_from_php(partials_root)
    else:
        for target in [admin_root, includes_root, public_root]:
            if target.exists():
                required_msgids |= extract_msgids_from_php(target)
        if main_php.exists():
            required_msgids |= extract_msgids_from_php(plugin_root)

    po_files = sorted([p for p in languages_root.rglob("*.po") if ".dedup." not in p.name])
    if args.locales:
        allowed = {x.strip() for x in args.locales.split(",") if x.strip()}
        po_files = [p for p in po_files if p.parent.name in allowed]
    if not po_files:
        print("No .po files found.")
        return 1

    en_us_map = build_en_us_map(po_files)
    family_map = build_family_map(po_files)
    translator_cls = get_translator(args.machine_translate)
    mt_cache: Dict[str, str] = {}
    do_not_translate: Set[str] = {
        "Free",
        "Growth",
        "Scale",
        "Established",
        "Free Plan",
        "Growth Plan",
        "Scale Plan",
        "Established Plan",
    }

    changed_count = 0
    for po_path in po_files:
        changed = sync_po_file(
            po_path=po_path,
            required_msgids=required_msgids,
            en_us_map=en_us_map,
            translator_cls=translator_cls,
            mt_cache=mt_cache,
            dry_run=args.dry_run,
            retranslate_identical=args.retranslate_identical,
            do_not_translate=do_not_translate,
            family_map=family_map,
        )
        if changed:
            changed_count += 1
            print(f"Updated: {po_path.relative_to(plugin_root)}")

    print(f"Processed {len(po_files)} locale files. Updated: {changed_count}.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
