import sys
from pathlib import Path
import numpy as np

ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT))

from suite5_common import (
    boundary_context,
    failure_aware_utility,
    competence_sample_weights,
    mix_council,
    weight_diagnostics,
    align_expert_matrix,
    decision_change_diagnostics,
)


def test_failure_aware_utility_rewards_rescue_and_penalizes_lost_tp():
    # q warns rows 0 and 1 at 50% budget. Row2 is a missed failure.
    y=np.array([1,0,1,0])
    q=np.array([.90,.80,.40,.10])
    # specialist 1 rescues row2 and keeps row0; specialist 2 drops row0.
    s1=np.array([.85,.30,.95,.20])
    s2=np.array([.20,.85,.70,.10])
    E=np.column_stack([q,s1,s2])
    U,diag=failure_aware_utility(y,E,budget=.50)
    assert U.shape==(4,2)
    assert diag['rescues_by_expert'][0] >= 1
    assert diag['lost_tp_by_expert'][0] == 0
    assert diag['lost_tp_by_expert'][1] >= 1
    # Aggregate realized utility should prefer the rescuer.
    assert U[:,0].sum() > U[:,1].sum()


def test_boundary_context_marks_top_budget_and_nearness():
    q=np.array([.05,.10,.20,.30,.40,.50,.60,.70,.80,.90])
    E=np.column_stack([q,q[::-1],q])
    Z,names,ctx=boundary_context(E,budget=.20)
    assert Z.shape[0]==10
    assert 'committee_rank_pct' in names
    assert ctx['committee_warn'].sum()==2
    # .70 and .80 sit close to the 80th-percentile boundary compared with extremes.
    near=np.where(np.isclose(q,.70))[0][0]
    far=np.where(np.isclose(q,.05))[0][0]
    assert ctx['boundary_proximity'][near] > ctx['boundary_proximity'][far]


def test_competence_sample_weights_emphasize_failures_and_missed_failures():
    y=np.array([1,1,0,0,0])
    q=np.array([.95,.10,.90,.30,.20])
    E=np.column_stack([q,q,q])
    w,info=competence_sample_weights(y,E,budget=.40,positive_weight=3.0,rescue_weight=4.0)
    # row1 is positive and missed; row0 positive and already warned; normals lower.
    assert w[1] > w[0] > w[3]
    assert info['missed_failures']==1


def test_lower_temperature_increases_specialization_entropy_drops():
    E=np.array([[.2,.4,.6,.8],[.8,.6,.4,.2]])
    R=np.array([[0.1,0.2,0.3],[0.3,0.2,0.1]])
    _,w_hot=mix_council(E,R,alpha=1.0,temperature=2.0)
    _,w_cold=mix_council(E,R,alpha=1.0,temperature=.25)
    dh=weight_diagnostics(w_hot);dc=weight_diagnostics(w_cold)
    assert dc['mean_entropy'] < dh['mean_entropy']
    assert dc['mean_effective_experts'] < dh['mean_effective_experts']


def test_alpha_zero_is_exact_committee_fallback():
    rng=np.random.default_rng(3)
    E=rng.uniform(.01,.99,size=(20,4))
    R=rng.normal(size=(20,3))
    p,w=mix_council(E,R,alpha=0.0,temperature=.2)
    assert np.array_equal(p,E[:,0])
    assert w.shape==(20,4)


def test_alignment_preserves_committee_and_specialist_rank_order_with_ties():
    E=np.array([
        [.10,.4,.3,.7],
        [.20,.4,.1,.6],
        [.30,.8,.2,.5],
        [.40,.6,.4,.4],
    ])
    A=align_expert_matrix(E)
    assert np.array_equal(A[:,0],E[:,0])
    # tied specialist scores remain tied
    assert A[0,1]==A[1,1]
    # ordering of non-tied scores is preserved
    assert A[2,1] > A[3,1] > A[0,1]


def test_decision_change_diagnostics_balances_rescue_and_damage():
    y=np.array([1,1,0,0,0])
    q=np.array([.9,.3,.8,.2,.1])
    p=np.array([.8,.95,.2,.7,.1])
    d=decision_change_diagnostics(y,q,p,budget=.40)
    assert d['rescued_failures'] == 1
    assert d['lost_existing_tp'] == 0
    assert d['false_positives_removed'] == 1
    assert d['false_positives_added'] == 0


def test_policy_selection_rejects_catastrophic_sharp_candidate_and_prefers_smoother_tie():
    from suite5_common import choose_robust_candidate
    rows=[
        {'gate_mode':'committee','median_delta_ap':0.,'median_delta_f2':0.,'mean_delta_ap':0.,'mean_delta_f2':0.,'worst_delta_ap':0.,'worst_delta_f2':0.,'combined_win_rate':0.,'mean_effective_experts':4.0},
        {'gate_mode':'failure','name':'sharp_bad','median_delta_ap':.02,'median_delta_f2':.02,'mean_delta_ap':.02,'mean_delta_f2':.02,'worst_delta_ap':-.08,'worst_delta_f2':-.03,'combined_win_rate':.8,'mean_effective_experts':1.2},
        {'gate_mode':'failure','name':'smooth_good','median_delta_ap':.01,'median_delta_f2':.01,'mean_delta_ap':.01,'mean_delta_f2':.01,'worst_delta_ap':-.002,'worst_delta_f2':-.003,'combined_win_rate':.8,'mean_effective_experts':3.4},
        {'gate_mode':'failure','name':'sharp_same','median_delta_ap':.01,'median_delta_f2':.01,'mean_delta_ap':.01,'mean_delta_f2':.01,'worst_delta_ap':-.002,'worst_delta_f2':-.003,'combined_win_rate':.8,'mean_effective_experts':1.4},
    ]
    best=choose_robust_candidate(rows)
    assert best['name']=='smooth_good'
