#!/usr/bin/env python3
import sys
import pathlib
import subprocess
from check_video import check_video_ext, normalize_language, normalize_lang_code

def collect_files(paths):
    files = []
    for p in paths:
        p = pathlib.Path(p)
        if p.is_dir():
            files += [f for f in p.iterdir() if check_video_ext(f.suffix)]
        elif check_video_ext(p.suffix):
            files.append(p)
    return files

def set_audio_lang(file_path, lang_code):
    """
    Sets the first audio track language to the given ISO 639-1 code using mkvpropedit.
    """
    try:
        # Target first audio track (track ID 1)
        subprocess.run([
            "mkvpropedit", str(file_path),
            "--edit", "track:a1",
            "--set", f"language={lang_code}"
        ], check=True)
        print(f"Set first audio track of '{file_path}' to {lang_code}")
    except subprocess.CalledProcessError as e:
        print(f"Failed to set language for '{file_path}': {e}")

def main():
    if len(sys.argv) == 1:
        targets = ["."]
        lang = "German"
    else:
        targets = sys.argv[1:]
        lang = "German"  # Hardcoded to German
    subprocess.run(["python", "/home/honney/.bin/tracker.py", "add", "set_1_ger"])

    lang = normalize_language(lang)
    lang_code = normalize_lang_code(lang)

    for f in collect_files(targets):
        set_audio_lang(f, lang_code)

if __name__ == "__main__":
    main()
