import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))

import numpy as np


def test_quantile_alignment_preserves_order_and_reference_distribution():
    from suite3_common import quantile_align_to_reference
    source = np.array([0.9, 0.1, 0.7, 0.4, 0.2])
    reference = np.array([0.01, 0.03, 0.08, 0.20, 0.70])
    aligned = quantile_align_to_reference(source, reference)
    assert np.array_equal(np.argsort(source, kind='mergesort'), np.argsort(aligned, kind='mergesort'))
    assert np.allclose(np.sort(aligned), np.sort(reference))


def test_blockwise_alignment_does_not_mix_blocks():
    from suite3_common import blockwise_quantile_align
    source = np.array([.9,.8,.1, .9,.8,.1])
    reference = np.array([.01,.02,.03, .7,.8,.9])
    blocks = np.array([1,1,1, 2,2,2])
    out = blockwise_quantile_align(source, reference, blocks)
    assert np.allclose(np.sort(out[:3]), np.sort(reference[:3]))
    assert np.allclose(np.sort(out[3:]), np.sort(reference[3:]))
    assert out[:3].max() < out[3:].min()


def test_composite_is_convex_and_relational_only_changes_rich_rows():
    from suite3_common import apply_composite
    q = np.array([.1,.2,.3,.4])
    a1 = np.array([.2,.3,.4,.5])
    recent = np.array([.3,.4,.5,.6])
    rel = np.array([.9,.9,.9,.9])
    rich = np.array([False, False, True, True])
    base, final = apply_composite(q,a1,recent,rel,rich,w_a1=.25,w_recent=.25,rel_alpha=.4)
    expected = .5*q + .25*a1 + .25*recent
    assert np.allclose(base, expected)
    assert np.allclose(final[~rich], expected[~rich])
    assert np.all(final[rich] > expected[rich])
    assert np.all((final >= 0) & (final <= 1))


def test_weight_grid_is_convex_and_contains_committee():
    from suite3_common import fusion_grid
    grid = fusion_grid([0,.25,.5,1], [0,.1,.3])
    assert any(r['w_a1']==0 and r['w_recent']==0 and r['rel_alpha']==0 for r in grid)
    for r in grid:
        assert r['w_a1'] >= 0 and r['w_recent'] >= 0
        assert r['w_a1'] + r['w_recent'] <= 1 + 1e-12
        assert 0 <= r['rel_alpha'] <= 1


def test_robust_selector_falls_back_when_every_candidate_hurts():
    from suite3_common import select_robust_weights
    y = np.array([0,1,0,1, 0,1,0,1])
    blocks = np.array([1,1,1,1,2,2,2,2])
    q = np.array([.1,.9,.2,.8, .1,.9,.2,.8])
    # Reverse both auxiliary rankings so any nonzero use is bad.
    bad = 1-q
    rich = np.ones(len(y), bool)
    selected, rows = select_robust_weights(y, blocks, q, bad, bad, bad, rich,
                                           weight_values=[0,.5,1], rel_values=[0,.5],
                                           min_median_delta_ap=0.001, min_win_rate=.6,
                                           worst_delta_ap=-.005)
    assert selected['w_a1'] == 0
    assert selected['w_recent'] == 0
    assert selected['rel_alpha'] == 0
    assert selected['reason'].startswith('committee_fallback')


def test_window_indices_use_only_prior_blocks_and_latest_k():
    from suite3_common import window_indices_before_block
    blocks = np.array([1,1,2,2,3,3,4,4], float)
    all_idx = window_indices_before_block(blocks, 4, None)
    last2 = window_indices_before_block(blocks, 4, 2)
    assert set(all_idx.tolist()) == {0,1,2,3,4,5}
    assert set(last2.tolist()) == {2,3,4,5}


def test_frozen_policy_evaluation_uses_supplied_threshold():
    from suite3_common import evaluate_fixed_threshold
    y=np.array([0,0,1,1])
    p=np.array([.1,.4,.6,.9])
    m=evaluate_fixed_threshold(y,p,threshold=.5,beta=2.)
    assert m['tp']==2 and m['fp']==0 and m['fn']==0 and m['tn']==2
    m2=evaluate_fixed_threshold(y,p,threshold=.8,beta=2.)
    assert m2['tp']==1 and m2['fn']==1


def test_decision_policy_writer_does_not_shadow_pandas(tmp_path):
    import train_v3 as core
    from train_suite3 import FoldRecord, _evaluate_decision_policy
    y=np.array([0,0,1,1,0,1])
    q=np.array([.1,.2,.7,.8,.3,.9])
    r=FoldRecord(1,y,q,q,q,q,q,q,q,q,q,q)
    pol=core.tune_threshold(y,q,None,None,2.,.0,3.0,1,False)
    _evaluate_decision_policy([r],[],pol,tmp_path,'fac')
    assert (tmp_path/'fac_threshold_policy.csv').exists()
    assert (tmp_path/'fac_warning_metrics.csv').exists()


def test_quantile_alignment_preserves_ties():
    from suite3_common import quantile_align_to_reference
    s=np.array([.1,.1,.5,.9,.9])
    q=np.array([.01,.02,.1,.2,.8])
    a=quantile_align_to_reference(s,q)
    assert a[0] == a[1]
    assert a[3] == a[4]
    assert a[0] < a[2] < a[3]
