# -*- coding: utf-8 -*-
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import gc
import numpy as np
import torch
from torch.utils.data import Dataset
from suite23_graph_index import *

class GraphDataset(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 not in {'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 PerturbedGraphDataset(Dataset):
    def __init__(self,base,mode,source_index=None):
        self.base=base;self.mode=mode;self.source_index=np.asarray(source_index,np.int64) if source_index is not None else None
    def __len__(self):return len(self.base)
    @staticmethod
    def _touching(a,slots):
        src=a['edge_src'].cpu().numpy();dst=a['edge_dst'].cpu().numpy();mask=a['edge_mask'].cpu().numpy().astype(bool)
        return [q for q,(x,y,m) in enumerate(zip(src,dst,mask)) if m and (int(x) in slots or int(y) in slots)]
    @staticmethod
    def _replace_edge_subset(a,b,slots):
        ia=PerturbedGraphDataset._touching(a,slots);ib=PerturbedGraphDataset._touching(b,slots)
        # Remove the target evidence first, then insert the source evidence in any free edge slots.
        if ia:a['edge_mask'][torch.as_tensor(ia,dtype=torch.long)]=False
        free=torch.where(~a['edge_mask'])[0].cpu().numpy().tolist()
        if len(ib)>len(free):raise RuntimeError('perturbation edge capacity exhausted')
        for qa,qb in zip(free,ib):
            a['edge_src'][qa]=b['edge_src'][qb];a['edge_dst'][qa]=b['edge_dst'][qb];a['edge_type'][qa]=b['edge_type'][qb];a['edge_attr'][qa]=b['edge_attr'][qb];a['edge_mask'][qa]=b['edge_mask'][qb]
    def __getitem__(self,j):
        a=self.base[j]
        # clone every tensor that a perturbation may mutate
        for k in ['node_x','node_type','node_mask','node_entity','edge_src','edge_dst','edge_type','edge_attr','edge_mask','support']:
            a[k]=a[k].clone()
        if self.mode.startswith('shuffle'):
            if self.source_index is None:raise ValueError('shuffle perturbation needs source_index')
            b=self.base[int(self.source_index[j])]
        else:b=None
        if self.mode in {'zero_history','shuffle_history'}:
            slots=set(range(SL_HISTORY.start,SL_HISTORY.stop))
            if b is None:
                a['node_x'][SL_HISTORY]=0;a['node_type'][SL_HISTORY]=0;a['node_mask'][SL_HISTORY]=False;a['node_entity'][SL_HISTORY]=-1
                ia=self._touching(a,slots)
                if ia:a['edge_mask'][torch.as_tensor(ia,dtype=torch.long)]=False
                a['support'][0]=0
            else:
                a['node_x'][SL_HISTORY]=b['node_x'][SL_HISTORY];a['node_type'][SL_HISTORY]=b['node_type'][SL_HISTORY];a['node_mask'][SL_HISTORY]=b['node_mask'][SL_HISTORY];a['node_entity'][SL_HISTORY]=b['node_entity'][SL_HISTORY]
                self._replace_edge_subset(a,b,slots);a['support'][0]=b['support'][0]
        if self.mode in {'zero_cohort','shuffle_cohort'}:
            slots=set(range(SL_COHORT.start,SL_COHORT.stop))
            if b is None:
                a['node_x'][SL_COHORT]=0;a['node_type'][SL_COHORT]=0;a['node_mask'][SL_COHORT]=False;a['node_entity'][SL_COHORT]=-1
                ia=self._touching(a,slots)
                if ia:a['edge_mask'][torch.as_tensor(ia,dtype=torch.long)]=False
                a['support'][1]=0
            else:
                a['node_x'][SL_COHORT]=b['node_x'][SL_COHORT];a['node_type'][SL_COHORT]=b['node_type'][SL_COHORT];a['node_mask'][SL_COHORT]=b['node_mask'][SL_COHORT];a['node_entity'][SL_COHORT]=b['node_entity'][SL_COHORT]
                self._replace_edge_subset(a,b,slots);a['support'][1]=b['support'][1]
        return a


def same_faculty_permutation(bundle,seed=42):
    rng=np.random.default_rng(seed);p=np.arange(len(bundle.y))
    for f in np.unique(bundle.faculty_idx):
        idx=np.where(bundle.faculty_idx==f)[0];q=idx.copy();rng.shuffle(q)
        if len(idx)>1 and np.any(q==idx):q=np.roll(q,1)
        p[idx]=q
    return p


def same_faculty_course_permutation(bundle,seed=42):
    """Shuffle student-history evidence while preserving faculty and target course when possible."""
    rng=np.random.default_rng(seed);p=np.arange(len(bundle.y));assigned=np.zeros(len(bundle.y),bool)
    courses=np.asarray(bundle.course_id,dtype=object);fac=np.asarray(bundle.faculty_idx,int)
    for f in np.unique(fac):
        fm=np.where(fac==f)[0]
        for c in np.unique(courses[fm]):
            idx=fm[courses[fm]==c]
            if len(idx)<2:continue
            q=idx.copy();rng.shuffle(q)
            if np.any(q==idx):q=np.roll(q,1)
            p[idx]=q;assigned[idx]=True
        # fallback for singleton course groups: same faculty
        rem=fm[~assigned[fm]]
        if len(rem)>1:
            q=rem.copy();rng.shuffle(q)
            if np.any(q==rem):q=np.roll(q,1)
            p[rem]=q
    return p


def fit_node_stats(store,indices,max_rows=50000,seed=42):
    rng=np.random.default_rng(seed);idx=np.asarray(indices,np.int64)
    if len(idx)>max_rows:idx=rng.choice(idx,size=max_rows,replace=False)
    sums=np.zeros((5,NODE_RAW_DIM),np.float64);sq=np.zeros_like(sums);cnt=np.zeros(5,np.int64)
    for i in idx:
        x=np.asarray(store.data['node_x'][i],np.float32);t=np.asarray(store.data['node_type'][i],int);m=np.asarray(store.data['node_mask'][i],bool)
        for typ in range(1,5):
            z=x[m&(t==typ)]
            if len(z):sums[typ]+=z.sum(0);sq[typ]+=(z*z).sum(0);cnt[typ]+=len(z)
    mean=np.zeros_like(sums,np.float32);std=np.ones_like(sums,np.float32)
    for typ in range(1,5):
        if cnt[typ]:mean[typ]=sums[typ]/cnt[typ];v=sq[typ]/cnt[typ]-mean[typ]**2;std[typ]=np.sqrt(np.maximum(v,1e-6))
    return mean,std,cnt


def graph_support_frame(store,bundle):
    s=np.asarray(store.data['support']);return {'faculty_idx':bundle.faculty_idx,'history_courses':s[:,0],'cohort_students':s[:,1],'structural_courses':s[:,2],'curriculum_groups':s[:,3],'chronology_violation':store.data['chronology_violation'],'max_edge_semester':store.data['max_edge_semester'],'target_semester':bundle.target_semester}
