import os
import sys
import soxr
import torch
import torchaudio
import librosa
import soundfile as sf
import numpy as np
import re
import unicodedata
from rvc.lib.tools.http_download import download_http
from torch import nn

import logging
import warnings

# Remove this to see warnings about transformers models
warnings.filterwarnings("ignore")

logging.getLogger("fairseq").setLevel(logging.ERROR)
logging.getLogger("faiss.loader").setLevel(logging.ERROR)
logging.getLogger("transformers").setLevel(logging.ERROR)
logging.getLogger("torch").setLevel(logging.ERROR)

now_dir = os.getcwd()
sys.path.append(now_dir)

_HubertModelWithFinalProj = None


def get_hubert_model_class():
    global _HubertModelWithFinalProj
    if _HubertModelWithFinalProj is None:
        # HuBERT is audio-only, but Transformers also probes optional vision
        # packages. Some ROCm wheels leave torchvision installed without its
        # native operators; do not let that unrelated dependency block audio.
        from transformers import utils as transformers_utils
        from transformers.utils import import_utils

        if import_utils.is_torchvision_available():
            try:
                import torchvision
            except (ImportError, OSError, RuntimeError) as error:
                logging.getLogger(__name__).warning(
                    "Ignoring unavailable optional torchvision for HuBERT: %s", error
                )
                import_utils._torchvision_available = False
                import_utils.is_torchvision_available = lambda: False
                import_utils.is_torchvision_v2_available = lambda: False
                # Transformers re-exports these checks from utils, and image
                # modules may import that alias rather than import_utils.
                transformers_utils.is_torchvision_available = lambda: False
                transformers_utils.is_torchvision_v2_available = lambda: False

        from transformers import HubertModel

        class _RealHubertModelWithFinalProj(HubertModel):
            def __init__(self, config):
                super().__init__(config)
                self.final_proj = nn.Linear(
                    config.hidden_size, config.classifier_proj_size
                )

        _HubertModelWithFinalProj = _RealHubertModelWithFinalProj
    return _HubertModelWithFinalProj


class _HubertModelMeta(type):
    def __instancecheck__(cls, instance):
        return isinstance(instance, get_hubert_model_class())

    def __subclasscheck__(cls, subclass):
        return issubclass(subclass, get_hubert_model_class())

    def __getattr__(cls, name):
        return getattr(get_hubert_model_class(), name)


class HubertModelWithFinalProj(metaclass=_HubertModelMeta):
    def __new__(cls, *args, **kwargs):
        real_cls = get_hubert_model_class()
        return real_cls(*args, **kwargs)

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        real_cls = get_hubert_model_class()
        return real_cls.from_pretrained(*args, **kwargs)


def load_audio_16k(file):
    # this is used by f0 and feature extractions that load preprocessed 16k files, so there's no need to resample
    try:
        audio, sr = librosa.load(file, sr=16000)
    except Exception as error:
        raise RuntimeError(f"An error occurred loading the audio: {error}")

    return audio.flatten()


def load_audio(file, sample_rate):
    try:
        file = file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
        audio, sr = sf.read(file)
        if len(audio.shape) > 1:
            audio = librosa.to_mono(audio.T)
        if sr != sample_rate:
            audio = librosa.resample(
                audio, orig_sr=sr, target_sr=sample_rate, res_type="soxr_vhq"
            )
    except Exception as error:
        raise RuntimeError(f"An error occurred loading the audio: {error}")

    return audio.flatten()


def load_audio_ta(file, sample_rate):
    try:
        file = file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
        audio, sr = sf.read(file)
        audio = np.asarray(audio, dtype=np.float32)
        if len(audio.shape) > 1:
            audio = librosa.to_mono(audio.T)
        if sr != sample_rate:
            transform = torchaudio.transforms.Resample(
                orig_freq=sr,
                new_freq=sample_rate,
                lowpass_filter_width=128,
            )
            audio = torch.from_numpy(audio).unsqueeze(0)
            audio = transform(audio).squeeze(0).contiguous().numpy()

    except Exception as error:
        raise RuntimeError(f"An error occurred loading the audio: {error}")

    return audio


