import sys
import subprocess
import os
from pathlib import Path

from PySide6.QtCore import QCoreApplication, QTranslator, QLocale
from PySide6.QtWidgets import QApplication

def register_translations(app: QApplication):
    """
    Creates a QTranslator and registers the translations.

    Uses the translations from the locale directory based on the current locale.
    """
    locale_dir = Path(__file__).parent / "locale"

    translator = QTranslator(app)

    if translator.load(QLocale().name(), str(locale_dir)):
        app.installTranslator(translator)
    else:
        print("Could not load translation file.")


def tr_str(name):
    """Return translated name if available, else original."""
    translations = {
        # Stage names
        "reverb": QCoreApplication.translate("Stage", "Reverb"),
        # Parameter names
        "gain_db": QCoreApplication.translate("Parameter", "Gain (dB)"),
        "gains_db": QCoreApplication.translate("Parameter", "Gains (dB)"),

        "mute_state": QCoreApplication.translate("Parameter", "Mute"),
        "wet_dry_mix": QCoreApplication.translate("Parameter", "Wet/Dry Mix"),
        "position": QCoreApplication.translate("Parameter", "Position"),
        "delay": QCoreApplication.translate("Parameter", "Delay"),
        "ratio": QCoreApplication.translate("Parameter", "Ratio"),
        "threshold_db": QCoreApplication.translate("Parameter", "Threshold (dB)"),
        "attack_t": QCoreApplication.translate("Parameter", "Attack Time"),
        "release_t": QCoreApplication.translate("Parameter", "Release Time"),
        "predelay": QCoreApplication.translate("Parameter", "Pre-delay"),
        "pregain": QCoreApplication.translate("Parameter", "Pre-gain"),
        "damping": QCoreApplication.translate("Parameter", "Damping"),
        "decay": QCoreApplication.translate("Parameter", "Decay"),
        "room_size": QCoreApplication.translate("Parameter", "Room Size"),
        "width": QCoreApplication.translate("Parameter", "Width"),
        "early_diffusion": QCoreApplication.translate("Parameter", "Early Diffusion"),
        "late_diffusion": QCoreApplication.translate("Parameter", "Late Diffusion"),
        "bandwidth": QCoreApplication.translate("Parameter", "Bandwidth"),
        "mix": QCoreApplication.translate("Parameter", "Mix"),
        # Biquad/filter/PEQ/GEQ related
        "biquad_allpass": QCoreApplication.translate("Parameter", "Allpass"),
        "biquad_bandpass": QCoreApplication.translate("Parameter", "Bandpass"),
        "biquad_bandstop": QCoreApplication.translate("Parameter", "Bandstop"),
        "biquad_bypass": QCoreApplication.translate("Parameter", "Bypass"),
        "biquad_constant_q": QCoreApplication.translate("Parameter", "Constant Q"),
        "biquad_gain": QCoreApplication.translate("Parameter", "Linear Gain"),
        "biquad_highpass": QCoreApplication.translate("Parameter", "Highpass"),
        "biquad_highshelf": QCoreApplication.translate("Parameter", "Highshelf"),
        "biquad_linkwitz": QCoreApplication.translate("Parameter", "Linkwitz Transform"),
        "biquad_lowpass": QCoreApplication.translate("Parameter", "Lowpass"),
        "biquad_lowshelf": QCoreApplication.translate("Parameter", "Lowshelf"),
        "biquad_notch": QCoreApplication.translate("Parameter", "Notch"),
        "biquad_peaking": QCoreApplication.translate("Parameter", "Peaking"),
        "biquad_mute": QCoreApplication.translate("Parameter", "Mute"),
        "filter_freq": QCoreApplication.translate("Parameter", "Frequency"),
        "q_factor": QCoreApplication.translate("Parameter", "Q Factor"),
        "bw": QCoreApplication.translate("Parameter", "Bandwidth"),
        "boost_db": QCoreApplication.translate("Parameter", "Boost (dB)"),
        "f0": QCoreApplication.translate("Parameter", "f0"),
        "q0": QCoreApplication.translate("Parameter", "Q0"),
        "fp": QCoreApplication.translate("Parameter", "fp"),
        "qp": QCoreApplication.translate("Parameter", "Qp"),
        "highpass": QCoreApplication.translate("Parameter", "Highpass"),
        "lowpass": QCoreApplication.translate("Parameter", "Lowpass"),
        "bypass": QCoreApplication.translate("Parameter", "Bypass"),
        "type": QCoreApplication.translate("Parameter", "Type"),
        "filter": QCoreApplication.translate("Parameter", "Filter"),
        "butterworth": QCoreApplication.translate("Parameter", "Butterworth"),
        "order": QCoreApplication.translate("Parameter", "Order"),
        "units": QCoreApplication.translate("Parameter", "Units"),
        "samples": QCoreApplication.translate("Parameter", "Samples"),
        "s": QCoreApplication.translate("Parameter", "Seconds"),
        "ms": QCoreApplication.translate("Parameter", "Milliseconds"),
        # Application related
        "XMOS DSP Controller": QCoreApplication.translate("App", "XMOS DSP Controller"),
        "Load": QCoreApplication.translate("App", "Load"),
        "Save": QCoreApplication.translate("App", "Save"),
        "Generate Code": QCoreApplication.translate("App", "Generate Code"),
        "Save xDSP": QCoreApplication.translate("App", "Save xDSP"),
        "Open xDSP": QCoreApplication.translate("App", "Open xDSP"),
        "xDSP Files (*.json)": QCoreApplication.translate("App", "xDSP Files (*.json)"),
        # Plot related
        "Magnitude (dB)": QCoreApplication.translate("Plot", "Magnitude (dB)"),
        "Phase (rad)": QCoreApplication.translate("Plot", "Phase (rad)"),
        "Frequency (Hz)": QCoreApplication.translate("Plot", "Frequency (Hz)"),
        "frequency response": QCoreApplication.translate("Plot", "frequency response"),
        # numbers
        "2": QCoreApplication.translate("Number", "2"),
        "4": QCoreApplication.translate("Number", "4"),
        "6": QCoreApplication.translate("Number", "6"),
        "8": QCoreApplication.translate("Number", "8"),
        "10": QCoreApplication.translate("Number", "10"),
        "12": QCoreApplication.translate("Number", "12"),
        "14": QCoreApplication.translate("Number", "14"),
        "16": QCoreApplication.translate("Number", "16"),
    }

    if str(name) not in translations:
        print(f"No translation found for '{name}'. Using original name.")
    return translations.get(str(name), str(name))


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Translation utility for PySide6 project.")
    parser.add_argument("-generate", action="store_true", help="Generate .ts files from source Python files")
    parser.add_argument("-compile", action="store_true", help="Compile all .ts files in the locale folder to .qm files")
    args = parser.parse_args()

    tuning_root = Path(os.path.dirname(__file__))
    locale_dir = Path(tuning_root, "locale")
    sources = [
        Path(tuning_root, "..", "..", "tuning_gui.py"),
        Path(tuning_root, "widgets.py"),
        Path(tuning_root, "translations.py"),
        Path(tuning_root, "core.py"),
    ]

    if args.generate:
        for fname in os.listdir(locale_dir):
            if fname.endswith(".ts"):
                cmd = ["pyside6-lupdate"] + [str(s) for s in sources] + ["-ts", os.path.join(locale_dir, fname)]
                subprocess.run(cmd, check=True)
                print(f"Generated {fname}")
    elif args.compile:
        for fname in os.listdir(locale_dir):
            if fname.endswith(".ts"):
                ts_path = os.path.join(locale_dir, fname)
                qm_path = os.path.splitext(ts_path)[0] + ".qm"
                cmd = ["pyside6-lrelease", ts_path, "-qm", qm_path]
                subprocess.run(cmd, check=True)
                print(f"Compiled {qm_path}")
    else:
        print("Usage: python translations.py -generate | -compile")

