"""Map a free-text respiratory description to the Frame ASD 4-class label.

0 normal, 1 crackle, 2 wheeze, 3 both.
A mention counts only when it is not inside a negation span.
"""

import re

# 0 normal, 1 crackle, 2 wheeze, 3 both.
_CLAUSE_SPLIT = re.compile(
    r'(?<=[.?;!])\s+|\bwhile\b|\bbut\b|\bhowever\b|,\s+with\b',
    re.IGNORECASE,
)

# Longer spans first so "no crackles or wheezes" does not leave a bare "wheezes".
# "crackle-free" and comma lists ("no crackles, wheezes, wheezing") must go first.
_NEG_SPANS = [
    r'\b(?:crackl\w*|wheez\w*)[\s-]+free\b',
    r'\b(?:no|without(?:\s+any)?|free\s+of(?:\s+any)?|absence\s+of|negative\s+for)\s+(?:crackl\w*|wheez\w*)(?:\s*(?:,\s*)?(?:or|and)?\s*(?:crackl\w*|wheez\w*))*',
    r'\bno\s+evidence\s+of\s+crackl\w*\s+or\s+wheez\w*',
    r'\bno\s+evidence\s+of\s+wheez\w*\s+or\s+crackl\w*',
    r'\bno\s+crackl\w*\s+or\s+wheez\w*',
    r'\bno\s+wheez\w*\s+or\s+crackl\w*',
    r'\bwithout\s+(?:any\s+)?crackl\w*\s+or\s+wheez\w*',
    r'\bwithout\s+(?:any\s+)?wheez\w*\s+or\s+crackl\w*',
    r'\bfree\s+of\s+crackl\w*\s+or\s+wheez\w*',
    r'\bfree\s+of\s+wheez\w*\s+or\s+crackl\w*',
    r'\babsence\s+of\s+crackl\w*\s+or\s+wheez\w*',
    r'\babsence\s+of\s+wheez\w*\s+or\s+crackl\w*',
    r'\bnegative\s+for\s+crackl\w*\s+or\s+wheez\w*',
    r'\bnegative\s+for\s+wheez\w*\s+or\s+crackl\w*',
    r'\bneither\s+crackl\w*\s+nor\s+wheez\w*',
    r'\bneither\s+wheez\w*\s+nor\s+crackl\w*',
    r'\bno\s+evidence\s+of\s+crackl\w*',
    r'\bno\s+evidence\s+of\s+wheez\w*',
    r'\bno\s+history\s+of\s+crackl\w*',
    r'\bno\s+history\s+of\s+wheez\w*',
    r'\bwithout\s+(?:a\s+)?history\s+of\s+crackl\w*',
    r'\bwithout\s+(?:a\s+)?history\s+of\s+wheez\w*',
    r'\bno\s+significant\s+crackl\w*',
    r'\bno\s+significant\s+wheez\w*',
    r'\bno\s+crackl\w*',
    r'\bno\s+wheez\w*',
    r'\bwithout\s+(?:any\s+)?crackl\w*',
    r'\bwithout\s+(?:any\s+)?wheez\w*',
    r'\bfree\s+of\s+(?:any\s+)?crackl\w*',
    r'\bfree\s+of\s+(?:any\s+)?wheez\w*',
    r'\babsence\s+of\s+crackl\w*',
    r'\babsence\s+of\s+wheez\w*',
    r'\bnegative\s+for\s+crackl\w*',
    r'\bnegative\s+for\s+wheez\w*',
    r'\bcrackl\w*\s+(?:were|was)\s+not\s+detected\b',
    r'\bwheez\w*\s+(?:were|was)\s+not\s+detected\b',
    r'\bnot\s+detected\b(?:\s+\w+){0,5}\s+crackl\w*',
    r'\bnot\s+detected\b(?:\s+\w+){0,5}\s+wheez\w*',
]
_NEG_RES = [re.compile(p, re.IGNORECASE) for p in _NEG_SPANS]
_CRACKLE = re.compile(r'crackl', re.IGNORECASE)
_WHEEZE = re.compile(r'wheez', re.IGNORECASE)
# "1.144s to 14.716s", "from 1.036s to 2.364s", "between 18.78s and 19.696s", "0.364–3.25s".
_TIME_SPAN = re.compile(
    r'(\d+(?:\.\d+)?)\s*s?\s*(?:to|and|[-–—])\s*(\d+(?:\.\d+)?)\s*s\b',
    re.IGNORECASE,
)
_MIN_WINDOW_SEC = 0.05


