import torch
import torch.nn as nn
import torch.optim as optim

import torch.nn.functional as F
import torchaudio
import tqdm

from torch.utils.data import random_split
from torch.utils.data import DataLoader

from data import AudioDataset
from generator import SISUGenerator
from discriminator import SISUDiscriminator

# Mel Spectrogram Loss
class MelSpectrogramLoss(nn.Module):
    def __init__(self, sample_rate=44100, n_fft=2048, hop_length=512, n_mels=128):
        super(MelSpectrogramLoss, self).__init__()
        self.mel_transform = torchaudio.transforms.MelSpectrogram(
            sample_rate=sample_rate,
            n_fft=n_fft,
            hop_length=hop_length,
            n_mels=n_mels
        ).to(device) # Move to device

    def forward(self, y_pred, y_true):
        mel_pred = self.mel_transform(y_pred)
        mel_true = self.mel_transform(y_true)
        return F.l1_loss(mel_pred, mel_true)

def snr(y_true, y_pred):
    noise = y_true - y_pred
    signal_power = torch.mean(y_true ** 2)
    noise_power = torch.mean(noise ** 2)
    snr_db = 10 * torch.log10(signal_power / noise_power)
    return snr_db

def discriminator_train(high_quality, low_quality, scale, real_labels, fake_labels):
    optimizer_d.zero_grad()

    discriminator_decision_from_real = discriminator(high_quality)
    # TODO: Experiment with criterions HERE!
    d_loss_real = criterion_d(discriminator_decision_from_real, real_labels)

    generator_output = generator(low_quality, scale)
    discriminator_decision_from_fake = discriminator(generator_output.detach())
    # TODO: Experiment with criterions HERE!
    d_loss_fake = criterion_d(discriminator_decision_from_fake, fake_labels)

    d_loss = (d_loss_real + d_loss_fake) / 2.0

    d_loss.backward()
    nn.utils.clip_grad_norm_(discriminator.parameters(), max_norm=1.0) #Gradient Clipping
    optimizer_d.step()
    return d_loss

def generator_train(low_quality, scale, real_labels):
    optimizer_g.zero_grad()

    generator_output = generator(low_quality, scale)
    discriminator_decision = discriminator(generator_output)
    # TODO: Fix this shit
    g_loss = criterion_g(discriminator_decision, real_labels)

    g_loss.backward()
    optimizer_g.step()
    return generator_output

# Check for CUDA availability
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")

# Initialize dataset and dataloader
dataset_dir = './dataset/good'
dataset = AudioDataset(dataset_dir, target_duration=2.0)

dataset_size = len(dataset)
train_size = int(dataset_size * .9)
val_size = int(dataset_size-train_size)

train_dataset, val_dataset = random_split(dataset, [train_size, val_size])

train_data_loader = DataLoader(train_dataset, batch_size=1, shuffle=True)
val_data_loader = DataLoader(val_dataset, batch_size=1, shuffle=True)

# Initialize models and move them to device
generator = SISUGenerator()
discriminator = SISUDiscriminator()

generator = generator.to(device)
discriminator = discriminator.to(device)

# Loss
criterion_g = nn.L1Loss()
criterion_g_mel = MelSpectrogramLoss().to(device)
criterion_d = nn.BCEWithLogitsLoss()

# Optimizers
optimizer_g = optim.Adam(generator.parameters(), lr=0.0001, betas=(0.5, 0.999))
optimizer_d = optim.Adam(discriminator.parameters(), lr=0.0001, betas=(0.5, 0.999))

# Scheduler
scheduler_g = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer_g, mode='min', factor=0.5, patience=5)
scheduler_d = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer_d, mode='min', factor=0.5, patience=5)

def start_training():

    # Training loop

    # ========= DISCRIMINATOR PRE-TRAINING =========
    discriminator_epochs = 1
    for discriminator_epoch in range(discriminator_epochs):

        # ========= TRAINING =========
        for high_quality_clip, low_quality_clip in tqdm.tqdm(train_data_loader, desc=f"Epoch {discriminator_epoch+1}/{discriminator_epochs}"):
            high_quality_sample = high_quality_clip[0].to(device)
            low_quality_sample = low_quality_clip[0].to(device)

            scale = high_quality_clip[0].shape[2]/low_quality_clip[0].shape[2]

            # ========= LABELS =========
            batch_size = high_quality_sample.size(0)
            real_labels = torch.ones(batch_size, 1).to(device)
            fake_labels = torch.zeros(batch_size, 1).to(device)

            # ========= DISCRIMINATOR =========
            discriminator.train()
            discriminator_train(high_quality_sample, low_quality_sample, scale, real_labels, fake_labels)

        torch.save(discriminator.state_dict(), "models/discriminator-single-shot-pre-train.pt")

    generator_epochs = 500
    for generator_epoch in range(generator_epochs):
        low_quality_audio = (torch.empty((1)), 1)
        high_quality_audio = (torch.empty((1)), 1)
        ai_enhanced_audio = (torch.empty((1)), 1)

        # ========= TRAINING =========
        for high_quality_clip, low_quality_clip in tqdm.tqdm(train_data_loader, desc=f"Epoch {generator_epoch+1}/{generator_epochs}"):
            high_quality_sample = high_quality_clip[0].to(device)
            low_quality_sample = low_quality_clip[0].to(device)

            scale = high_quality_clip[0].shape[2]/low_quality_clip[0].shape[2]

            # ========= LABELS =========
            batch_size = high_quality_clip[0].size(0)
            real_labels = torch.ones(batch_size, 1).to(device)
            fake_labels = torch.zeros(batch_size, 1).to(device)

            # ========= DISCRIMINATOR =========
            discriminator.train()
            for _ in range(3):
                discriminator_train(high_quality_sample, low_quality_sample, scale, real_labels, fake_labels)

            # ========= GENERATOR =========
            generator.train()
            generator_output = generator_train(low_quality_sample, scale, real_labels)

            # ========= SAVE LATEST AUDIO =========
            high_quality_audio = high_quality_clip
            low_quality_audio = low_quality_clip
            ai_enhanced_audio = (generator_output, high_quality_clip[1])

        metric = snr(high_quality_audio[0].to(device), ai_enhanced_audio[0])
        print(f"Generator metric {metric}!")
        scheduler_g.step(metric)

        if generator_epoch % 10 == 0:
            print(f"Saved epoch {generator_epoch}!")
            torchaudio.save(f"./output/epoch-{generator_epoch}-audio-crap.wav", low_quality_audio[0][0].cpu(), low_quality_audio[1])
            torchaudio.save(f"./output/epoch-{generator_epoch}-audio-ai.wav", ai_enhanced_audio[0][0].cpu(), ai_enhanced_audio[1])
            torchaudio.save(f"./output/epoch-{generator_epoch}-audio-orig.wav", high_quality_audio[0][0].cpu(), high_quality_audio[1])

        if generator_epoch % 50 == 0:
            torch.save(discriminator.state_dict(), f"models/epoch-{generator_epoch}-discriminator.pt")
            torch.save(generator.state_dict(), f"models/epoch-{generator_epoch}-generator.pt")

    torch.save(discriminator.state_dict(), "models/epoch-500-discriminator.pt")
    torch.save(generator.state_dict(), "models/epoch-500-generator.pt")
    print("Training complete!")

start_training()
