#!/usr/bin/env python3
#
# CreateTranslations.py                                                   v0.4.0
# from corz.org + (mostly) Gemini
#
# Used to create BASIC language translation files for checksum.
# These provided a starting point for a decent AI to work with.
#
# This automatically creates translation files from a master English text list.
# The master list is named en.ini and is simply a list of English strings.
#
# You do not need to create a [section] or put = after the strings, which would
# quickly become choreful; just make a list of words and phrases and save it as
# "en.ini", or whatever name you set in your prefs (below).
#
# Run this script in your working directory and it will create either one large
# languages.ini file or individual xx.ini language files inside /languages.
# You can of course configure these things, below.
#
# Words inside {{curly braces}} and [square braces] are protected, and if a 
# string contains them, this script splits the string arounds these words, sends
# the fragments to the translator, then reconstructs the fragments to produce 
# the final result. You can also set specific protected words which are *always* 
# protected. [square] braces are used to transform [variables] inside checksum.
#
# We use the Google translation API for the translations. For all 72+ languages
# and a couple hundred strings it will take an hour or so to build the initial
# translation file(s). The longer the string, the longer it takes to translate;
# a background task.
#
# If you add new strings, simply run the script again and it will add the new
# translations to /all/ your chosen languages in one pass, skipping existing
# translation lines so it's nice and fast.
#
# Missing translations [bg]: 48
# Translating [bg] FILE=ФАЙЛ
# Translating [bg] checksum will now shutdown your computer=checksum сега ще изключи вашия компютър
# Translating [bg] Check your {{upgrade_all_hashes}} ini setting=Проверете вашата {{upgrade_all_hashes}} ini настройка
# Translating [bg] My checksum task=Моята checksum задача
# Translating [bg] Invalid date selection!\n\nchecksum will now exit!=Невалиден избор на дата!\n\nchecksum сега ще излезе!
# Translating [bg] Create Task?=Създаване на задача?
# Translating [bg] The following task will be created=Ще бъде създадена следната задача
# Translating [bg] On Which Days?=В кои дни?
# Translating [bg] Run the task on which days?=Изпълнение на задачата в кои дни?
# Translating [bg] mon=пн
# Translating [bg] tue=вт
# Translating [bg] wed=ср
# Translating [bg] thu=чт
# Translating [bg] fri=пт
# Translating [bg] sat=сед
# Translating [bg] sun=слънце
#
# etc..
#
# There is a companion script named LanguageFilesHandler.py, which is able to
# remove English=OtherLanguage key=val pairs from ALL your languages at-once,
# and is very handy for updates and correcting mistakes, like so..
#
#   python /path/to/LanguageFilesHandler.py remove "my stupidly worded line"
#
# Then grab all the new translations using your updated en.ini and this script.
#

import json
import re
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path


# Prefs

# The language we are translating FROM.
SOURCE_LANGUAGE = "en"

# A list of words and phrases in the source language.
SOURCE_FILE = "en.ini"

# Your Google Cloud Translation API key. Leave this blank to use the public
# interface, but watch for those 429 errors! You can get a FREE API key with a
# MASSIVE free allowance here: https://console.cloud.google.com/
# The V2 access has better translations for technical terms.
GOOGLE_API_KEY = "<YOUR-KEY-HERE>"

# Languages we will create language files for.
TARGET_LANGUAGES = [
    "af", "am", "ar", "az", "be", "bg", "bn", "bs", "ca", "cs", "cy", "da",
    "de", "el", "es", "et", "eu", "fa", "fi", "fr", "ga", "gd", "gl", "gu",
    "he", "hi", "hr", "hu", "hy", "id", "is", "it", "ja", "ka", "kk", "km",
    "kn", "ko", "ky", "lo", "lt", "lv", "mk", "ml", "mn", "mr", "ms", "ne",
    "nl", "no", "pa", "pl", "ps", "pt", "ro", "ru", "si", "sk", "sl", "sq",
    "sr", "sv", "sw", "ta", "te", "th", "tr", "uk", "ur", "uz", "vi", "zh"
]

# Individual language.ini files will be placed in this directory.
OUTPUT_DIR = Path("languages")

# If using a single file, its name goes here..
MASTER_INI_PATH = Path("languages.ini")

# These terms will NEVER be translated..
PROTECTED_TERMS = ["checksum.ini", "checksum"]

# Seconds to wait after each translation API request. Set to 0 for no delay.
REQUEST_DELAY_SECONDS = 3.0

# checksum uses separate language files, for speed / to avoid memory overhead.
# Set to false to create a HUGE languages.ini file, one language per [section].
SEPARATE_FILES = True

# End prefs


print(f"\nTranslating from: {SOURCE_LANGUAGE}")


