import os
import time
import gradio as gr
import numpy as np
import torch
from inference.tts.base_tts_infer import BaseTTSInfer
from utils.commons.ckpt_utils import load_ckpt
from utils.commons.hparams import hparams
from utils.text.text_encoder import build_token_encoder
from modules.TCSinger.tcsinger import SADecoder
from modules.TCSinger.sdlm import SDLM
from tasks.tts.vocoder_infer.base_vocoder import get_vocoder_cls
from utils.audio import librosa_wav2spec
from utils.commons.hparams import set_hparams
from utils.audio.io import save_wav
import json
import traceback

class StyleControlApp(BaseTTSInfer):
    def build_model(self):
        dict_size = len(self.ph_encoder)
        model = SDLM(dict_size, self.hparams)
        self.model_decoder = SADecoder()
        model.eval()
        # Check if binary_data_dir is present in hparams
        binary_data_dir = hparams.get('binary_data_dir', './default_binary_data')
        if not os.path.exists(binary_data_dir):
            raise FileNotFoundError(f"[ERROR] binary_data_dir '{binary_data_dir}' not found. Please check your hparams configuration.")

        print(f"[DEBUG] Using binary_data_dir: {binary_data_dir}")


        load_ckpt(model, hparams['exp_name'], strict=False)
        load_ckpt(self.model_decoder, hparams['decoder_ckpt_dir'], strict=False)
        self.model_decoder.to(self.device)
        self.ph_encoder = build_token_encoder('./ZHEN_checkpoint_phone_set.json')
        return model

    def build_vocoder(self):
        vocoder = get_vocoder_cls(hparams["vocoder"])()
        return vocoder

    def input_to_batch(self, item):
        item_names = [item['item_name']]
        text = [item['text']]
        ph = [item['ph']]
        print("MIXTECH1",item['mix_tech'])
        txt_tokens = torch.LongTensor(item['ph_token'])[None, :].to(self.device)
        txt_lengths = torch.LongTensor([txt_tokens.shape[1]]).to(self.device)
        note = torch.LongTensor(item['note'])[None, :].to(self.device)
        note_dur = torch.FloatTensor(item['note_dur'])[None, :].to(self.device)
        note_type = torch.LongTensor(item['note_type'][:hparams['max_input_tokens']]).to(self.device)
        mix_tech = torch.LongTensor(item['mix_tech'])[None, :].to(self.device)
        print("MIXTECH2",mix_tech)
        falsetto_tech = torch.LongTensor(item['falsetto_tech'])[None, :].to(self.device)
        breathy_tech = torch.LongTensor(item['breathy_tech'])[None, :].to(self.device)
        pharyngeal_tech = torch.LongTensor(item['pharyngeal_tech'])[None, :].to(self.device)
        glissando_tech = torch.LongTensor(item['glissando_tech'])[None, :].to(self.device)
        vibrato_tech = torch.LongTensor(item['vibrato_tech'])[None, :].to(self.device)
        emotion = [item['emotion']]
        pace = [item['pace']]
        range_ = [item['range_']]
        singing_method = [item['singing_method']]
        mels = torch.Tensor(item['mel'])[None, :].to(self.device)

        batch = {
            'item_name': item_names,
            'text': ph,
            'ph': ph,
            'txt_tokens': txt_tokens,
            'txt_lengths': txt_lengths,
            'notes': note,
            'note_durs': note_dur,
            'note_types': note_type,
            'mix_tech': mix_tech,
            'falsetto_tech': falsetto_tech,
            'breathy_tech': breathy_tech,
            'vibrato_tech': vibrato_tech,
            'pharyngeal_tech': pharyngeal_tech,
            'glissando_tech': glissando_tech,
            'emotion': emotion,
            'pace': pace,
            'range_': range_,
            'singing_method': singing_method,
            'mel_prompt': mels,
        }
        return batch


    def forward_model(self, inp):
        sample = self.input_to_batch(inp)
        txt_tokens = sample['txt_tokens']  # [B, T_t]
        print(sample)
        notes, note_durs,note_types = sample["notes"], sample["note_durs"],sample['note_types']
        emotion, pace, range_,singing_method = sample['emotion'], sample['pace'], sample['range_'], sample['singing_method']
        mix_tech, falsetto_tech, breathy_tech, pharyngeal_tech, glissando_tech, vibrato_tech = sample['mix_tech'], sample['falsetto_tech'], sample['breathy_tech'], sample['pharyngeal_tech'], sample['glissando_tech'], sample['vibrato_tech']
        mel_prompt = sample['mel_prompt']
        
        output = {}

        # Run model
        with torch.no_grad():
            output = self.model.infer(txt_tokens, None,
                tgt_mels=None, 
                infer=True,
                mel_prompt=mel_prompt,
                note=notes, note_dur=note_durs, note_type=note_types,
                emotion=emotion,singing_method=singing_method,pace=pace,range_=range_,
                mix=mix_tech, falsetto=falsetto_tech, breathy=breathy_tech, pharyngeal=pharyngeal_tech, glissando=glissando_tech, vibrato=vibrato_tech,control=True)
            self.model_decoder(tgt_mels=None, infer=True, ret=output, spk_embed=None)

            # Get gen mel
            mel_out =  output['mel_out'][0]
            pred_f0 = output.get('f0_denorm_pred')[0]
            wav_out = self.vocoder.spec2wav(mel_out.cpu(),f0=pred_f0.cpu())

        wav_out = wav_out
        return wav_out, mel_out
    



    def preprocess_input(self, inp):
        ph=' '.join(inp['ph'])
        ph_token = self.ph_encoder.encode(ph.replace('_en',''))
        print(ph_token)
        #return
        #ph_token=inp['text_gen']
        #note= inp['note_gen']
        note= inp['ep_pitches']
        note_dur=inp['ep_notedurs']
        note_type=inp['ep_types']

        wav_fn=inp['ref_audio']
        wav2spec_dict = librosa_wav2spec(
            wav_fn,
            fft_size=hparams['fft_size'],
            hop_size=hparams['hop_size'],
            win_length=hparams['win_size'],
            num_mels=hparams['audio_num_mel_bins'],
            fmin=hparams['fmin'],
            fmax=hparams['fmax'],
            sample_rate=hparams['audio_sample_rate'],
            loud_norm=hparams['loud_norm'])
        mel = wav2spec_dict['mel']
        mel = np.clip(mel, hparams['mel_vmin'], hparams['mel_vmax'])
        
        tech_list=inp['tech']

        mix=[]
        falsetto=[]
        breathy=[]
        pharyngeal=[]
        vibrato=[]
        glissando=[]    
        for element in tech_list:
            mix.append(1 if '1' in element else 0)
            falsetto.append(1 if '2' in element else 0)
            breathy.append(1 if '3' in element else 0)
            pharyngeal.append(1 if '4' in element else 0)
            vibrato.append(1 if '5' in element else 0)
            glissando.append(1 if '6' in element else 0)

        item = {'item_name': wav_fn, 'text': ph, 'ph': ph,
                'ph_token': ph_token, 'mel': mel, 'note':note, 'note_dur':note_dur, 'note_type':note_type,
                'mix_tech': mix, 'falsetto_tech': falsetto,
                'breathy_tech': breathy, 'pharyngeal_tech': pharyngeal,
                'glissando_tech': glissando, 'vibrato_tech': vibrato,
                'emotion': inp['emotion'], 'pace': inp['pace'], 'range_': inp['range_'],'singing_method':inp['singing_method']}
        item['ph_len'] = len(item['ph_token'])
        return item

