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']]
        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)
        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 main():
    with gr.Blocks() 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")
        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()