def find_ini_separator(line: str) -> int:
    """Returns the first '=' outside protected {{...}} and [...] tokens."""
    curly_depth = 0
    square_depth = 0
    index = 0

    while index < len(line):
        if line.startswith("{{", index):
            curly_depth += 1
            index += 2
            continue
        if line.startswith("}}", index) and curly_depth:
            curly_depth -= 1
            index += 2
            continue

        character = line[index]
        if character == "[" and not curly_depth:
            square_depth += 1
        elif character == "]" and square_depth and not curly_depth:
            square_depth -= 1
        elif character == "=" and not curly_depth and not square_depth:
            return index

        index += 1

    return -1


def contains_translatable_text(text: str) -> bool:
    """Returns whether anything except protected content and syntax remains."""
    remaining = re.sub(r"\{\{.+?\}\}|\[[^\]]+\]", " ", text)
    for term in sorted(PROTECTED_TERMS, key=len, reverse=True):
        remaining = re.sub(
            rf"\b{re.escape(term)}\b",
            " ",
            remaining,
            flags=re.IGNORECASE,
        )
    return bool(re.search(r"[A-Za-z]", remaining))


def translate_segment(text: str, target_lang: str) -> str:

    if not text.strip():
        return text

    if not contains_translatable_text(text):
        return text

    # 1. Extract and preserve {{identifiers}} and [identifiers] verbatim
    dyn_terms = []

    def _mask_dyn(m):
        idx = len(dyn_terms)
        dyn_terms.append(m.group(0))
        return f" ___DYN{idx}___ "

    masked = re.sub(r"(\{\{.+?\}\}|\[[a-zA-Z0-9_]+\])", _mask_dyn, text)

    # 2. Mask static protected terms
    term_map = {}
    for i, term in enumerate(sorted(PROTECTED_TERMS, key=len, reverse=True)):
        pattern = re.compile(rf"\b{re.escape(term)}\b", re.IGNORECASE)
        if pattern.search(masked):
            term_map[i] = term
            masked = pattern.sub(f" ___PRT{i}___ ", masked)

    
    #  Using FREE interface..
    if GOOGLE_API_KEY == "":

        # 3. API Translation (FREE Access
        params = urllib.parse.urlencode({
            "client": "gtx",
            "sl": SOURCE_LANGUAGE,
            "tl": target_lang,
            "dt": "t",
            "q": masked,
        })
        url = f"https://translate.googleapis.com/translate_a/single?{params}"
        req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})

        # Let urllib exceptions raise so network issues can be handled caller-side
        with urllib.request.urlopen(req, timeout=10) as resp:
            res = json.loads(resp.read().decode("utf-8"))
            masked = "".join([part[0] for part in res[0] if part[0]])

    else:
        
        # 3. API Translation (Cloud Translation API v2)
        payload = json.dumps({
            "q": masked,
            "source": SOURCE_LANGUAGE,
            "target": target_lang,
            "format": "text",
        }).encode("utf-8")
        url = f"https://translation.googleapis.com/language/translate/v2?key={GOOGLE_API_KEY}"
        req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"})

        with urllib.request.urlopen(req, timeout=10) as resp:
            res = json.loads(resp.read().decode("utf-8"))
            masked = res["data"]["translations"][0]["translatedText"]
        
        
    if REQUEST_DELAY_SECONDS > 0:
        time.sleep(REQUEST_DELAY_SECONDS)

    # 4. Restore verbatim {{identifiers}}
    for i, original_tag in enumerate(dyn_terms):
        pattern = re.compile(rf"\s*_*[\s_]*DYN{i}[\s_]*_*\s*", re.IGNORECASE)
        masked = pattern.sub(f" {original_tag} ", masked)

    # 5. Restore static protected terms
    for i, original_term in term_map.items():
        pattern = re.compile(rf"\s*_*[\s_]*PRT{i}[\s_]*_*\s*", re.IGNORECASE)
        masked = pattern.sub(f" {original_term} ", masked)

    # Normalize whitespace around punctuation and tokens
    masked = re.sub(r"\s+([.,!?;:])", r"\1", masked)
    return re.sub(r"[ \t]+", " ", masked).strip()


def translate_text(text: str, target_lang: str) -> str:
    if not text:
        return text

    # Split on literal \n to prevent placeholder corruption by translation engine
    lines = text.split(r"\n")
    translated_lines = [translate_segment(line, target_lang) for line in lines]
    return r"\n".join(translated_lines)


def read_plain_strings(path: Path) -> list[tuple[str, str]]:
    """Reads authoritative source strings without interpreting their content."""
    raw = path.read_bytes()
    content = ""
    for enc in ("utf-8-sig", "utf-16", "utf-8", "cp1252", "latin-1"):
        try:
            content = raw.decode(enc)
            break
        except UnicodeDecodeError:
            continue

    items = []
    seen = set()
    for line in content.splitlines():
        line_str = line.strip()

        # Ignore comments or empty lines
        if not line_str or line_str.startswith(("#", ";")):
            continue

        key = line_str
        text = line_str

        if key not in seen:
            seen.add(key)
            items.append((key, text))

    return items