def infer(prompt_audio, target_audio, target_json):
    print("[DEBUG] Infer function called")

    try:
        print(f"[DEBUG] target_audio: {target_audio}")
        print(f"[DEBUG] target_json: {target_json}")

        inp=json.loads(target_json)
        #with open(target_json.name, 'r') as f:
        #    inp = json.load(f)
        print("[DEBUG] Loaded target JSON metadata")

        print(f"[DEBUG] target_audio: {target_audio}")
        print(f"[DEBUG] target_info: {inp}")
        #inp = next(item for item in inp if ref_audio in item['wav_fn'])
        inp = next(item for item in inp)
        inp["ref_audio"] = prompt_audio
        #inp['ref_audio'] = ref_audio

        print("[DEBUG] Input prepared for inference")
        hparams['binary_data_dir']="./default_binary_data"
        #set_hparams(config='egs/sdlm.yaml', exp_name='checkpoints/SDLM',binary_data_dir='/data/GTSinger/processed/English/')
        set_hparams(config='egs/sdlm.yaml', exp_name='checkpoints/SDLM')

        infer_ins = StyleControlApp(hparams)
        #wav_out, _ = infer_ins.forward_model(inp)
        wav_out, _ = infer_ins.infer_once(inp)

        timestamp = time.strftime('%Y%m%d-%H%M%S')
        output_path = f"generated/output_{timestamp}.wav"
        os.makedirs('generated', exist_ok=True)
        save_wav(wav_out, output_path, hparams['audio_sample_rate'])

        print(f"[DEBUG] Inference completed, file saved at {output_path}")

        return output_path
    except Exception as e:
        print(f"[ERROR] Infer function error: {str(e)}")
        traceback.print_exc()
        return f"Error: {str(e)}"

def load_audio(file_path):
    """Returns the file path if it exists"""
    if file_path and os.path.exists(file_path):
        return file_path
    return None  # 
def process_json(json_str):
    """Handles the updated JSON from the editor"""
    try:
        parsed_data = json.loads(json_str)
        return json.dumps(parsed_data, indent=4)  # Pretty-print for display
    except json.JSONDecodeError:
        return "Invalid JSON"

