import os
import time
import json
import traceback
import torch
import numpy as np
from sanic import Sanic,response
from sanic.response import json as sanic_json, file as sanic_file
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

# Initialize Sanic app
app = Sanic("TCSingerAPI")

# Load models at startup
class StyleControlApp(BaseTTSInfer):
    def build_model(self):
        model = SDLM(len(self.ph_encoder), self.hparams)
        self.model_decoder = SADecoder()
        model.eval()
        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):
        return get_vocoder_cls(hparams["vocoder"])()

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

        wav2spec_dict = librosa_wav2spec(
            inp['ref_audio'], 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 = np.clip(wav2spec_dict['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)


        return {
            'item_name': inp['ref_audio'], 'text': ' '.join(inp['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']
        }

    def input_to_batch(self, item):
        print(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,
            'ph_token': item['ph_token'],
            'txt_token': txt_tokens,
            'txt_length': txt_lengths,
            'note': note,
            'note_dur': note_dur,
            'note_type': 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 infer_audio(self, input_data):
        sample = self.input_to_batch(self.preprocess_input(input_data))
        txt_tokens = torch.LongTensor(sample['ph_token'])[None, :].to(self.device)
        print(sample)
        print(txt_tokens)
        with torch.no_grad():
            output = self.model.infer(
                txt_tokens, None, infer=True, mel_prompt=sample['mel_prompt'],
                note=sample["note"], note_dur=sample["note_dur"], note_type=sample['note_type'],
                emotion=sample["emotion"], singing_method=sample['singing_method'],
                pace=sample['pace'], range_=sample['range_'],
                mix=sample['mix_tech'], falsetto=sample['falsetto_tech'],
                breathy=sample['breathy_tech'], pharyngeal=sample['pharyngeal_tech'],
                glissando=sample['glissando_tech'], vibrato=sample['vibrato_tech'], control=True
            )
            self.model_decoder(tgt_mels=None, infer=True, ret=output, spk_embed=None)

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

        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'])

        return output_path

# Initialize TTS model
hparams['binary_data_dir']="./default_binary_data"
set_hparams(config='egs/sdlm.yaml', exp_name='checkpoints/SDLM')
tts_model = StyleControlApp(hparams)

@app.route("/sing/infer", methods=["POST"])
async def infer(request):
    try:
        input_data = request.json
        print(input_data)
        print("WTF")
        output_path = tts_model.infer_audio(input_data)
        return sanic_json({"success": True, "audio_path": output_path})
    except Exception as e:
        traceback.print_exc()
        return sanic_json({"success": False, "error": str(e)})

@app.route("/sing/download/<filename>")
async def download(request, filename):
    file_path = os.path.join("generated", filename)
    if os.path.exists(file_path):
        return await sanic_file(file_path)
    return sanic_json({"error": "File not found"}, status=404)

if __name__ == "__main__":
    app.run(
        host="0.0.0.0",
        port=7777,
        access_log=True,
        workers=1
    )