def read_ini_dict(path: Path) -> dict[str, dict[str, str]]:
    """Reads an INI file into a {section: {key: value}} dictionary safely."""
    if not path.exists():
        return {}
    raw = path.read_bytes()
    content = ""
    for enc in ("utf-16", "utf-8-sig", "utf-8", "cp1252", "latin-1"):
        try:
            content = raw.decode(enc)
            break
        except UnicodeDecodeError:
            continue

    data = {}
    current_section = None

    for line in content.splitlines():
        line_str = line.strip()
        if not line_str or line_str.startswith(("#", ";")):
            continue

        # Valid section header must not contain '='
        if line_str.startswith("[") and line_str.endswith("]") and "=" not in line_str:
            current_section = line_str[1:-1].strip()
            if current_section not in data:
                data[current_section] = {}
            continue

        separator = find_ini_separator(line_str)
        if separator >= 0 and current_section is not None:
            key = line_str[:separator]
            val = line_str[separator + 1:]
            data[current_section][key.strip()] = val.strip()

    return data


def save_ini_dict(data: dict[str, dict[str, str]], path: Path) -> None:
    """Writes a {section: {key: value}} dictionary to file in UTF-16 encoding."""
    path.parent.mkdir(parents=True, exist_ok=True)
    lines = []
    for section, keys in data.items():
        lines.append(f"[{section}]")
        for k, v in keys.items():
            lines.append(f"{k}={v}")
        lines.append("")

    content = "\n".join(lines)
    path.write_bytes(content.encode("utf-16"))


def main():

    args = sys.argv[1:]
    if len(args) > 2:
        print(f"Usage: {Path(sys.argv[0]).name} <source-file|-> <target-directory>")
        sys.exit(1)

    source_arg = SOURCE_FILE if not args or args[0] == "-" else args[0]
    target_arg = args[1] if len(args) == 2 else OUTPUT_DIR
    source_path = Path(source_arg).expanduser().resolve()
    output_dir = Path(target_arg).expanduser().resolve()
    master_ini_path = output_dir / MASTER_INI_PATH.name

    print(f"Reading Master language file: {source_path.name}")

    if not source_path.exists():
        print(f"ERROR: File not found: {source_path}")
        sys.exit(1)

    split_mode = SEPARATE_FILES

    english_items = read_plain_strings(source_path)
    src_sec = SOURCE_LANGUAGE

    if split_mode:

        print("Split Files Mode. Files in: " + output_dir.name + "\\")
        output_dir.mkdir(parents=True, exist_ok=True)

        # Write English source file (you can customize the source language, too!)
        en_path = output_dir / f"{src_sec}.ini"
        en_data = read_ini_dict(en_path)

        if src_sec not in en_data:
            en_data[src_sec] = {}
        english_changed = not en_path.exists()
        for k, txt in english_items:
            if not en_data[src_sec].get(k, "").strip():
                en_data[src_sec][k] = txt
                english_changed = True
        if english_changed:
            save_ini_dict(en_data, en_path)

        # Process target languages
        for lang in TARGET_LANGUAGES:

            lang_path = output_dir / f"{lang}.ini"
            lang_data = read_ini_dict(lang_path)

            if lang not in lang_data:
                lang_data[lang] = {}

            missing_items = [
                (k, txt) for k, txt in english_items
                if not lang_data[lang].get(k, "").strip()
            ]
            print(f"Missing translations [{lang}]: {len(missing_items)}")

            for k, txt in missing_items:
                print(f"Translating [{lang}] {k}", end="", flush=True)
                try:
                    translated_val = translate_text(txt, target_lang=lang)
                except Exception as err:
                    print()
                    print(f"Network / Translation error on [{lang}]: {err}")
                    print("Aborting...")
                    sys.exit(1)

                print(f"={translated_val}")
                lang_data[lang][k] = translated_val
                save_ini_dict(lang_data, lang_path)

    else:

        output_dir.mkdir(parents=True, exist_ok=True)
        out_data = read_ini_dict(master_ini_path)

        if src_sec not in out_data:
            out_data[src_sec] = {}
        for k, txt in english_items:
            out_data[src_sec][k] = txt

        for lang in TARGET_LANGUAGES:
            if lang not in out_data:
                out_data[lang] = {}

            missing_items = [
                (k, txt) for k, txt in english_items
                if not out_data[lang].get(k, "").strip()
            ]
            print(f"Missing translations [{lang}]: {len(missing_items)}")

            for k, txt in missing_items:
                print(f"Translating [{lang}] {k}", end="", flush=True)
                try:
                    translated_val = translate_text(txt, target_lang=lang)
                except Exception as err:
                    print()
                    print(f"Network / Translation error on [{lang}]: {err}")
                    print("Aborting...")
                    sys.exit(1)

                print(f"={translated_val}")
                out_data[lang][k] = translated_val
                save_ini_dict(out_data, master_ini_path)

        save_ini_dict(out_data, master_ini_path)

    print("All languages are up-to-date.")


# Ctrl+C deliberately uses Python's native KeyboardInterrupt handling.
if __name__ == "__main__":
    raise SystemExit(main())
