"""Four-class Shannon entropy used as a stage-2 BCE anchor."""

import torch

from method.feedback_decoder import (
    CONFUSED_ENTROPY,
    REASON_ENTROPY,
    REASON_WHEEZE,
    boundary_hinge,
    choose_entropy_anchor,
    cycle_decision,
    entropy_anchor_weights,
    entropy_class_report,
    four_class_entropy,
    four_class_probs,
    reason_targets_from_stats,
)


def test_uniform_four_class_entropy_exceeds_a_peaked_distribution():
    uniform = four_class_probs(torch.tensor([0.5]), torch.tensor([0.5]))
    peaked = four_class_probs(torch.tensor([0.99]), torch.tensor([0.01]))
    assert torch.allclose(uniform.sum(dim=-1), torch.ones(1))
    assert torch.allclose(uniform, torch.full((1, 4), 0.25))
    assert four_class_entropy(uniform).item() > four_class_entropy(peaked).item()


def test_constant_entropy_yields_weights_of_one():
    logit_c = torch.zeros(4, 6)
    logit_w = torch.ones(4, 6)
    weight = entropy_anchor_weights(logit_c, logit_w, mil_pool='topk', mil_topk=3)
    assert weight.shape == (4,)
    assert weight.grad_fn is None
    assert torch.allclose(weight, torch.ones(4))


def test_top_decile_enrichment_is_share_over_base_rate():
    labels = torch.tensor([3, 0, 0, 0, 0, 0, 0, 0, 0, 1])
    entropy = torch.tensor([5.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
    report = entropy_class_report(entropy, labels)
    assert report['n'] == 10
    assert report['top_k'] == 1
    assert report['top10_share']['both'] == 1.0
    assert report['base_rate']['both'] == 0.1
    assert report['enrichment']['both'] == 10.0
    assert report['enrichment']['crackle'] == 0.0


def test_gate_stops_when_neither_layer_is_enriched():
    flat = {'both': 1.0, 'crackle': 1.1}
    choice = choose_entropy_anchor(flat, {'both': 1.2, 'crackle': 1.0})
    assert choice['train'] is False
    assert choice['frame_layer'] == 11
    assert choice['slot_layer'] == 11


def test_gate_uses_layer_10_entropy_only_when_it_clears_the_margin():
    layer10 = {'both': 1.60, 'crackle': 1.00}
    layer11 = {'both': 1.30, 'crackle': 1.40}
    choice = choose_entropy_anchor(layer10, layer11)
    assert choice['train'] is True
    assert choice['entropy_layer'] == 10
    assert choice['frame_layer'] == 11

    close = choose_entropy_anchor({'both': 1.50, 'crackle': 1.00}, layer11)
    assert close['train'] is True
    assert close['entropy_layer'] == 11


def test_cycle_decision_reports_threshold_class_entropy_and_margin():
    decision = cycle_decision(
        torch.tensor([0.99, 0.50]),
        torch.tensor([0.01, 0.50]),
        tau_c=0.91, tau_w=0.75)
    assert decision['pred'].tolist() == [1, 0]
    assert decision['entropy'][0] < decision['entropy'][1]
    assert decision['margin'][0] > decision['margin'][1]
    assert decision['entropy'][1] >= CONFUSED_ENTROPY


def test_soft_handoff_does_not_harden_a_confused_wheeze_peak():
    stats = torch.zeros(1, 9)
    stats[0, 0] = 0.45
    stats[0, 1] = 0.55
    stats[0, 8] = 1.0
    hard = reason_targets_from_stats(stats, soft_handoff=False)
    soft = reason_targets_from_stats(stats, soft_handoff=True)
    assert int(hard[0]) == REASON_WHEEZE
    assert int(soft[0]) == REASON_ENTROPY


def test_soft_handoff_keeps_a_peaked_class_code():
    stats = torch.zeros(1, 9)
    stats[0, 0] = 0.05
    stats[0, 1] = 0.95
    stats[0, 8] = 1.0
    soft = reason_targets_from_stats(stats, soft_handoff=True)
    assert int(soft[0]) == REASON_WHEEZE


def test_boundary_hinge_pushes_near_threshold_crackle_and_ignores_saturated():
    # p=0.8 is inside [0.5, 0.91). p=0.99 is already past tau_c.
    logit_near = torch.tensor([0.8 / 0.2]).log().requires_grad_(True)
    logit_sat = torch.logit(torch.tensor([0.99])).requires_grad_(True)
    zero_w = torch.zeros(1)
    labels = torch.tensor([1])
    near = boundary_hinge(logit_near, zero_w, labels)
    sat = boundary_hinge(logit_sat, zero_w, labels)
    assert near.item() > 0.0
    assert sat.item() == 0.0
    near.backward()
    assert logit_near.grad.item() < 0.0


def test_boundary_hinge_pulls_down_overconfident_false_crackle():
    logit_c = torch.logit(torch.tensor([0.95])).requires_grad_(True)
    logit_w = torch.zeros(1)
    loss = boundary_hinge(logit_c, logit_w, torch.tensor([0]))
    assert loss.item() > 0.0
    loss.backward()
    assert logit_c.grad.item() > 0.0


def test_boundary_hinge_is_zero_on_a_confident_normal():
    logit_c = torch.logit(torch.tensor([0.05]))
    logit_w = torch.logit(torch.tensor([0.05]))
    loss = boundary_hinge(logit_c, logit_w, torch.tensor([0]))
    assert loss.item() == 0.0
