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

EPS=1e-6

@dataclass
class DenseStandardizer:
    mean_: np.ndarray
    scale_: np.ndarray
    @classmethod
    def fit(cls,x):
        x=np.asarray(x,np.float32); x=np.nan_to_num(x)
        m=x.mean(0); s=x.std(0); s=np.where(s<EPS,1.0,s)
        return cls(m.astype(np.float32),s.astype(np.float32))
    def transform(self,x):
        x=np.nan_to_num(np.asarray(x,np.float32))
        return ((x-self.mean_)/self.scale_).astype(np.float32)

@dataclass
class MaskedStandardizer:
    mean_: np.ndarray
    scale_: np.ndarray
    @classmethod
    def fit(cls,x,mask):
        x=np.asarray(x,np.float32); mask=np.asarray(mask,bool)
        if x.ndim<2 or x.shape[:-1]!=mask.shape: raise ValueError('mask shape mismatch')
        vals=x[mask]
        if len(vals)==0:
            m=np.zeros(x.shape[-1],np.float32); s=np.ones(x.shape[-1],np.float32)
        else:
            vals=np.nan_to_num(vals);m=vals.mean(0);s=vals.std(0);s=np.where(s<EPS,1.0,s)
        return cls(m.astype(np.float32),s.astype(np.float32))
    def transform(self,x,mask):
        x=np.nan_to_num(np.asarray(x,np.float32)); mask=np.asarray(mask,bool)
        y=((x-self.mean_)/self.scale_).astype(np.float32)
        y[~mask]=0.0
        return y

@dataclass
class Suite12Bundle:
    flat: np.ndarray
    e0_context: np.ndarray
    fusion_context: np.ndarray
    e1_context: np.ndarray
    e2_context: np.ndarray
    e3_context: np.ndarray
    e4_context: np.ndarray
    y: np.ndarray
    teacher: np.ndarray
    faculty_idx: np.ndarray
    blocks: np.ndarray
    row_index: np.ndarray
    faculty_names: list[str]
    student_seq: np.ndarray
    student_mask: np.ndarray
    course_target: np.ndarray
    course_neighbors: np.ndarray
    course_neighbor_mask: np.ndarray
    course_relation_type: np.ndarray
    relation_events: np.ndarray
    relation_mask: np.ndarray
    relation_type: np.ndarray
    component_events: np.ndarray
    component_mask: np.ndarray
    component_type: np.ndarray

    def subset(self,mask):
        m=np.asarray(mask,bool);kw={}
        for k,v in self.__dict__.items():
            if isinstance(v,np.ndarray) and len(v)==len(m): kw[k]=v[m]
            else: kw[k]=v
        return Suite12Bundle(**kw)

@dataclass
class Suite12Standardizers:
    flat: DenseStandardizer
    e0_context: DenseStandardizer
    fusion_context: DenseStandardizer
    e1_context: DenseStandardizer
    e2_context: DenseStandardizer
    e3_context: DenseStandardizer
    e4_context: DenseStandardizer
    student: MaskedStandardizer
    course: DenseStandardizer
    relation: MaskedStandardizer
    component: MaskedStandardizer
    @classmethod
    def fit(cls,bundle:Suite12Bundle,mask):
        m=np.asarray(mask,bool)
        cn=bundle.course_neighbors[m];cm=bundle.course_neighbor_mask[m]
        ct=bundle.course_target[m][:,None,:];ctm=np.ones((len(ct),1),bool)
        allc=np.concatenate([ct,cn],1);allm=np.concatenate([ctm,cm],1);vals=allc[allm]
        cstd=DenseStandardizer.fit(vals if len(vals) else np.zeros((1,allc.shape[-1]),np.float32))
        return cls(
            DenseStandardizer.fit(bundle.flat[m]),
            DenseStandardizer.fit(bundle.e0_context[m]),DenseStandardizer.fit(bundle.fusion_context[m]),DenseStandardizer.fit(bundle.e1_context[m]),DenseStandardizer.fit(bundle.e2_context[m]),DenseStandardizer.fit(bundle.e3_context[m]),DenseStandardizer.fit(bundle.e4_context[m]),
            MaskedStandardizer.fit(bundle.student_seq[m],bundle.student_mask[m]),cstd,
            MaskedStandardizer.fit(bundle.relation_events[m],bundle.relation_mask[m]),
            MaskedStandardizer.fit(bundle.component_events[m],bundle.component_mask[m]))
    def transform(self,b:Suite12Bundle)->Suite12Bundle:
        return Suite12Bundle(
            flat=self.flat.transform(b.flat),e0_context=self.e0_context.transform(b.e0_context),fusion_context=self.fusion_context.transform(b.fusion_context),e1_context=self.e1_context.transform(b.e1_context),e2_context=self.e2_context.transform(b.e2_context),e3_context=self.e3_context.transform(b.e3_context),e4_context=self.e4_context.transform(b.e4_context),
            y=b.y,teacher=b.teacher,faculty_idx=b.faculty_idx,blocks=b.blocks,row_index=b.row_index,faculty_names=b.faculty_names,
            student_seq=self.student.transform(b.student_seq,b.student_mask),student_mask=b.student_mask,
            course_target=self.course.transform(b.course_target),course_neighbors=self.course.transform(b.course_neighbors),course_neighbor_mask=b.course_neighbor_mask,course_relation_type=b.course_relation_type,
            relation_events=self.relation.transform(b.relation_events,b.relation_mask),relation_mask=b.relation_mask,relation_type=b.relation_type,
            component_events=self.component.transform(b.component_events,b.component_mask),component_mask=b.component_mask,component_type=b.component_type,
        )
