"""Stream Resp-229K clips labeled for Frame ASD.

Train and valid items are timed spans from audio_descriptions.jsonl (16 kHz),
cut or repeat-padded to desired_length. Descriptions without a start and end
in seconds are skipped.

Test items are whole KAUH recordings. The filename sound code is the file-level
label. COUGHVID clips and Bronchial recordings are left out of Score.
"""

import json
import os

import numpy as np
import torch
from torch.utils.data import Dataset, WeightedRandomSampler

from util.desc_labels import (
    description_to_windows, kauh_file_label, kauh_sound_code, patient_id_from_name,
)
from util.icbhi_util import cut_pad_sample_torchaudio


CLASS_NAMES = ('normal', 'crackle', 'wheeze', 'both')
# Official ICBHI train cycle mix: 2063, 1215, 501, 363 of 4142.
ICBHI_TRAIN_PRIOR = (0.498, 0.293, 0.121, 0.088)
# A WAV header alone is 44 bytes. Smaller files, and header-only files, have no samples.
MIN_WAV_BYTES = 45


def _load_description_windows(path):
    """Map filename -> list of (start_sec, end_sec, label, clause)."""
    windows = {}
    with open(path, 'r', encoding='utf-8') as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            row = json.loads(line)
            name = row.get('audio_filename')
            if not name:
                continue
            windows[name] = description_to_windows(row.get('description') or '')
    return windows


def _load_description_labels(path):
    """File-level OR labels. Kept for callers that do not slice events."""
    from util.desc_labels import description_to_label

    labels = {}
    with open(path, 'r', encoding='utf-8') as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            row = json.loads(line)
            labels[row['audio_filename']] = description_to_label(row.get('description') or '')
    return labels


def load_window(path, args, start_sec, end_sec):
    """Mono 16 kHz clip of [start_sec, end_sec], then fit to desired_length.

    Only the first desired_length seconds of a longer event are read.
    Unreadable files become silence of the target length so one bad wav
    does not stop an epoch.
    """
    import librosa

    target = int(args.desired_length * args.sample_rate)
    span = max(0.0, float(end_sec) - float(start_sec))
    take = min(span, float(args.desired_length))
    try:
        if take <= 0:
            return torch.zeros(target, dtype=torch.float32)
        audio, _ = librosa.load(
            path, sr=args.sample_rate, mono=True,
            offset=float(start_sec), duration=take,
        )
        wave = torch.from_numpy(np.asarray(audio, dtype=np.float32)).unsqueeze(0)
        if wave.shape[-1] < 1:
            return torch.zeros(target, dtype=torch.float32)
        wave = cut_pad_sample_torchaudio(wave, args)
        return wave.reshape(-1).contiguous().float()
    except Exception as exc:
        print('Unreadable audio, using silence: {} ({})'.format(path, exc))
        return torch.zeros(target, dtype=torch.float32)


def load_clip(path, args):
    """Whole-file clip. Event training uses load_window instead."""
    return load_window(path, args, 0.0, float(args.desired_length))


def load_full(path, args):
    """Mono waveform at args.sample_rate, full duration, no cut or pad."""
    import librosa

    try:
        audio, _ = librosa.load(path, sr=args.sample_rate, mono=True)
        wave = torch.from_numpy(np.asarray(audio, dtype=np.float32)).reshape(-1)
        if wave.numel() < 1:
            return torch.zeros(1, dtype=torch.float32)
        return wave.contiguous().float()
    except Exception as exc:
        print('Unreadable audio, using silence: {} ({})'.format(path, exc))
        return torch.zeros(1, dtype=torch.float32)


def collate_padded_waves(batch):
    """Pad a batch of variable-length waves. padding_mask True is the padded tail."""
    waves, labels, patients = zip(*batch)
    max_len = max(int(wave.numel()) for wave in waves)
    padded = waves[0].new_zeros(len(waves), max_len)
    padding_mask = torch.ones(len(waves), max_len, dtype=torch.bool)
    for index, wave in enumerate(waves):
        length = int(wave.numel())
        padded[index, :length] = wave
        padding_mask[index, :length] = False
    return (
        padded,
        torch.stack(labels, dim=0),
        torch.stack(patients, dim=0),
        padding_mask,
    )


