# -*- 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 SemanticSpecialistResidualMoE(SharedPrivateResidualMoE):
    """Suite7 backbone whose four residual expert slots are trained semantically.

    The inherited learned router is retained solely for checkpoint compatibility.
    Suite10 inference uses externally constructed semantic weights instead.
    """
    def forward(self,x,faculty_idx,q,semantic_weights:torch.Tensor|None=None):
        e=self.faculty_embedding(faculty_idx)
        h=self.encoder(torch.cat([x,e],dim=1))
        h_adapted,adapter_out=self.apply_faculty_adapters(h,faculty_idx)
        residuals=torch.stack([m(h_adapted) for m in self.experts],dim=1)
        learned_logits=self.router(h_adapted)/max(self.router_temperature,1e-6)
        learned_weights=torch.softmax(learned_logits,dim=1)
        weights=learned_weights if semantic_weights is None else semantic_weights
        correction=(weights[:,1:]*residuals).sum(dim=1)
        zq=logit_tensor(q); final_logit=zq+correction
        cf_logit=zq[:,None]+residuals
        return {
            'final_logit':final_logit,'final_prob':torch.sigmoid(final_logit),
            'weights':weights,'learned_router_weights':learned_weights,
            'residuals':residuals,'counterfactual_logit':cf_logit,
            'counterfactual_prob':torch.sigmoid(cf_logit),
            'shared_representation':h,'adapter_output':adapter_out,
            'adapted_representation':h_adapted,'representation':h_adapted,
            'correction':correction,
        }


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


def freeze_for_semantic_discovery(model:SemanticSpecialistResidualMoE):
    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 semantic_specialist_loss(output,y,domain_scores,magnitude_lambda=.01,domain_power=2.0,min_domain_weight=0.0):
    """Independent domain-weighted BCE for each residual expert.

    Domain scores never contain labels. Overlap is allowed: a row can train
    multiple experts. Each expert loss is normalized by its own responsibility
    mass, preventing large domains from dominating small ones by construction.
    """
    y=y.float(); m=torch.clamp(domain_scores.float(),0,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>0:total=total/active
    return {
        'total':total,
        'expert_prediction':torch.stack(losses),
        'magnitude':torch.stack(mags),
        'domain_mass':torch.stack(masses),
        'effective_domain_scores':m.detach(),
    }


def semantic_fusion(q,residuals,weights):
    q=torch.clamp(q,EPS,1-EPS)
    correction=(weights[:,1:]*residuals).sum(dim=1)
    final_logit=logit_tensor(q)+correction
    return torch.sigmoid(final_logit),correction


def shrink_reliability(local_reliability,local_support,global_reliability,shrink_rows=200.0):
    local=np.asarray(local_reliability,float);support=np.maximum(np.asarray(local_support,float),0)
    g=np.asarray(global_reliability,float)
    if local.ndim!=2 or support.shape!=local.shape:raise ValueError('local reliability/support must be F x K')
    if g.shape!=(local.shape[1],):raise ValueError('global reliability must have K entries')
    w=support/(support+max(float(shrink_rows),1e-8))
    out=w*local+(1-w)*g[None,:]
    return np.clip(np.nan_to_num(out,nan=0.0),0.0,1.0)


def structured_semantic_weights(
    domain_scores,faculty_idx,reliability,uncertainty,
    authority_min=.10,authority_max=.70,domain_floor=.10,
):
    """Build NULL + expert weights from semantic membership and reliability.

    Uncertainty affects only total specialist authority. It cannot change the
    relative composition among experts, satisfying Suite10's design constraint.
    """
    m=np.clip(np.asarray(domain_scores,float),0,1);f=np.asarray(faculty_idx,int);rho=np.clip(np.asarray(reliability,float),0,1);u=np.clip(np.asarray(uncertainty,float),0,1)
    if m.ndim!=2:raise ValueError('domain_scores must be N x K')
    if rho.ndim!=2 or rho.shape[1]!=m.shape[1]:raise ValueError('reliability must be F x K')
    if len(f)!=len(m) or len(u)!=len(m):raise ValueError('row arrays must align')
    if np.any(f<0) or np.any(f>=len(rho)):raise ValueError('faculty index out of range')
    eligible=np.where(m>=float(domain_floor),m,0.0)
    base=eligible*rho[f]
    base_sum=base.sum(axis=1)
    composition=np.divide(base,base_sum[:,None],out=np.zeros_like(base),where=base_sum[:,None]>EPS)
    domain_strength=np.max(eligible,axis=1) if m.shape[1] else np.zeros(len(m))
    reliability_strength=np.max(np.where(eligible>0,rho[f],0.0),axis=1) if m.shape[1] else np.zeros(len(m))
    cap=float(authority_min)+(float(authority_max)-float(authority_min))*u
    authority=np.clip(domain_strength*reliability_strength*cap,0.0,1.0)
    authority=np.where(base_sum>EPS,authority,0.0)
    weights=np.column_stack([1.0-authority,composition*authority[:,None]])
    weights=weights/np.maximum(weights.sum(axis=1,keepdims=True),EPS)
    return weights,{
        'authority':authority,'authority_cap':cap,'domain_strength':domain_strength,
        'reliability_strength':reliability_strength,'specialist_base_mass':base_sum,
        'expert_composition':composition,
    }