def _clauses(text):
    parts = _CLAUSE_SPLIT.split(text)
    return [p for p in parts if p and p.strip()]


def _strip_negation(clause):
    cleaned = clause
    for pattern in _NEG_RES:
        cleaned = pattern.sub(' ', cleaned)
    return cleaned


def _clause_label(clause):
    """0/1/2/3 for one clause after negation spans are removed."""
    kept = _strip_negation(clause)
    crackle = _CRACKLE.search(kept) is not None
    wheeze = _WHEEZE.search(kept) is not None
    if crackle and wheeze:
        return 3
    if crackle:
        return 1
    if wheeze:
        return 2
    return 0


def description_to_label(text):
    """Return 0/1/2/3 from one audio description. Empty text is normal."""
    if not text:
        return 0
    crackle = False
    wheeze = False
    for clause in _clauses(text):
        label = _clause_label(clause)
        crackle = crackle or label in (1, 3)
        wheeze = wheeze or label in (2, 3)
    if crackle and wheeze:
        return 3
    if crackle:
        return 1
    if wheeze:
        return 2
    return 0


def description_to_windows(text):
    """One window per timed span. Clauses without a start and end in seconds are dropped.

    Each item is (start_sec, end_sec, label, clause). The label is the clause
    label, so a negated span stays normal and a later positive span stays abnormal.
    """
    if not text:
        return []
    grouped = {}
    order = []
    for clause in _clauses(text):
        label = _clause_label(clause)
        clause = clause.strip()
        for match in _TIME_SPAN.finditer(clause):
            start = float(match.group(1))
            end = float(match.group(2))
            if end < start + _MIN_WINDOW_SEC or start < 0:
                continue
            key = (round(start, 3), round(end, 3))
            if key not in grouped:
                grouped[key] = [int(label), clause]
                order.append(key)
                continue
            # Same cycle cited twice (crackle in one clause, wheeze in another) is both.
            grouped[key][0] = _merge_labels(grouped[key][0], int(label))
    return [(key[0], key[1], grouped[key][0], grouped[key][1]) for key in order]


def _merge_labels(left, right):
    crackle = left in (1, 3) or right in (1, 3)
    wheeze = left in (2, 3) or right in (2, 3)
    if crackle and wheeze:
        return 3
    if crackle:
        return 1
    if wheeze:
        return 2
    return 0


def patient_id_from_name(filename):
    """ICBHI names start with a numeric patient id. Other names use 0."""
    head = filename.split('_', 1)[0]
    if head.isdigit():
        return int(head)
    return 0


# Second comma field of a KAUH name, e.g. BP101_Asthma,E W,P L M,12,F.wav.
_KAUH_SOUND_LABELS = {
    'n': 0,
    'c': 1,
    'crep': 1,
    'e w': 2,
    'i e w': 2,
}


def kauh_sound_code(filename):
    """Sound field from a KAUH filename, or None when the name has no such field."""
    stem = filename[:-4] if filename.lower().endswith('.wav') else filename
    parts = stem.split(',')
    if len(parts) < 2:
        return None
    code = parts[1].strip()
    if not code:
        return None
    return code


def kauh_file_label(filename):
    """File-level 4-class label from a KAUH sound code.

    N is normal, C and Crep are crackle, E W and I E W are wheeze.
    Bronchial, COUGHVID UUIDs, and any other name return None and stay out of Score.
    """
    code = kauh_sound_code(filename)
    if code is None:
        return None
    return _KAUH_SOUND_LABELS.get(code.lower())
