# -*- coding: utf-8 -*-
from __future__ import annotations
from pathlib import Path
import numpy as np
import pandas as pd

from suite7_reporting import load_shared_feature_schema, load_shared_fold_frame, merge_external_references, summarize_shared_router_frame


def load_suite7_fold_frame(suite7_results_dir,fold:int,faculty:str,expected_y,expected_committee,atol:float=1e-6)->pd.DataFrame:
    path=Path(suite7_results_dir)/f'fold_{int(fold)}'/f'{faculty}_scores.csv'
    if not path.exists():raise FileNotFoundError(f'missing Suite7 score file: {path}')
    df=pd.read_csv(path);required={'actual','committee','residual_moe_shared_private'};missing=sorted(required-set(df.columns))
    if missing:raise ValueError(f'Suite7 score file missing columns {missing}: {path}')
    y=np.asarray(expected_y,int);q=np.asarray(expected_committee,float)
    if len(df)!=len(y):raise ValueError(f'Suite7 score row alignment mismatch for {faculty} fold {fold}')
    if not np.array_equal(df.actual.to_numpy(int),y):raise ValueError(f'Suite7 label alignment mismatch for {faculty} fold {fold}')
    qq=df.committee.to_numpy(float)
    if not np.allclose(qq,q,atol=float(atol),rtol=1e-5):
        raise ValueError(f'Suite7 committee alignment mismatch for {faculty} fold {fold}; max_abs={float(np.max(np.abs(qq-q))):.3g}')
    return df


def _get(df,faculty,model,metric):
    d=df[(df.faculty==faculty)&(df.model==model)]
    if d.empty or metric not in d.columns:return np.nan
    return float(d.iloc[0][metric])


def _pref(a,b,tol=1e-6):
    if not np.isfinite(a) or not np.isfinite(b):return 'NA'
    if a-b>tol:return 'SPECIALIST'
    if a-b<-tol:return 'ADAPTER'
    return 'TIE'


def build_true_specialist_comparison(pooled,operational,specialist_model='residual_moe_true_specialist',adapter_model='residual_moe_shared_private',shared_model='residual_moe_shared',committee_model='committee'):
    po=operational[operational.fold.astype(str)=='POOLED'];fixed=po[po.policy=='fixed'];drift=po[po.policy=='drift'];rows=[]
    for faculty in sorted(pooled.faculty.unique()):
        models=[committee_model,shared_model,adapter_model,specialist_model]
        vals={m:{'ap':_get(pooled,faculty,m,'ap'),'auc':_get(pooled,faculty,m,'auc'),'f2':_get(pooled,faculty,m,'f2_at_20'),
                 'fixed':_get(fixed,faculty,m,'fbeta'),'drift':_get(drift,faculty,m,'fbeta')} for m in models}
        a=vals[adapter_model];s=vals[specialist_model]
        prefs=[_pref(s['ap'],a['ap']),_pref(s['f2'],a['f2']),_pref(s['drift'],a['drift'])]
        nv=sum(x=='SPECIALIST' for x in prefs);av=sum(x=='ADAPTER' for x in prefs)
        pattern='SPECIALIST_STRONGER' if nv>=2 else ('ADAPTER_STRONGER' if av>=2 else 'MIXED')
        r={'faculty':faculty}
        for model,short in [(committee_model,'committee'),(shared_model,'shared'),(adapter_model,'adapter'),(specialist_model,'specialist')]:
            for key in ['ap','auc','f2','fixed','drift']:
                name={'f2':'f2_20','fixed':'fixed_f2','drift':'drift_f2'}.get(key,key);r[f'{short}_{name}']=vals[model][key]
        r.update({'specialist_minus_adapter_ap':s['ap']-a['ap'],'specialist_minus_adapter_auc':s['auc']-a['auc'],
                  'specialist_minus_adapter_f2_20':s['f2']-a['f2'],'specialist_minus_adapter_fixed_f2':s['fixed']-a['fixed'],
                  'specialist_minus_adapter_drift_f2':s['drift']-a['drift'],
                  'specialist_minus_committee_ap':s['ap']-vals[committee_model]['ap'],
                  'specialist_minus_committee_f2_20':s['f2']-vals[committee_model]['f2'],
                  'ap_prefers':prefs[0],'f2_20_prefers':prefs[1],'drift_f2_prefers':prefs[2],'evidence_pattern':pattern})
        rows.append(r)
    return pd.DataFrame(rows)
