import os
import sys
import subprocess
import re
import platform
import torch
import logging
import yt_dlp
import json
import copy
import spaces
import gradio as gr
import urllib.parse
import assets.themes.loadThemes as loadThemes
from audio_separator.separator import Separator
from assets.i18n.i18n import I18nAuto
from argparse import ArgumentParser
from assets.presence.discord_presence import RPCManager, track_presence

i18n = I18nAuto()

now_dir = os.getcwd()
sys.path.append(now_dir)
config_file = os.path.join(now_dir, "assets", "config.json")
models_file = os.path.join(now_dir, "assets", "models.json")
default_settings_file = os.path.join(now_dir, "assets", "default_settings.json")
custom_settings_file = os.path.join(now_dir, "assets", "custom_settings.json")

device = "cuda" if torch.cuda.is_available() else "cpu"
use_autocast = device == "cuda"

if os.path.isdir("env"):
    if platform.system() == "Windows":
        python_location = ".\\env\\python.exe"
        separator_location = ".\\env\\Scripts\\audio-separator.exe"
    elif platform.system() == "Linux":
        python_location = "env/bin/python"
        separator_location = "env/bin/audio-separator"
else:
    python_location = None
    separator_location = "audio-separator"

#=======================#
#     VR-ARCH Models     #
#=======================#
vrarch_models = [
    '1_HP-UVR.pth',
    '2_HP-UVR.pth',
    '3_HP-Vocal-UVR.pth',
    '4_HP-Vocal-UVR.pth',
    '5_HP-Karaoke-UVR.pth',
    '6_HP-Karaoke-UVR.pth',
    '7_HP2-UVR.pth',
    '8_HP2-UVR.pth',
    '9_HP2-UVR.pth',
    '10_SP-UVR-2B-32000-1.pth',
    '11_SP-UVR-2B-32000-2.pth',
    '12_SP-UVR-3B-44100.pth',
    '13_SP-UVR-4B-44100-1.pth',
    '14_SP-UVR-4B-44100-2.pth',
    '15_SP-UVR-MID-44100-1.pth',
    '16_SP-UVR-MID-44100-2.pth',
    '17_HP-Wind_Inst-UVR.pth',
    'UVR-De-Echo-Aggressive.pth',
    'UVR-De-Echo-Normal.pth',
    'UVR-DeEcho-DeReverb.pth',
    'UVR-De-Reverb-aufr33-jarredou.pth',
    'UVR-DeNoise-Lite.pth',
    'UVR-DeNoise.pth',
    'UVR-BVE-4B_SN-44100-1.pth',
    'MGM_HIGHEND_v4.pth',
    'MGM_LOWEND_A_v4.pth',
    'MGM_LOWEND_B_v4.pth',
    'MGM_MAIN_v4.pth',
]

output_format = [
    'wav',
    'flac',
    'mp3',
    'ogg',
    'opus',
    'm4a',
    'aiff',
    'ac3'
]

found_files = []
logs = []
out_dir = "./outputs"
models_dir = "./models"
extensions = (".wav", ".flac", ".mp3", ".ogg", ".opus", ".m4a", ".aiff", ".ac3")

def load_config_presence():
    with open(config_file, "r", encoding="utf8") as file:
        config = json.load(file)
        return config["discord_presence"]

def initialize_presence():
    if load_config_presence():
        RPCManager.start_presence()

initialize_presence()

def download_audio(url, output_dir="ytdl"):

    os.makedirs(output_dir, exist_ok=True)

    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'wav',
            'preferredquality': '32',
        }],
        'outtmpl': os.path.join(output_dir, '%(title)s.%(ext)s'),
        'postprocessor_args': [
            '-acodec', 'pcm_f32le'
        ],
    }

    try:
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(url, download=False)
            video_title = info['title']

            ydl.download([url])

            file_path = os.path.join(output_dir, f"{video_title}.wav")

            if os.path.exists(file_path):
                return os.path.abspath(file_path)
            else:
                raise Exception("Something went wrong")

    except Exception as e:
        raise Exception(f"Error extracting audio with yt-dlp: {str(e)}")

