#!/usr/bin/env python3

# This applies a batch of revised translations to an existing language file. 
# It only replaces values for keys that already exist. It's useful when you 
# have a list of corrections to apply and want to keep the language file's
# layout and comments, like so:

# 1. In a working folder, copy the language file to old.ini (or whatever; see prefs).
# 2. Put the revised key = value lines in updated.ini in the same folder. Save both files as UTF-16 LE with BOM.
# 3. From that folder, run: python "C:\PATH\TO\\UpdateTranslationFile.py"

# The result is written to old.ini.

# NOTE: If you want to add brand-new translation keys, this script won't do it.
# It simply reports those keys to the console.

import re
from pathlib import Path

ROOT = Path.cwd()
OLD_INI = ROOT / "old.ini"
UPDATES_FILE = ROOT / "updated.ini"


def patch_ini(old_path: Path, update_path: Path) -> None:
    kv_re = re.compile(r"^\s*([^=:#;\s][^=:]*?)\s*([:=])\s*(.*)$")

    # Read update pairs (UTF-16 LE + BOM)
    updates = {}
    for line in update_path.read_text(encoding="utf-16").splitlines():
        line_stripped = line.strip()
        if line_stripped and not line_stripped.startswith((";", "#")):
            match = kv_re.match(line)
            if match:
                updates[match.group(1).strip()] = match.group(3).strip()

    matched_keys = set()
    new_lines = []

    # Process source file preserving whitespace and comments
    for line in old_path.read_text(encoding="utf-16").splitlines(keepends=True):
        line_stripped = line.strip()

        if line_stripped.startswith((";", "#")):
            new_lines.append(line)
            continue

        match = kv_re.match(line)
        if match:
            key = match.group(1).strip()
            delim = match.group(2)
            if key in updates:
                matched_keys.add(key)
                indent = line[: len(line) - len(line.lstrip())]
                ending = (
                    "\r\n"
                    if line.endswith("\r\n")
                    else ("\n" if line.endswith("\n") else "")
                )
                new_lines.append(f"{indent}{key} {delim} {updates[key]}{ending}")
                continue

        new_lines.append(line)

    # Overwrite in place (UTF-16 LE + BOM)
    old_path.write_text("".join(new_lines), encoding="utf-16")

    # Report unmapped keys
    unmatched = [k for k in updates if k not in matched_keys]
    if unmatched:
        print(f"[{len(unmatched)}] Key(s) in '{update_path.name}' were NOT found in '{old_path.name}':")
        for key in unmatched:
            print(f"  - {key}")
    else:
        print(f"All {len(updates)} key(s) from '{update_path.name}' were matched and updated.")


if __name__ == "__main__":
    patch_ini(OLD_INI, UPDATES_FILE)
