# -*- coding: utf-8 -*-
from __future__ import annotations
from pathlib import Path
from typing import Sequence
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F

from suite7_shared_private_moe import SharedPrivateResidualMoE, logit_tensor

EPS=1e-7


class OpportunityRouter(nn.Module):
    def __init__(self,input_dim,n_domains=4,hidden=128,dropout=.10):
        super().__init__();h=int(hidden);self.net=nn.Sequential(nn.Linear(int(input_dim),h),nn.GELU(),nn.LayerNorm(h),nn.Dropout(float(dropout)),nn.Linear(h,max(32,h//2)),nn.GELU(),nn.Dropout(float(dropout)),nn.Linear(max(32,h//2),int(n_domains)+1))
    def forward(self,x):return self.net(x)


class LatentOpportunityResidualMoE(SharedPrivateResidualMoE):
    """Suite7 backbone with residual experts trained on discovered latent opportunity domains.

    The inherited Suite7 router remains checkpoint-compatible but Suite11 inference uses the
    separately trained OpportunityRouter, because the latter predicts fixed latent-domain labels.
    """
    def forward(self,x,faculty_idx,q,weights=None):
        e=self.faculty_embedding(faculty_idx);h=self.encoder(torch.cat([x,e],dim=1));ha,adapter_out=self.apply_faculty_adapters(h,faculty_idx)
        residuals=torch.stack([m(ha) for m in self.experts],dim=1);zq=logit_tensor(q);cf=zq[:,None]+residuals
        if weights is None:
            learned=torch.softmax(self.router(ha)/max(self.router_temperature,1e-6),dim=1);weights=learned
        else:learned=torch.softmax(self.router(ha)/max(self.router_temperature,1e-6),dim=1)
        corr=(weights[:,1:]*residuals).sum(dim=1);fl=zq+corr
        return {'final_logit':fl,'final_prob':torch.sigmoid(fl),'weights':weights,'suite7_router_weights':learned,'residuals':residuals,
                'counterfactual_logit':cf,'counterfactual_prob':torch.sigmoid(cf),'shared_representation':h,'adapter_output':adapter_out,
                'adapted_representation':ha,'representation':ha,'correction':corr}


def load_suite7_initialization(model,checkpoint_path:str|Path,expected_faculties:Sequence[str]|None=None):
    ck=torch.load(Path(checkpoint_path),map_location='cpu',weights_only=False);fac=list(ck.get('faculties',[]))
    if expected_faculties is not None and fac and list(expected_faculties)!=fac:raise ValueError(f'Suite7 checkpoint faculty ordering mismatch: expected={list(expected_faculties)} checkpoint={fac}')
    r=model.load_state_dict(ck['state_dict'],strict=True)
    if r.missing_keys or r.unexpected_keys:raise RuntimeError(f'incompatible Suite7 checkpoint: missing={r.missing_keys} unexpected={r.unexpected_keys}')
    return {'selected_epoch':ck.get('selected_epoch'),'model_config':ck.get('model_config',{}),'faculties':fac}


def freeze_for_latent_specialists(model):
    for p in model.parameters():p.requires_grad=False
    for expert in model.experts:
        for p in expert.parameters():p.requires_grad=True
    return [p for p in model.parameters() if p.requires_grad]


def latent_specialist_loss(output,y,responsibilities,magnitude_lambda=.01,domain_power=1.0,min_domain_weight=0.0):
    y=y.float();resp=torch.clamp(responsibilities.float(),0,1)
    if resp.shape[1]!=output['counterfactual_logit'].shape[1]+1:raise ValueError('responsibilities must be NULL + K experts')
    m=resp[:,1:]
    if float(domain_power)!=1.0:m=m.pow(float(domain_power))
    if float(min_domain_weight)>0:m=torch.where(m>=float(min_domain_weight),m,torch.zeros_like(m))
    yy=y[:,None].expand_as(output['counterfactual_logit']);lk=F.binary_cross_entropy_with_logits(output['counterfactual_logit'],yy,reduction='none')
    losses=[];mags=[];masses=[];total=torch.zeros((),device=lk.device,dtype=lk.dtype);active=0
    for k in range(lk.shape[1]):
        wk=m[:,k];mass=wk.sum();masses.append(mass.detach())
        if float(mass.detach().cpu())<=1e-8:
            losses.append(torch.zeros((),device=lk.device,dtype=lk.dtype));mags.append(torch.zeros((),device=lk.device,dtype=lk.dtype));continue
        pred=(wk*lk[:,k]).sum()/mass;mag=(wk*output['residuals'][:,k].pow(2)).sum()/mass;losses.append(pred);mags.append(mag);total=total+pred+float(magnitude_lambda)*mag;active+=1
    if active:total=total/active
    return {'total':total,'expert_prediction':torch.stack(losses),'magnitude':torch.stack(mags),'domain_mass':torch.stack(masses),'effective_responsibility':m.detach()}


def authority_adjusted_weights(router_prob,alpha=1.0):
    p=np.asarray(router_prob,float)
    if p.ndim!=2 or p.shape[1]<2:raise ValueError('router_prob must be N x (K+1)')
    p=np.clip(p,0,1);p=p/np.maximum(p.sum(axis=1,keepdims=True),EPS);a=float(np.clip(alpha,0,1));nonnull=p[:,1:]*a;null=1.0-nonnull.sum(axis=1);w=np.column_stack([null,nonnull]);return w/np.maximum(w.sum(axis=1,keepdims=True),EPS)


def fuse_numpy(q,residuals,weights):
    q=np.clip(np.asarray(q,float),EPS,1-EPS);r=np.asarray(residuals,float);w=np.asarray(weights,float);corr=(w[:,1:]*r).sum(axis=1);z=np.log(q/(1-q))+corr;z=np.clip(z,-30,30);return 1/(1+np.exp(-z)),corr