@track_presence("Performing VR Arch Separation")
@spaces.GPU(duration=60)
def vrarch_separator(audio, model, out_format, window_size, aggression, tta, post_process, post_process_threshold, high_end_process, batch_size, norm_thresh, amp_thresh, single_stem, progress=gr.Progress(track_tqdm=True)):
    model_path = os.path.join(models_dir, model)
    try:
        if not os.path.exists(model_path):
            gr.Info(f"This is the first time the {model} model is being used. The separation will take a little longer because the model needs to be downloaded.")

        separator = Separator(
            log_level=logging.WARNING,
            model_file_dir=models_dir,
            output_dir=out_dir,
            output_format=out_format,
            use_autocast=use_autocast,
            normalization_threshold=norm_thresh,
            amplification_threshold=amp_thresh,
            output_single_stem=single_stem,
            vr_params={
                "batch_size": batch_size,
                "window_size": window_size,
                "aggression": aggression,
                "enable_tta": tta,
                "enable_post_process": post_process,
                "post_process_threshold": post_process_threshold,
                "high_end_process": high_end_process,
            }
        )

        progress(0.2, desc="Loading model...")
        separator.load_model(model_filename=model)

        progress(0.7, desc="Separating audio...")
        separation = separator.separate(audio)

        stems = [os.path.join(out_dir, file_name) for file_name in separation]
        
        if single_stem.strip():
            return stems[0], None
        
        return stems[0], stems[1]

    except Exception as e:
        raise RuntimeError(f"VR ARCH separation failed: {e}") from e

@track_presence("Performing VR Arch Batch Separation")
@spaces.GPU(duration=60)
def vrarch_batch(path_input, path_output, model, out_format, window_size, aggression, tta, post_process, post_process_threshold, high_end_process, batch_size, norm_thresh, amp_thresh, single_stem, progress=gr.Progress()):
    found_files.clear()
    logs.clear()
    model_path = os.path.join(models_dir, model)

    if not os.path.exists(model_path):
        gr.Info(f"This is the first time the {model} model is being used. The separation will take a little longer because the model needs to be downloaded.")

    for audio_files in os.listdir(path_input):
        if audio_files.endswith(extensions):
            found_files.append(audio_files)
    total_files = len(found_files)

    if total_files == 0:
        logs.append("No valid audio files.")
        return "\n".join(logs)
    else:
        logs.append(f"{total_files} audio files found")
        found_files.sort()
        progress(0, desc="Starting processing...")

        for i, audio_files in enumerate(found_files):
            progress((i / total_files), desc=f"Processing file {i+1}/{total_files}")
            file_path = os.path.join(path_input, audio_files)
            try:
                separator = Separator(
                    log_level=logging.WARNING,
                    model_file_dir=models_dir,
                    output_dir=path_output,
                    output_format=out_format,
                    use_autocast=use_autocast,
                    normalization_threshold=norm_thresh,
                    amplification_threshold=amp_thresh,
                    output_single_stem=single_stem,
                    vr_params={
                        "batch_size": batch_size,
                        "window_size": window_size,
                        "aggression": aggression,
                        "enable_tta": tta,
                        "enable_post_process": post_process,
                        "post_process_threshold": post_process_threshold,
                        "high_end_process": high_end_process,
                    }
                )

                logs.append("Loading model...")
                separator.load_model(model_filename=model)

                logs.append(f"Separating file: {audio_files}")
                separator.separate(file_path)
                logs.append(f"File: {audio_files} separated!")
            except Exception as e:
                raise RuntimeError(f"VR Arch batch separation failed: {e}") from e
            
        progress(1.0, desc="Processing complete")
        return "\n".join(logs)

components = {
    "VR Arch": {}
}

def read_main_config():
    try:
        with open(config_file, "r", encoding="utf8") as f:
            return json.load(f)
    except Exception as e:
        print(f"Error reading main config file '{config_file}': {e}")
        gr.Warning(i18n("Error reading main config file"))
    
def write_main_config(data):
    try:
        with open(config_file, "w", encoding="utf8") as f:
            json.dump(data, f, indent=2)
    except Exception as e:
        print(f"Error writing to main config file '{config_file}': {e}")
        gr.Warning(i18n("Error writing to main config file"))

def load_settings_from_file(filepath):
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"Error reading settings file '{filepath}': {e}")
        gr.Warning(i18n("Error reading settings file"))
        return None
    
