# -*- coding: utf-8 -*-
from __future__ import annotations
from dataclasses import dataclass
import numpy as np

@dataclass(frozen=True)
class TemporalWindow:
    index:int
    train_idx:np.ndarray
    val_idx:np.ndarray
    val_blocks:np.ndarray
    faculties:int
    failures:int
    rows:int

def _window_ok(idx,y,faculty,min_faculties,min_failures,min_rows):
    if len(idx)<int(min_rows): return False
    if int(np.sum(np.asarray(y)[idx]))<int(min_failures): return False
    return len(np.unique(np.asarray(faculty)[idx]))>=int(min_faculties)

def build_temporal_windows(blocks,y,faculty,n_windows=3,min_prior_blocks=4,min_faculties=8,min_failures=120,min_rows=5000):
    b=np.asarray(blocks,float); y=np.asarray(y); faculty=np.asarray(faculty)
    uniq=np.array(sorted(x for x in np.unique(b) if np.isfinite(x)),float)
    if len(uniq)<=int(min_prior_blocks): return []
    windows=[]; end=len(uniq)-1
    while end>=int(min_prior_blocks) and len(windows)<int(n_windows):
        start=end; chosen=None
        while start>=int(min_prior_blocks):
            vals=uniq[start:end+1]; vi=np.where(np.isin(b,vals))[0]; train=np.where(b<vals[0])[0]
            if len(np.unique(b[train]))>=int(min_prior_blocks) and _window_ok(vi,y,faculty,min_faculties,min_failures,min_rows):
                chosen=(start,vi,train,vals); break
            start-=1
        if chosen is None: break
        start,vi,train,vals=chosen
        windows.append(TemporalWindow(-1,train.astype(np.int64),vi.astype(np.int64),vals.copy(),len(np.unique(faculty[vi])),int(np.sum(y[vi])),len(vi)))
        end=start-1
    windows=list(reversed(windows))
    return [TemporalWindow(i,w.train_idx,w.val_idx,w.val_blocks,w.faculties,w.failures,w.rows) for i,w in enumerate(windows)]

def build_crossfit_windows(blocks,y,faculty,min_prior_blocks=4,min_faculties=8,min_failures=120,min_rows=5000):
    b=np.asarray(blocks,float); y=np.asarray(y); faculty=np.asarray(faculty)
    uniq=np.array(sorted(x for x in np.unique(b) if np.isfinite(x)),float)
    out=[]; start=int(min_prior_blocks)
    while start < len(uniq):
        end=start; emitted=False
        while end < len(uniq):
            vals=uniq[start:end+1]; vi=np.where(np.isin(b,vals))[0]; train=np.where(b<vals[0])[0]
            if _window_ok(vi,y,faculty,min_faculties,min_failures,min_rows):
                out.append(TemporalWindow(len(out),train.astype(np.int64),vi.astype(np.int64),vals.copy(),len(np.unique(faculty[vi])),int(np.sum(y[vi])),len(vi)))
                start=end+1; emitted=True; break
            end+=1
        if not emitted: break
    return out

