"""Window labels follow the clause that contains the time span."""

import numpy as np
import pytest
import torch

from method.frame_asd import mil_pool_logits
from util.desc_labels import description_to_label, description_to_windows, kauh_file_label
from util.resp_dataset import Resp229KDataset, collate_padded_waves, load_window


COPD_HEAD = (
    "Respiratory sounds were assessed at the anterior left recording location "
    "using the AKG C417L microphone. No crackles or wheezes were detected in "
    "the first six cycles (1.144s to 14.716s), while crackles were present in "
    "the final cycle (17.571s to 19.975s)."
)

WHEEZE_LIST = (
    "The respiratory sounds were recorded bilaterally from the posterior right lung. "
    "Wheezes were detected in several cycles, including from 1.036s to 2.364s, "
    "2.364s to 3.693s, and 5.121s to 6.621s."
)

BETWEEN_NORMAL = (
    "Crackles were present from 0.292s to 18.78s, with no wheezes detected during "
    "these intervals. A brief period of no crackles or wheezes was noted between "
    "18.78s and 19.696s."
)

NO_TIME = (
    "The trachea recording revealed no crackles or wheezes in cycles 1, 3, and 4, "
    "with crackles present in cycle 2 and wheezes in cycles 5."
)

ENDASH = "Crackles were present in cycles 0.364–3.25s and 6.636–11.179s."


def _pairs(text):
    return [(round(s, 3), round(e, 3), lab) for s, e, lab, _ in description_to_windows(text)]


def test_copd_head_is_normal_and_late_cycle_is_crackle():
    assert _pairs(COPD_HEAD) == [
        (1.144, 14.716, 0),
        (17.571, 19.975, 1),
    ]
    assert description_to_label(COPD_HEAD) == 1


def test_wheeze_list_keeps_each_cycle():
    assert _pairs(WHEEZE_LIST) == [
        (1.036, 2.364, 2),
        (2.364, 3.693, 2),
        (5.121, 6.621, 2),
    ]


def test_between_span_stays_normal_when_negated():
    assert _pairs(BETWEEN_NORMAL) == [
        (0.292, 18.78, 1),
        (18.78, 19.696, 0),
    ]


def test_cycle_numbers_without_seconds_are_dropped():
    assert description_to_windows(NO_TIME) == []
    assert description_to_windows('') == []
    assert description_to_windows(
        'Cough from a female patient in her 40s, who is a non-smoker.'
    ) == []


def test_endash_spans():
    assert _pairs(ENDASH) == [
        (0.364, 3.25, 1),
        (6.636, 11.179, 1),
    ]


def test_both_in_one_clause():
    text = 'Both crackles and wheezes were heard from 1.0s to 3.5s.'
    assert _pairs(text) == [(1.0, 3.5, 3)]


def test_crackle_free_span_is_normal():
    text = (
        'The respiratory sounds show a normal crackle-free and wheeze-free pattern '
        'during the first cycle (3.464s to 5.868s). Wheezes are present in cycles '
        '2 through 5 (5.868s to 17.186s), while the final cycle (17.186s to 19.959s) '
        'returns to normal without crackles or wheezes.'
    )
    assert _pairs(text) == [
        (3.464, 5.868, 0),
        (5.868, 17.186, 2),
        (17.186, 19.959, 0),
    ]


def test_negated_comma_list_is_normal():
    text = (
        'Each of the eight cycles analyzed—ranging from 0.036s to 19.936s—showed '
        'no crackles, wheezes, wheezing, crackling, or crackles.'
    )
    assert _pairs(text) == [(0.036, 19.936, 0)]


def test_same_span_crackle_and_wheeze_merges_to_both():
    text = (
        "Crackles in cycles 0.522s to 3.264s, 3.264s to 5.45s, and 5.45s to 8.493s, "
        "with wheezes present in the cycle from 3.264s to 5.45s. "
        "No crackles or wheezes were detected in cycles from 8.493s to 10.793s."
    )
    assert _pairs(text) == [
        (0.522, 3.264, 1),
        (3.264, 5.45, 3),
        (5.45, 8.493, 1),
        (8.493, 10.793, 0),
    ]


def test_inverted_span_is_dropped():
    text = 'Crackles from 5s to 1s were noted.'
    assert description_to_windows(text) == []