custom_js = """
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/dialog/dialog.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/search/matchesonscrollbar.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/mode/javascript/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/search/search.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/search/searchcursor.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/search/match-highlighter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/dialog/dialog.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/edit/matchbrackets.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/edit/closebrackets.min.js"></script>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        var editorContainer = document.getElementById("editor-container");
        if (!editorContainer) {
            console.error("Editor container not found!");
            return;
        }

        var editor = CodeMirror(editorContainer, {
            mode: "application/json",
            lineNumbers: true,
            matchBrackets: true,
            autoCloseBrackets: true,
            theme: "default",
            viewportMargin: Infinity
        });

        // Sync changes with Gradio
        editor.on("change", function() {
            var gradioInput = document.getElementById("gradio_json");
            gradioInput.value = editor.getValue();
            gradioInput.dispatchEvent(new Event("input"));
        });

        // Function to load JSON into the editor
        window.loadJsonToEditor = function() {
            var gradioInput = document.getElementById("gradio_json");
            try {
                var jsonData = JSON.parse(gradioInput.value || '{}');
                editor.setValue(JSON.stringify(jsonData, null, 4));
            } catch (error) {
                console.error("Invalid JSON input:", error);
            }
        };
    });
</script>
"""
custom_js = """
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/dialog/dialog.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/search/matchesonscrollbar.min.css">

<script>
    function loadScript(url, callback) {
        var script = document.createElement("script");
        script.src = url;
        script.onload = callback;
        document.head.appendChild(script);
    }

    function loadCodeMirror() {
        loadScript("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.js", function() {
            loadScript("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/mode/javascript/javascript.min.js", function() {
                loadScript("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/search/search.min.js");
                loadScript("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/search/searchcursor.min.js");
                loadScript("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/search/match-highlighter.min.js");
                loadScript("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/dialog/dialog.min.js");
                loadScript("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/edit/matchbrackets.min.js");
                loadScript("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/edit/closebrackets.min.js");
                loadScript("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/search/jump-to-line.min.js", initCodeMirror);
            });
        });
    }

    function initCodeMirror() {
        var editorContainer = document.getElementById("editor-container");
        if (!editorContainer) {
            console.error("Editor container not found!");
            return;
        }

        window.editor = CodeMirror(editorContainer, {
            mode: "application/json",
            lineNumbers: true,
            matchBrackets: true,
            autoCloseBrackets: true,
            theme: "default",
            viewportMargin: Infinity,
            extraKeys: {
                "Ctrl-F": "findPersistent",
                "Cmd-F": "findPersistent",
                "Ctrl-H": "replace",
                "Cmd-H": "replace"
            }
        });

        // Sync changes with Gradio
        editor.on("change", function() {
            var gradioInput = document.getElementById("gradio_json");
            if (gradioInput) {
                gradioInput.value = editor.getValue();
                gradioInput.dispatchEvent(new Event("input"));
            }
        });
    }

    window.onload = function() {
        setTimeout(loadCodeMirror, 500);
    };

    function updateEditor() {
        var gradioInput = document.getElementById("gradio_json");
        if (window.editor && gradioInput.value) {
            window.editor.setValue(gradioInput.value);
        }
    }
</script>
"""

editor_html="""
<div id="toolbar">
    <button onclick="editor.execCommand('findPersistent')">🔍 Search</button>
    <button onclick="editor.execCommand('replace')">🔄 Replace</button>
    <input type="file" id="file-input" style="display: none;" onchange="handleFileLoad(event)">
</div>
<div id="editor-container" style="width: 100%; height: 300px; border: 1px solid #ccc;"></div>
"""
def main():
    with gr.Blocks(head=custom_js) as app:
        gr.Markdown("## Style-Control Song Generation")
        with gr.Row():
            prompt_file = gr.Audio(label="Prompt Audio File", type="filepath")
            local_prompt_file = gr.Textbox(label="Filepath on the Server")
            load_prompt_btn = gr.Button("Load Prompt")
            target_audio = gr.Audio(label="Target Audio File", type="filepath")
            #target_json = gr.File(label="Target JSON Metadata", type="filepath")
            local_target_file = gr.Textbox(label="Filepath on the Server")
            load_target_btn = gr.Button("Load Target")

        #generate_btn = gr.Button("Generate")

        load_prompt_btn.click(load_audio, inputs=[local_prompt_file], outputs=[prompt_file])
        load_target_btn.click(load_audio, inputs=[local_target_file], outputs=[target_audio])

        #target_json = gr.Code(label="Target JSON Metadata", language="json")
        gr.HTML(editor_html) 

        process_btn = gr.Button("Process JSON")
        json_output = gr.Textbox(label="Synced JSON Data", elem_id="gradio_json", lines=10)
        target_json = gr.Code(label="Processed JSON Output", language="json")
        process_btn.click(process_json, inputs=[json_output], outputs=[target_json])

        generate_btn = gr.Button("Generate")
        output_audio = gr.Audio(label="Generated Audio File", type="filepath")

        generate_btn.click(
            infer,
            inputs=[prompt_file, target_audio, target_json],
            outputs=[output_audio]
        )

    #app.launch(server_port=7777, root_path="/sing", auth=("singer", "SingeR"))
    app.launch(server_port=7777, root_path="/sing")

if __name__ == "__main__":
    main()