def aggregate_window_stats(rows,recent_guard_windows=2,downside_penalty=0.5):
    if not rows:
        return {'mean_delta_ap':np.nan,'median_delta_ap':np.nan,'q25_delta_ap':np.nan,
                'recent_delta_ap':np.nan,'recent_median_delta_ap':np.nan,'recent_mean_delta_ap':np.nan,
                'worst_recent_window_mean_delta_ap':np.nan,'min_window_mean_delta_ap':np.nan,
                'win_rate':0.,'mean_delta_f1':np.nan,'mean_delta_f2':np.nan,'windows':0,'score':-np.inf}
    cells=[]; means=[]; meds=[]; f1=[]; f2=[]; wins=0; total=0
    for r in rows:
        ds=np.asarray(r.get('faculty_delta_ap',[]),float)
        if ds.size==0:
            # Backward-compatible path for synthetic/older callers.
            med=float(r.get('delta_ap',np.nan)); mean=float(r.get('delta_ap_mean',med)); fac=int(r.get('faculties',0)); w=int(r.get('wins',0))
            if np.isfinite(med): cells.append(med)
            meds.append(med);means.append(mean);total+=fac;wins+=w
        else:
            cells.extend(ds[np.isfinite(ds)].tolist());meds.append(float(np.nanmedian(ds)));means.append(float(np.nanmean(ds)));total+=len(ds);wins+=int(np.sum(ds>0))
        f1.append(float(r.get('delta_f1',0.)));f2.append(float(r.get('delta_f2',0.)))
    c=np.asarray(cells,float); c=c[np.isfinite(c)]
    if c.size==0:
        return {'mean_delta_ap':np.nan,'median_delta_ap':np.nan,'q25_delta_ap':np.nan,
                'recent_delta_ap':np.nan,'recent_median_delta_ap':np.nan,'recent_mean_delta_ap':np.nan,
                'worst_recent_window_mean_delta_ap':np.nan,'min_window_mean_delta_ap':np.nan,
                'win_rate':0.,'mean_delta_f1':np.nan,'mean_delta_f2':np.nan,'windows':len(rows),'score':-np.inf}
    mean=float(np.mean(c));med=float(np.median(c));q25=float(np.quantile(c,.25));recent_med=float(meds[-1]);recent_mean=float(means[-1]);k=max(1,int(recent_guard_windows));recent_means=np.asarray(means[-k:],float);worst=float(np.nanmin(recent_means));minmean=float(np.nanmin(np.asarray(means,float)));wr=float(wins/max(total,1))
    raw=.35*med+.35*mean+.20*q25+.10*recent_med
    penalty=float(downside_penalty)*max(0.,-worst)
    return {'mean_delta_ap':mean,'median_delta_ap':med,'q25_delta_ap':q25,
            'recent_delta_ap':recent_med,'recent_median_delta_ap':recent_med,'recent_mean_delta_ap':recent_mean,
            'worst_recent_window_mean_delta_ap':worst,'min_window_mean_delta_ap':minmean,
            'win_rate':wr,'mean_delta_f1':float(np.nanmean(f1)),'mean_delta_f2':float(np.nanmean(f2)),
            'windows':len(rows),'score':float(raw-penalty)}

def stage_admission(stats,min_mean_ap=.002,min_median_ap=0.,min_win_rate=.60,
                    min_recent_mean_ap=0.,min_recent_median_ap=0.,max_recent_window_mean_drop=-.003,
                    max_f1_drop=-.005,max_f2_drop=-.005):
    if int(stats.get('windows',0))==0:return False,'no_temporal_windows'
    if not np.isfinite(stats.get('mean_delta_ap',np.nan)) or stats['mean_delta_ap']<=float(min_mean_ap):return False,'mean_ap'
    if not np.isfinite(stats.get('median_delta_ap',np.nan)) or stats['median_delta_ap']<=float(min_median_ap):return False,'median_ap'
    if not np.isfinite(stats.get('recent_mean_delta_ap',np.nan)) or stats['recent_mean_delta_ap']<float(min_recent_mean_ap):return False,'recent_mean_ap'
    if not np.isfinite(stats.get('recent_median_delta_ap',np.nan)) or stats['recent_median_delta_ap']<=float(min_recent_median_ap):return False,'recent_median_ap'
    if stats.get('worst_recent_window_mean_delta_ap',np.inf)<float(max_recent_window_mean_drop):return False,'recent_window_downside'
    if stats['win_rate']<float(min_win_rate):return False,'faculty_win_rate'
    if stats.get('mean_delta_f1',0.)<float(max_f1_drop):return False,'f1_guard'
    if stats.get('mean_delta_f2',0.)<float(max_f2_drop):return False,'f2_guard'
    return True,'accepted'