class Resp229KDataset(Dataset):
    """audio_images entries are (path, label, device, patient_id, start_sec, end_sec).

    Index 1 is the 4-class label so get_frame_pos_weights can count
    positives without decoding audio. Test entries use the whole file:
    start_sec and end_sec are 0 and the waveform is not cut to desired_length.
    """

    def __init__(self, split, args, print_flag=True, description_windows=None):
        if split not in ('train', 'valid', 'test'):
            raise ValueError('split must be train, valid, or test, got {}'.format(split))
        self.split = split
        self.args = args
        self.train_flag = split == 'train'
        self.sample_rate = args.sample_rate
        self.whole_file = split == 'test'

        root = os.path.join(args.data_folder, 'dataset', split)
        if not os.path.isdir(root):
            raise FileNotFoundError('Missing split directory {}'.format(root))
        if self.whole_file:
            self.audio_images = self._index_file_labels(root, print_flag)
            return

        desc_path = os.path.join(args.data_folder, 'audio_descriptions.jsonl')
        if description_windows is None:
            if not os.path.isfile(desc_path):
                raise FileNotFoundError('Missing {}'.format(desc_path))
            description_windows = _load_description_windows(desc_path)

        skipped = 0
        skipped_empty = 0
        skipped_no_event = 0
        items = []
        for name in sorted(os.listdir(root)):
            if not name.endswith('.wav'):
                continue
            windows = description_windows.get(name)
            if windows is None:
                skipped += 1
                continue
            if not windows:
                skipped_no_event += 1
                continue
            path = os.path.join(root, name)
            try:
                size = os.path.getsize(path)
            except OSError:
                skipped_empty += 1
                continue
            if size < MIN_WAV_BYTES:
                skipped_empty += 1
                continue
            patient_id = patient_id_from_name(name)
            for start_sec, end_sec, label, _clause in windows:
                items.append((path, int(label), 0, patient_id, float(start_sec), float(end_sec)))
        self.audio_images = items

        if print_flag:
            self._print_window_counts(split, items, skipped, skipped_no_event, skipped_empty)

    def _index_file_labels(self, root, print_flag):
        """One item per KAUH file whose sound code maps to a 4-class label."""
        skipped_unlabeled = 0
        skipped_bronchial = 0
        skipped_empty = 0
        items = []
        for name in sorted(os.listdir(root)):
            if not name.endswith('.wav'):
                continue
            label = kauh_file_label(name)
            if label is None:
                code = kauh_sound_code(name)
                if code is not None and code.lower() == 'bronchial':
                    skipped_bronchial += 1
                else:
                    skipped_unlabeled += 1
                continue
            path = os.path.join(root, name)
            try:
                size = os.path.getsize(path)
            except OSError:
                skipped_empty += 1
                continue
            if size < MIN_WAV_BYTES:
                skipped_empty += 1
                continue
            patient_id = patient_id_from_name(name)
            items.append((path, int(label), 0, patient_id, 0.0, 0.0))
        if print_flag:
            self._print_file_counts(items, skipped_unlabeled, skipped_bronchial, skipped_empty)
        return items

    @staticmethod
    def _print_class_counts(counts):
        total = max(int(counts.sum()), 1)
        for idx, class_name in enumerate(CLASS_NAMES):
            print('Class {} ({:<9}): {:<6} ({:.1f}%)'.format(
                idx, class_name, int(counts[idx]), 100.0 * counts[idx] / total))

    def _print_window_counts(self, split, items, skipped, skipped_no_event, skipped_empty):
        counts = np.zeros(4, dtype=np.int64)
        for item in items:
            counts[item[1]] += 1
        print('*' * 20)
        print('Resp-229K {} windows: {} (skipped no description {}, no timed event {}, empty {})'.format(
            split, len(items), skipped, skipped_no_event, skipped_empty))
        self._print_class_counts(counts)

    def _print_file_counts(self, items, skipped_unlabeled, skipped_bronchial, skipped_empty):
        counts = np.zeros(4, dtype=np.int64)
        for item in items:
            counts[item[1]] += 1
        print('*' * 20)
        print('Resp-229K test files: {} (skipped unlabeled {}, skipped bronchial {}, empty {})'.format(
            len(items), skipped_unlabeled, skipped_bronchial, skipped_empty))
        self._print_class_counts(counts)

    def __len__(self):
        return len(self.audio_images)

    def __getitem__(self, index):
        path, label, _device, patient_id, start_sec, end_sec = self.audio_images[index]
        if self.whole_file:
            wave = load_full(path, self.args)
        else:
            wave = load_window(path, self.args, start_sec, end_sec)
        return (
            wave,
            torch.tensor(label, dtype=torch.long),
            torch.tensor(patient_id, dtype=torch.long),
        )


def class_counts(dataset):
    counts = [0, 0, 0, 0]
    for item in dataset.audio_images:
        counts[int(item[1])] += 1
    return counts


def normal_fraction(dataset):
    counts = class_counts(dataset)
    total = sum(counts)
    if total <= 0:
        return 1.0
    return counts[0] / float(total)


def icbhi_prior_sampler(dataset, prior=ICBHI_TRAIN_PRIOR):
    """Draw training windows near the ICBHI cycle mix, with replacement."""
    labels = [int(item[1]) for item in dataset.audio_images]
    counts = [sum(1 for label in labels if label == cls) for cls in range(4)]
    active = [cls for cls in range(4) if counts[cls] > 0]
    if not active:
        raise ValueError('Resp-229K train split has no event windows')
    prior_mass = sum(prior[cls] for cls in active)
    class_weight = {
        cls: (prior[cls] / prior_mass) / counts[cls]
        for cls in active
    }
    weights = [class_weight[label] for label in labels]
    print('Resp-229K sampler prior (renormalized over classes present):')
    for cls in range(4):
        share = 0.0 if cls not in active else 100.0 * prior[cls] / prior_mass
        print('  {} count {} target {:.1f}%'.format(CLASS_NAMES[cls], counts[cls], share))
    return WeightedRandomSampler(weights, num_samples=len(labels), replacement=True)
