from pathlib import Path
import json
import numpy as np
import pandas as pd
import pytest

from suite7_reporting import (
    load_shared_feature_schema,
    load_shared_fold_frame,
    build_shared_private_comparison,
)


def test_load_shared_schema_and_frame_alignment(tmp_path: Path):
    fold_dir=tmp_path/'fold_6'
    fold_dir.mkdir()
    (fold_dir/'feature_schema.json').write_text(json.dumps({
        'common_raw_features':['a','b'],
        'faculties':['fac_a','fac_b'],
    }))
    pd.DataFrame({
        'actual':[0,1],
        'committee':[0.1,0.8],
        'residual_moe_shared':[0.2,0.7],
    }).to_csv(fold_dir/'fac_a_scores.csv',index=False)
    schema=load_shared_feature_schema(tmp_path,6)
    assert schema['common_raw_features']==['a','b']
    df=load_shared_fold_frame(tmp_path,6,'fac_a',np.array([0,1]),np.array([0.1,0.8]))
    assert np.allclose(df['residual_moe_shared'],[0.2,0.7])


def test_shared_frame_rejects_committee_misalignment(tmp_path: Path):
    fold_dir=tmp_path/'fold_6';fold_dir.mkdir()
    (fold_dir/'feature_schema.json').write_text(json.dumps({'common_raw_features':['a']}))
    pd.DataFrame({'actual':[0],'committee':[0.2],'residual_moe_shared':[0.3]}).to_csv(fold_dir/'fac_scores.csv',index=False)
    with pytest.raises(ValueError,match='committee alignment mismatch'):
        load_shared_fold_frame(tmp_path,6,'fac',np.array([0]),np.array([0.1]))


def test_build_shared_private_comparison_has_expected_deltas():
    pooled=pd.DataFrame([
        {'faculty':'f','model':'committee','ap':.20,'auc':.70,'f2_at_20':.30},
        {'faculty':'f','model':'residual_moe_shared','ap':.25,'auc':.72,'f2_at_20':.32},
        {'faculty':'f','model':'residual_moe_shared_private','ap':.28,'auc':.75,'f2_at_20':.36},
    ])
    ops=pd.DataFrame([
        {'faculty':'f','model':'committee','fold':'POOLED','policy':'fixed','fbeta':.31,'precision':.2,'recall':.4,'f1':.27,'flag_rate':.1},
        {'faculty':'f','model':'residual_moe_shared','fold':'POOLED','policy':'fixed','fbeta':.33,'precision':.2,'recall':.45,'f1':.28,'flag_rate':.11},
        {'faculty':'f','model':'residual_moe_shared_private','fold':'POOLED','policy':'fixed','fbeta':.37,'precision':.22,'recall':.49,'f1':.30,'flag_rate':.12},
        {'faculty':'f','model':'committee','fold':'POOLED','policy':'drift','fbeta':.30,'precision':.2,'recall':.38,'f1':.26,'flag_rate':.09},
        {'faculty':'f','model':'residual_moe_shared','fold':'POOLED','policy':'drift','fbeta':.34,'precision':.21,'recall':.44,'f1':.28,'flag_rate':.10},
        {'faculty':'f','model':'residual_moe_shared_private','fold':'POOLED','policy':'drift','fbeta':.39,'precision':.23,'recall':.50,'f1':.31,'flag_rate':.11},
    ])
    out=build_shared_private_comparison(pooled,ops)
    r=out.iloc[0]
    assert np.isclose(r['private_minus_shared_ap'],.03)
    assert np.isclose(r['private_minus_shared_f2_20'],.04)
    assert np.isclose(r['private_minus_shared_drift_f2'],.05)
    assert r['evidence_pattern']=='ADAPTER_STRONGER'
