# -*- coding: utf-8 -*-
from __future__ import annotations
import numpy as np
import torch
from torch.utils.data import Dataset
from suite24_graph_index import *

class EvidenceDataset(Dataset):
    def __init__(self,store,bundle,indices=None):
        self.store=store;self.bundle=bundle;self.indices=np.arange(len(bundle.y),dtype=np.int64) if indices is None else np.asarray(indices,np.int64)
    def __len__(self):return len(self.indices)
    def __getitem__(self,j):
        i=int(self.indices[j]);g=self.store[i]
        out={k:torch.from_numpy(np.asarray(v)) for k,v in g.items() if k!='chronology_violation'}
        out['y']=torch.tensor(float(self.bundle.y[i]),dtype=torch.float32);out['committee']=torch.tensor(float(self.bundle.committee[i]),dtype=torch.float32);out['faculty_idx']=torch.tensor(int(self.bundle.faculty_idx[i]),dtype=torch.long);out['bundle_index']=torch.tensor(i,dtype=torch.long)
        return out

class PerturbedEvidenceDataset(Dataset):
    def __init__(self,base,mode,source_index=None):self.base=base;self.mode=str(mode);self.source_index=None if source_index is None else np.asarray(source_index,np.int64)
    def __len__(self):return len(self.base)
    def __getitem__(self,j):
        a={k:(v.clone() if torch.is_tensor(v) else v) for k,v in self.base[j].items()}
        mode=self.mode
        if mode=='zero_history':
            for k in ['history_x','history_edge','history_rel','history_mask']:a[k]=torch.zeros_like(a[k])
            a['support'][0]=0;a['support'][2:5]=0
        elif mode=='zero_structural':
            for k in ['struct_x','struct_edge','struct_rel','struct_mask']:a[k]=torch.zeros_like(a[k])
            a['support'][1]=0;a['support'][5]=0
        elif mode in {'shuffle_history','shuffle_structural'}:
            if self.source_index is None:raise ValueError('source_index required')
            b=self.base[int(self.source_index[j])]
            if mode=='shuffle_history':
                for k in ['history_x','history_edge','history_rel','history_mask']:a[k]=b[k].clone()
                a['support'][0]=b['support'][0];a['support'][2:5]=b['support'][2:5]
            else:
                for k in ['struct_x','struct_edge','struct_rel','struct_mask']:a[k]=b[k].clone()
                a['support'][1]=b['support'][1];a['support'][5]=b['support'][5]
        return a

def same_faculty_permutation(bundle,seed,require_different_course=False):
    rng=np.random.default_rng(seed);out=np.arange(len(bundle.y),dtype=np.int64)
    for fi in range(len(bundle.faculty_names)):
        idx=np.where(bundle.faculty_idx==fi)[0]
        if len(idx)<=1:continue
        perm=idx.copy();rng.shuffle(perm)
        if require_different_course:
            # deterministic repair when a source carries the same target course.
            for k,i in enumerate(idx):
                if bundle.course_id[perm[k]]==bundle.course_id[i]:
                    cand=idx[bundle.course_id[idx]!=bundle.course_id[i]]
                    if len(cand):perm[k]=cand[(k+seed)%len(cand)]
        out[idx]=perm
    return out

def fit_stats(store,indices,max_rows=50000,seed=42):
    idx=np.asarray(indices,np.int64)
    if len(idx)>max_rows:
        rng=np.random.default_rng(seed);idx=np.sort(rng.choice(idx,size=max_rows,replace=False))
    sx=np.asarray(store.data['student_x'][idx],np.float32);cx=np.asarray(store.data['target_course_x'][idx],np.float32)
    h=np.asarray(store.data['history_x'][idx],np.float32);hm=np.asarray(store.data['history_mask'][idx],bool);st=np.asarray(store.data['struct_x'][idx],np.float32);sm=np.asarray(store.data['struct_mask'][idx],bool)
    course_parts=[cx]
    if hm.any():course_parts.append(h[hm])
    if sm.any():course_parts.append(st[sm])
    cc=np.concatenate(course_parts,axis=0);return sx.mean(0),sx.std(0)+1e-3,cc.mean(0),cc.std(0)+1e-3

def evidence_support_frame(store,bundle):
    s=np.asarray(store.data['support']);return {
      'history_courses':s[:,0],'structural_courses':s[:,1],'related_history':s[:,2],'same_course_history':s[:,3],'failed_history':s[:,4],'direct_structural':s[:,5],
      'max_edge_semester':np.asarray(store.data['max_edge_semester']), 'query_semester':np.asarray(bundle.target_semester), 'chronology_violation':np.asarray(store.data['chronology_violation'])}