def load_audio_infer(
    file,
    sample_rate,
    **kwargs,
):
    formant_shifting = kwargs.get("formant_shifting", False)
    try:
        file = file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
        if not os.path.isfile(file):
            raise FileNotFoundError(f"File not found: {file}")
        audio, sr = sf.read(file)
        if len(audio.shape) > 1:
            audio = librosa.to_mono(audio.T)
        if (
            kwargs.get("cleanup_mode", "off") != "off"
            and kwargs.get("cleanup_stage", "input") == "input"
        ):
            from rvc.lib.tools.audio_cleanup import cleanup_audio

            audio = cleanup_audio(
                audio, sr, kwargs["cleanup_mode"], kwargs.get("cleanup_strength", 12)
            )
        if sr != sample_rate:
            audio = librosa.resample(
                audio, orig_sr=sr, target_sr=sample_rate, res_type="soxr_vhq"
            )
        if formant_shifting:
            formant_qfrency = kwargs.get("formant_qfrency", 1.0)
            formant_timbre = kwargs.get("formant_timbre", 1.0)

            from rvc.lib.tools.formant import FormantShifter

            audio = FormantShifter(sample_rate).process_file(
                audio,
                quefrency=formant_qfrency,
                timbre=formant_timbre,
            )
    except Exception as error:
        raise RuntimeError(f"An error occurred loading the audio: {error}")
    return np.array(audio).flatten()


def format_title(title):
    formatted_title = unicodedata.normalize("NFC", title)
    formatted_title = re.sub(r"[\u2500-\u257F]+", "", formatted_title)
    formatted_title = re.sub(r"[^\w\s.-]", "", formatted_title, flags=re.UNICODE)
    formatted_title = re.sub(r"\s+", "_", formatted_title)
    return formatted_title


def load_embedding(embedder_model, custom_embedder=None):
    embedder_root = os.path.join(now_dir, "rvc", "models", "embedders")
    embedding_list = {
        "contentvec": os.path.join(embedder_root, "contentvec"),
        "spin": os.path.join(embedder_root, "spin"),
        "spin-v2": os.path.join(embedder_root, "spin-v2"),
        "chinese-hubert-base": os.path.join(embedder_root, "chinese_hubert_base"),
        "japanese-hubert-base": os.path.join(embedder_root, "japanese_hubert_base"),
        "korean-hubert-base": os.path.join(embedder_root, "korean_hubert_base"),
    }

    online_embedders = {
        "contentvec": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/contentvec/pytorch_model.bin",
        "spin": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/spin/pytorch_model.bin",
        "spin-v2": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/spin-v2/pytorch_model.bin",
        "chinese-hubert-base": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/chinese_hubert_base/pytorch_model.bin",
        "japanese-hubert-base": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/japanese_hubert_base/pytorch_model.bin",
        "korean-hubert-base": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/korean_hubert_base/pytorch_model.bin",
    }

    config_files = {
        "contentvec": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/contentvec/config.json",
        "spin": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/spin/config.json",
        "spin-v2": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/spin-v2/config.json",
        "chinese-hubert-base": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/chinese_hubert_base/config.json",
        "japanese-hubert-base": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/japanese_hubert_base/config.json",
        "korean-hubert-base": "https://huggingface.co/IAHispano/Applio/resolve/main/Resources/embedders/korean_hubert_base/config.json",
    }

    if embedder_model == "custom":
        if os.path.exists(custom_embedder):
            model_path = custom_embedder
        else:
            print(f"Custom embedder not found: {custom_embedder}, using contentvec")
            model_path = embedding_list["contentvec"]
    else:
        model_path = embedding_list[embedder_model]
        bin_file = os.path.join(model_path, "pytorch_model.bin")
        json_file = os.path.join(model_path, "config.json")
        os.makedirs(model_path, exist_ok=True)
        if not os.path.exists(bin_file):
            url = online_embedders[embedder_model]
            print(f"Downloading {url} to {model_path}...")
            download_http(url, bin_file)
        if not os.path.exists(json_file):
            url = config_files[embedder_model]
            print(f"Downloading {url} to {model_path}...")
            download_http(url, json_file)

    models = HubertModelWithFinalProj.from_pretrained(model_path)
    return models
