#!/usr/bin/env python3

# LanguageFilesHandler.py
# from corz.org + Gemini

# Simple script to manipulate ALL language files at-once.
# Used for working with checksum language translations.
#
# Usage:
#
#   To remove a line (key=val pair) from ALL language files..
#
#     pyr LanguageFilesHandler remove "foobar test"
#
#   on a regular system..
#
#     python LanguageFilesHandler.py remove "foobar test"
#

import argparse
import sys
from pathlib import Path

# This script expects to find this directory in its working directory, and 
# inside there, all your language files; af.ini, am.ini, etc..
LANGUAGES_DIR = Path("languages")

# If your languages are in ONE BIG FILE, it is named this..
ONE_BIG_LANGUAGES_INI = Path("languages.ini")


def get_target_files(dir_path: Path = LANGUAGES_DIR, master_path: Path = ONE_BIG_LANGUAGES_INI) -> list[Path]:
    files = []
    if dir_path.exists() and dir_path.is_dir():
        files.extend(sorted(dir_path.glob("*.ini")))
    if master_path.exists() and master_path.is_file():
        files.append(master_path)
    return files


def read_file_text(path: Path) -> str:
    raw = path.read_bytes()

    # Check for UTF-16 LE BOM
    if not (raw.startswith(b"\xff\xfe")):
        raise ValueError(
            f"File '{path}' is not UTF-16 encoded. Please convert the file to UTF-16 LE + BOM."
        )

    try:
        return raw.decode("utf-16")
    except UnicodeError as err:
        raise ValueError(
            f"File '{path}' failed UTF-16 decoding ({err}). Please fix the file encoding."
        )


def cmd_remove(key_to_remove: str):
    target_key = key_to_remove.strip()
    files = get_target_files()

    if not files:
        print("No language INI files found.")
        return

    total_removed = 0
    modified_files = []

    for file_path in files:
        content = read_file_text(file_path)
        lines = content.splitlines()
        new_lines = []
        file_modified = False

        for line in lines:
            stripped = line.strip()
            if "=" in stripped and not stripped.startswith(("#", ";")):
                k, _ = stripped.split("=", 1)
                if k.strip() == target_key:
                    file_modified = True
                    total_removed += 1
                    continue

            new_lines.append(line)

        if file_modified:
            output_content = "\n".join(new_lines) + "\n"
            file_path.write_bytes(output_content.encode("utf-16"))
            modified_files.append(file_path)
            print(f"Removed from: {file_path}")

    if total_removed == 0:
        print(f"Key '{target_key}' not found in any files.")
    else:
        print(f"Complete. Removed '{target_key}' ({total_removed} instance(s) across {len(modified_files)} file(s)).")


def cmd_depad():
    files = get_target_files()

    if not files:
        print("No language INI files found.")
        return

    total_replaced = 0
    modified_files = []

    for file_path in files:
        content = read_file_text(file_path)

        count_literal = content.count("\\n ")
        count_newline = content.count("\n ")

        if count_literal > 0 or count_newline > 0:
            new_content = content.replace("\\n ", "\\n").replace("\n ", "\n")
            file_path.write_bytes(new_content.encode("utf-16"))
            total_replaced += (count_literal + count_newline)
            modified_files.append(file_path)
            print(f"Depadded: {file_path}")

    if total_replaced == 0:
        print("No instances of '\\n ' found in any files.")
    else:
        print(f"Complete. Depadded {total_replaced} instance(s) across {len(modified_files)} file(s).")


def main():
    parser = argparse.ArgumentParser(
        description="Language File Management Tool",
        epilog="Run 'python LanguageFilesHandler.py <command> -h' for help on a specific subcommand."
    )

    subparsers = parser.add_subparsers(
        dest="command",
        title="available commands",
        help="Subcommand to execute"
    )

    # Subcommand: remove
    remove_parser = subparsers.add_parser("remove", help="Remove a key=value entry across all language files")
    remove_parser.add_argument("key", type=str, help="The exact English key name to remove")

    # Subcommand: depad
    depad_parser = subparsers.add_parser("depad", help="Replace all instances of '\\n ' with '\\n'")

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(0)

    args = parser.parse_args()

    if args.command == "remove":
        cmd_remove(args.key)
    elif args.command == "depad":
        cmd_depad()


if __name__ == "__main__":
    main()
