# -*- coding: utf-8 -*-
from __future__ import annotations
from itertools import combinations
from math import factorial
import numpy as np
from sklearn.metrics import average_precision_score,precision_recall_curve,roc_auc_score


def safe_ap(y,s):
    y=np.asarray(y,int);return float('nan') if np.unique(y).size<2 else float(average_precision_score(y,np.asarray(s,float)))

def safe_auc(y,s):
    y=np.asarray(y,int);return float('nan') if np.unique(y).size<2 else float(roc_auc_score(y,np.asarray(s,float)))

def exact_shapley(performance,views=('V1','V2','V3','V4')):
    views=tuple(views);k=len(views);out={v:0. for v in views}
    for v in views:
        others=[x for x in views if x!=v]
        for r in range(k):
            for s in combinations(others,r):
                s=tuple(x for x in views if x in s);sv=tuple(x for x in views if x in set(s)|{v});w=factorial(r)*factorial(k-r-1)/factorial(k);out[v]+=w*(float(performance[sv])-float(performance[s]))
    return out

def pairwise_synergy(performance,views=('V1','V2','V3','V4')):
    base=float(performance[()]);out={}
    for a,b in combinations(views,2):
        sa=(a,);sb=(b,);sab=tuple(v for v in views if v in {a,b});out[(a,b)]=float(performance[sab])-float(performance[sa])-float(performance[sb])+base
    return out

def absorption_index(committee_gain,e0_gain,eps=1e-8):
    if not np.isfinite(committee_gain) or abs(float(committee_gain))<=eps:return float('nan')
    return float(1-float(e0_gain)/float(committee_gain))

def cluster_bootstrap_delta_ap(y,base,candidate,clusters,reps=500,seed=0,return_cluster_draws=False):
    y=np.asarray(y,int);base=np.asarray(base,float);candidate=np.asarray(candidate,float);clusters=np.asarray(clusters).astype(str);uniq=np.unique(clusters);rng=np.random.default_rng(seed);samples=[];draws=[]
    index={u:np.where(clusters==u)[0] for u in uniq}
    for _ in range(int(reps)):
        draw=rng.choice(uniq,size=len(uniq),replace=True);idx=np.concatenate([index[u] for u in draw]);draws.append(draw.tolist())
        samples.append(safe_ap(y[idx],candidate[idx])-safe_ap(y[idx],base[idx]) if np.unique(y[idx]).size>1 else np.nan)
    a=np.asarray(samples,float);a=a[np.isfinite(a)]
    out={'mean':float(np.mean(a)) if len(a) else np.nan,'ci_low':float(np.quantile(a,.025)) if len(a) else np.nan,'ci_high':float(np.quantile(a,.975)) if len(a) else np.nan,'samples':samples}
    if return_cluster_draws:out['cluster_draws']=draws
    return out

def optimal_threshold_metrics(y,score,beta=1.):
    y=np.asarray(y,int);s=np.asarray(score,float)
    if np.unique(y).size<2:return {'threshold':.5,'precision':np.nan,'recall':np.nan,'f1':np.nan,'fbeta':np.nan,'tp':0,'fn':0,'fp':0,'tn':0}
    p,r,t=precision_recall_curve(y,s);bb=float(beta);fb=(1+bb*bb)*p*r/(bb*bb*p+r+1e-12);i=int(np.nanargmax(fb[:-1])) if len(t) else 0;thr=float(t[i]) if len(t) else .5;pred=s>=thr;tp=int(np.sum((y==1)&pred));fn=int(np.sum((y==1)&~pred));fp=int(np.sum((y==0)&pred));tn=int(np.sum((y==0)&~pred));pr=tp/max(tp+fp,1);re=tp/max(tp+fn,1);f1=2*pr*re/max(pr+re,1e-12);f=(1+bb*bb)*pr*re/max(bb*bb*pr+re,1e-12)
    return {'threshold':thr,'precision':float(pr),'recall':float(re),'f1':float(f1),'fbeta':float(f),'tp':tp,'fn':fn,'fp':fp,'tn':tn}

def apply_threshold_metrics(y,score,threshold,beta=2.):
    y=np.asarray(y,int);s=np.asarray(score,float);pred=s>=float(threshold);tp=int(np.sum((y==1)&pred));fn=int(np.sum((y==1)&~pred));fp=int(np.sum((y==0)&pred));tn=int(np.sum((y==0)&~pred));p=tp/max(tp+fp,1);r=tp/max(tp+fn,1);f1=2*p*r/max(p+r,1e-12);b=float(beta);fb=(1+b*b)*p*r/max(b*b*p+r,1e-12);return {'precision':p,'recall':r,'f1':f1,'fbeta':fb,'tp':tp,'fn':fn,'fp':fp,'tn':tn,'threshold':float(threshold)}

def classify_view_verdict(delta_ap,wins,total,ci_low=np.nan):
    frac=float(wins)/max(int(total),1);stable=not np.isfinite(ci_low) or ci_low>0
    if delta_ap>=.01 and frac>=.60 and stable:return 'STRONG_INCREMENTAL'
    if delta_ap>=.005 and frac>=.55 and stable:return 'MEANINGFUL_INCREMENTAL'
    return 'WEAK_OR_REDUNDANT'