def test_load_window_reads_the_event_not_the_file_head(tmp_path):
    sr = 16000
    audio = np.zeros(10 * sr, dtype=np.float32)
    audio[int(8.0 * sr)] = 1.0
    path = tmp_path / 'event.wav'
    import wave
    pcm = (audio * 32767.0).astype(np.int16)
    with wave.open(str(path), 'wb') as handle:
        handle.setnchannels(1)
        handle.setsampwidth(2)
        handle.setframerate(sr)
        handle.writeframes(pcm.tobytes())
    args = type('A', (), {'sample_rate': sr, 'desired_length': 5, 'pad_types': 'repeat'})()
    event = load_window(str(path), args, 7.5, 8.5)
    head = load_window(str(path), args, 0.0, 5.0)
    assert event.shape == (5 * sr,)
    assert float(event[int(0.5 * sr)]) > 0.5
    assert float(torch.abs(head).max()) < 1e-4


def test_kauh_file_label_maps_sound_codes():
    assert kauh_file_label('BP100_N,N,P R M,70,F.wav') == 0
    assert kauh_file_label('BP18_pneumonia,C,P R U,57,M.wav') == 1
    assert kauh_file_label('DP36_pneumonia,Crep,P R M,36,F.wav') == 1
    assert kauh_file_label('BP101_Asthma,E W,P L M,12,F.wav') == 2
    assert kauh_file_label('BP1_Asthma,I E W,P L L,70,M.wav') == 2
    assert kauh_file_label('BP69_pneumonia,Bronchial,P R L ,64,M.wav') is None
    assert kauh_file_label('bcd05117-c0f9-46da-93a3-4107a1cc9dfa.wav') is None


def _write_wav(path, n_samples, sr=16000):
    import wave
    pcm = np.zeros(n_samples, dtype=np.int16)
    pcm[0] = 1000
    with wave.open(str(path), 'wb') as handle:
        handle.setnchannels(1)
        handle.setsampwidth(2)
        handle.setframerate(sr)
        handle.writeframes(pcm.tobytes())


def test_resp_test_split_keeps_labeled_kauh_files(tmp_path):
    root = tmp_path / 'dataset' / 'test'
    root.mkdir(parents=True)
    sr = 16000
    names = [
        'BP100_N,N,P R M,70,F.wav',
        'BP101_Asthma,E W,P L M,12,F.wav',
        'bcd05117-c0f9-46da-93a3-4107a1cc9dfa.wav',
        'BP69_pneumonia,Bronchial,P R L ,64,M.wav',
    ]
    for name in names:
        _write_wav(root / name, sr)
    args = type('A', (), {
        'data_folder': str(tmp_path),
        'sample_rate': sr,
        'desired_length': 5,
        'pad_types': 'repeat',
    })()
    dataset = Resp229KDataset('test', args, print_flag=False)
    assert len(dataset) == 2
    labels = sorted(item[1] for item in dataset.audio_images)
    assert labels == [0, 2]
    wave, label, _patient = dataset[0]
    assert wave.shape == (sr,)
    assert int(label) in (0, 2)


def test_collate_padded_waves_marks_the_tail():
    batch = [
        (torch.ones(4), torch.tensor(0), torch.tensor(1)),
        (torch.arange(2).float(), torch.tensor(2), torch.tensor(3)),
    ]
    waves, labels, patients, mask = collate_padded_waves(batch)
    assert waves.shape == (2, 4)
    assert labels.tolist() == [0, 2]
    assert patients.tolist() == [1, 3]
    assert mask[0].tolist() == [False, False, False, False]
    assert mask[1].tolist() == [False, False, True, True]
    assert waves[1, 2:].tolist() == [0.0, 0.0]


def test_mil_pool_ignores_padded_frame_even_with_energy_mask():
    logits = torch.tensor([[0.2, 8.0]])
    padding_mask = torch.tensor([[False, True]])
    energy_mask = torch.tensor([[True, True]])
    pooled = mil_pool_logits(logits, padding_mask=padding_mask)
    pooled_energy = mil_pool_logits(
        logits, energy_mask=energy_mask, padding_mask=padding_mask)
    pooled_topk = mil_pool_logits(
        logits, mode='topk', topk=1, energy_mask=energy_mask, padding_mask=padding_mask)
    assert float(pooled) == pytest.approx(0.2)
    assert float(pooled_energy) == pytest.approx(0.2)
    assert float(pooled_topk) == pytest.approx(0.2)
