from tuning_utility.translations import tr_str
from audio_dsp.models.stage import all_models
from audio_dsp.models.fields import BIQUAD_TYPES
from typing import get_args
import sys
import subprocess
import glob
from pathlib import Path
import os


def test_param_translations(capfd):
    all_m = all_models()

    for m_name, m in all_m.items():
        if "parameters" not in m.model_fields:
            continue

        if "cascaded" in m_name.lower() or "parametric" in m_name.lower():
            # just a list of biquads, tested in biquad
            continue
        elif "biquad" in m_name.lower():
            # Biquad stages have a different structure
            for biquad_cls in BIQUAD_TYPES.__args__:
                tr_str(biquad_cls.__name__)
                for param_name in biquad_cls.model_fields:
                    tr_str(param_name)
        else:
            for field, value in type(m.model_fields["parameters"].default_factory()).model_fields.items():
                print(tr_str(field))
                if get_args(value.annotation):
                    for option in get_args(value.annotation):
                        if type(option) is str:
                            tr_str(option)

    out, err = capfd.readouterr()
    assert "No translation found for" not in out, "Some parameters are missing translations."


def test_translation_files():
    # Use subprocess.check_output to run the translation commands and capture output
    repo_root = Path(os.path.dirname(__file__)).parents[0]
    translation_path = repo_root / "python" / "tuning_utility" / "translations.py"

    try:
        output_generate = subprocess.check_output(
            [sys.executable, translation_path, "-generate"],
            stderr=subprocess.STDOUT,
            text=True
        )
        output_compile = subprocess.check_output(
            [sys.executable, translation_path, "-compile"],
            stderr=subprocess.STDOUT,
            text=True
        )
    except subprocess.CalledProcessError as e:
        assert False, f"Command failed with output:\n{e.output}"

    # Check for uncommitted changes after running the commands
    git_diff = subprocess.check_output(
        ["git", "diff", "--name-only"],
        stderr=subprocess.STDOUT,
        encoding="utf-8",
        errors="replace"
    )
    print(f"Git diff output:\n{git_diff}")
    assert git_diff == "", "There are uncommitted changes after running translation scripts."


def test_no_unfinished_translations():
    # Find all .ts files in the translations directory (adjust path as needed)
    ts_files = glob.glob("python/tuning_utility/locale/**.ts")
    unfinished_found = []
    for ts_file in ts_files:
        if "en" in ts_file:
            # Skip the English translation file as it expected to have unfinished translations
            continue
        with open(ts_file, encoding="utf-8", errors="replace") as f:
            content = f.read()
            if 'type="unfinished"' in content:
                unfinished_found.append(ts_file)
    assert not unfinished_found, f"Unfinished translations found in: {unfinished_found}"


if __name__ == "__main__":
    test_no_unfinished_translations()
    print("All tests passed.")