def get_initial_settings():
    main_config = read_main_config()
    load_custom = main_config.get('load_custom_settings', False)

    settings_to_load = {}
    default_settings = load_settings_from_file(default_settings_file)

    if load_custom:
        print("Attempting to load custom settings...")
        custom_settings = load_settings_from_file(custom_settings_file)
        if custom_settings:
            settings_to_load = copy.deepcopy(default_settings)
            for section, params in custom_settings.items():
                if section in settings_to_load:
                    for key, value in params.items():
                        settings_to_load[section][key] = value
                else:
                    settings_to_load[section] = params
            print("Custom settings loaded successfully.")
        else:
            print("Custom settings file not found or invalid. Falling back to default settings.")
            settings_to_load = default_settings
    else:
        print("Loading default settings...")
        settings_to_load = default_settings

    return settings_to_load

initial_settings = get_initial_settings()

with gr.Blocks(theme = loadThemes.load_json() or "NoCrypt/miku", title = "🎵 UVR5 UI 🎵") as app:
    gr.Markdown("<h1> 🎵 UVR5 UI 🎵 </h1>")
    gr.Markdown(i18n("If you liked this HF Space you can give me a ❤️"))
    gr.Markdown(i18n("Try UVR5 UI using Colab [here](https://colab.research.google.com/github/Eddycrack864/UVR5-UI/blob/main/UVR_UI.ipynb)"))
    with gr.Tabs():
        with gr.TabItem("VR ARCH"):
            with gr.Row():
                vrarch_model = gr.Dropdown(
                    label = i18n("Select the model"),
                    choices = vrarch_models,
                    value = initial_settings.get("VR Arch", {}).get("model", None),
                    interactive = True
                )
                vrarch_output_format = gr.Dropdown(
                    label = i18n("Select the output format"),
                    choices = output_format,
                    value = initial_settings.get("VR Arch", {}).get("output_format", None),
                    interactive = True
                )
            with gr.Accordion(i18n("Advanced settings"), open = False):
                with gr.Group():
                    with gr.Row():
                        vrarch_window_size = gr.Slider(
                            label = i18n("Window size"),
                            info = i18n("Balance quality and speed. 1024 = fast but lower, 320 = slower but better quality"),
                            minimum=320,
                            maximum=1024,
                            step=32,
                            value = initial_settings.get("VR Arch", {}).get("window_size", 512),
                            interactive = True
                        )
                        vrarch_agression = gr.Slider(
                            minimum = 1,
                            maximum = 50,
                            step = 1,
                            label = i18n("Agression"),
                            info = i18n("Intensity of primary stem extraction"),
                            value = initial_settings.get("VR Arch", {}).get("aggression", 5),
                            interactive = True
                        )
                        vrarch_tta = gr.Checkbox(
                            label = i18n("TTA"),
                            info = i18n("Enable Test-Time-Augmentation; slow but improves quality"),
                            value = initial_settings.get("VR Arch", {}).get("tta", True),
                            visible = True,
                            interactive = True
                        )
                    with gr.Row():
                        vrarch_post_process = gr.Checkbox(
                            label = i18n("Post process"),
                            info = i18n("Identify leftover artifacts within vocal output; may improve separation for some songs"),
                            value = initial_settings.get("VR Arch", {}).get("post_process", False),
                            visible = True,
                            interactive = True
                        )
                        vrarch_post_process_threshold = gr.Slider(
                            label = i18n("Post process threshold"),
                            info = i18n("Threshold for post-processing"),
                            minimum = 0.1,
                            maximum = 0.3,
                            step = 0.1,
                            value = initial_settings.get("VR Arch", {}).get("post_process_threshold", 0.2),
                            interactive = True
                        )
                    with gr.Row():
                        vrarch_high_end_process = gr.Checkbox(
                            label = i18n("High end process"),
                            info = i18n("Mirror the missing frequency range of the output"),
                            value = initial_settings.get("VR Arch", {}).get("high_end_process", False),
                            visible = True,
                            interactive = True,
                        )
                        vrarch_batch_size = gr.Slider(
                            label = i18n("Batch size"),
                            info = i18n("Larger consumes more RAM but may process slightly faster"),
                            minimum = 1,
                            maximum = 16,
                            step = 1,
                            value = initial_settings.get("VR Arch", {}).get("batch_size", 1),
                            interactive = True
                        )
                    with gr.Row():
                        vrarch_normalization_threshold = gr.Slider(
                            label = i18n("Normalization threshold"),
                            info = i18n("The threshold for audio normalization"),
                            minimum = 0.1,
                            maximum = 1,
                            step = 0.1,
                            value = initial_settings.get("VR Arch", {}).get("normalization_threshold", 0.9),
                            interactive = True
                        )
                        vrarch_amplification_threshold = gr.Slider(
                            label = i18n("Amplification threshold"),
                            info = i18n("The threshold for audio amplification"),
                            minimum = 0.1,
                            maximum = 1,
                            step = 0.1,
                            value = initial_settings.get("VR Arch", {}).get("amplification_threshold", 0.7),
                            interactive = True
                        )
                    with gr.Row():
                        vrarch_single_stem = gr.Textbox(
                            label = i18n("Output only single stem"),
                            placeholder = i18n("Write the stem you want, check the stems of each model on Leaderboard. e.g. Instrumental"),
                            value = initial_settings.get("VR Arch", {}).get("single_stem", ""),
                            interactive = True
                        )

                    components["VR Arch"] = {
                        "model": vrarch_model,
                        "output_format": vrarch_output_format,
                        "window_size": vrarch_window_size,
                        "aggression": vrarch_agression,
                        "tta": vrarch_tta,
                        "post_process": vrarch_post_process,
                        "post_process_threshold": vrarch_post_process_threshold,
                        "high_end_process": vrarch_high_end_process,
                        "batch_size": vrarch_batch_size,
                        "normalization_threshold": vrarch_normalization_threshold,
                        "amplification_threshold": vrarch_amplification_threshold,
                        "single_stem": vrarch_single_stem
                    }

            with gr.Row():
                vrarch_audio = gr.Audio(
                    label = i18n("Input audio"),
                    type = "filepath",
                    interactive = True
                )
            with gr.Accordion(i18n("Separation by link"), open = False):
                with gr.Row():
                    vrarch_link = gr.Textbox(
                        label = i18n("Link"),
                        placeholder = i18n("Paste the link here"),
                        interactive = True
                    )
                with gr.Row():
                    gr.Markdown(i18n("You can paste the link to the video/audio from many sites, check the complete list [here](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md)"))
                with gr.Row():
                    vrarch_download_button = gr.Button(
                        i18n("Download!"),
                        variant = "primary"
                )

            vrarch_download_button.click(download_audio, [vrarch_link], [vrarch_audio])
            
            with gr.Accordion(i18n("Batch separation"), open = False):
                with gr.Row():
                    vrarch_input_path = gr.Textbox(
                        label = i18n("Input path"),
                        placeholder = i18n("Place the input path here"),
                        interactive = True
                    )
                    vrarch_output_path = gr.Textbox(
                        label = i18n("Output path"),
                        placeholder = i18n("Place the output path here"),
                        interactive = True
                    )
                with gr.Row():
                    vrarch_bath_button = gr.Button(i18n("Separate!"), variant = "primary")
                with gr.Row():
                    vrarch_info = gr.Textbox(
                        label = i18n("Output information"),
                        interactive = False
                    )

            vrarch_bath_button.click(vrarch_batch, [vrarch_input_path, vrarch_output_path, vrarch_model, vrarch_output_format, vrarch_window_size, vrarch_agression, vrarch_tta, vrarch_post_process, vrarch_post_process_threshold, vrarch_high_end_process, vrarch_batch_size, vrarch_normalization_threshold, vrarch_amplification_threshold, vrarch_single_stem], [vrarch_info])

            with gr.Row():
                vrarch_button = gr.Button(i18n("Separate!"), variant = "primary")
            with gr.Row():
                vrarch_stem1 = gr.Audio(
                    show_download_button = True,
                    interactive = False,
                    type = "filepath",
                    label = i18n("Stem 1")
                )
                vrarch_stem2 = gr.Audio(
                    show_download_button = True,
                    interactive = False,
                    type = "filepath",
                    label = i18n("Stem 2")
                )

            vrarch_button.click(vrarch_separator, [vrarch_audio, vrarch_model, vrarch_output_format, vrarch_window_size, vrarch_agression, vrarch_tta, vrarch_post_process, vrarch_post_process_threshold, vrarch_high_end_process, vrarch_batch_size, vrarch_normalization_threshold, vrarch_amplification_threshold, vrarch_single_stem], [vrarch_stem1, vrarch_stem2])

app.queue()
app.launch()

give me a clean list of model names from this