"""ICBHI evaluation metrics and threshold search helpers."""

import numpy as np

from util.icbhi_util import get_score

CLASS_NAMES = ['normal', 'crackle', 'wheeze', 'both']


def compute_class_metrics(labels, preds, n_cls=4, class_names=None):
    labels = [int(x) for x in labels]
    preds = [int(x) for x in preds]
    confusion = np.zeros((n_cls, n_cls), dtype=np.int64)
    counts = np.zeros(n_cls, dtype=np.float64)
    hits = np.zeros(n_cls, dtype=np.float64)

    for t, p in zip(labels, preds):
        confusion[t, p] += 1
        counts[t] += 1.0
        if t == p:
            hits[t] += 1.0

    recalls = []
    for c in range(n_cls):
        recalls.append(float(hits[c] / counts[c] * 100) if counts[c] > 0 else 0.0)

    names = class_names or CLASS_NAMES[:n_cls]
    per_class = {
        names[c]: {
            'count': int(counts[c]),
            'hits': int(hits[c]),
            'recall': recalls[c],
        }
        for c in range(n_cls)
    }
    sp, se, score, _ = get_score(hits.tolist(), counts.tolist())

    return {
        'per_class': per_class,
        'recalls': recalls,
        'confusion_matrix': confusion.tolist(),
        'abnormal_recalls': {
            'crackle': recalls[1] if n_cls > 1 else 0.0,
            'wheeze': recalls[2] if n_cls > 2 else 0.0,
            'both': recalls[3] if n_cls > 3 else 0.0,
        },
        'pooled_abnormal_recall': se,
        'sp': sp,
        'se': se,
        'score': score,
    }


def normal_wheeze_fp(confusion_matrix):
    if not confusion_matrix:
        return 0
    return int(confusion_matrix[0][2])


def aggregate_patient_predictions(patient_results):
    hits = [0.0] * 4
    counts = [0.0] * 4
    for data in patient_results.values():
        true_list = data['true']
        pred_list = data['pred']
        if not pred_list:
            continue
        vote = max(set(pred_list), key=pred_list.count)
        t = true_list[0]
        counts[t] += 1.0
        if vote == t:
            hits[t] += 1.0
    return hits, counts
