"""Ejemplo autocontenido de monitorización de embeddings; instala sentence-transformers y scipy."""
import numpy as np
from sentence_transformers import SentenceTransformer

MODEL='sentence-transformers/all-MiniLM-L6-v2'
REV='1110a243fdf4706b3f48f1d95db1a4f5529b4d41'
rng=np.random.default_rng(2026)
animals=['fox','otter','eagle','rabbit','bear','deer','wolf','badger','owl','whale','seal','tiger']
habitats=['forest','river','mountain','coast','valley','island','lake','desert','meadow','marsh','cave','tundra']
teams=['Falcons','Tigers','Wolves','Eagles','Bears','Lions','Sharks','Giants','Rockets','Waves','Stars','Ravens']
events=['match','final','tournament','season','league','cup','game','contest','round','fixture','playoff','qualifier']

def documents(topic, split):
    # Separate templates keep the learned direction from simply memorising a sentence.
    patterns = (['The {a} lives near the {b}.','Researchers observed a {a} in the {b}.'] if topic==0 else
                ['The {a} won the {b}.','Fans watched the {a} play in the {b}.'])
    if split=='eval':
        patterns = (['Near the {b}, a {a} was spotted.','A report describes a {a} inhabiting the {b}.'] if topic==0 else
                    ['In the {b}, the {a} played today.','A report describes the {a} competing in the {b}.'])
    left,right=(animals,habitats) if topic==0 else (teams,events)
    return [p.format(a=a,b=b) for p in patterns for a in left for b in right]

model=SentenceTransformer(MODEL,revision=REV,device='cuda')
groups=[documents(k,s) for s in ['train','eval'] for k in [0,1]]
emb=[model.encode(group,batch_size=64,normalize_embeddings=True,show_progress_bar=False) for group in groups]
train0,train1,source,target=emb
print('embeddings calculados',*[len(g) for g in groups],flush=True)
# Direction fitted only on independent templates. It is intentionally specific to
# this known topic contrast; the raw component retains sensitivity elsewhere.
direction=train1.mean(0)-train0.mean(0); direction/=np.linalg.norm(direction)
def feature(x, learned):
    return np.concatenate([x,2*(x@direction)[:,None]],axis=1) if learned else x

def distances(learned):
    z=feature(np.vstack([source,target]),learned);sq=(z*z).sum(1)
    return np.maximum(sq[:,None]+sq[None,:]-2*z@z.T,0)

def gram(d):
    # Fixed on reference only, never tuned using the evaluated window labels.
    ds=d[:48,:48]; s=max(np.median(ds[np.triu_indices(48,1)]),1e-9)
    return np.exp(-d/(2*s))

def mmd(K,a,b):
    aa=K[np.ix_(a,a)];bb=K[np.ix_(b,b)]
    return ((aa.sum()-np.trace(aa))/(len(a)*(len(a)-1))+
            (bb.sum()-np.trace(bb))/(len(b)*(len(b)-1))-2*K[np.ix_(a,b)].mean())

def trajectory(dist, shifted):
    # 48 fixed reference examples; 16 windows, each with 24 independently sampled
    # documents. The topic fraction rises gradually after the fourth window.
    ref=rng.integers(len(source),size=48)
    batches=[]; fractions=[]
    for t in range(16):
        q=max(0,(t-3)/12) if shifted else 0
        mask=rng.random(24)<q
        idx=rng.integers(len(source),size=24)
        batches.append(np.where(mask,idx+len(source),idx));fractions.append(q)
    ids=np.concatenate([ref,*batches]);K=gram(dist[np.ix_(ids,ids)])
    return np.array([mmd(K,np.arange(48),np.arange(48+24*t,48+24*(t+1))) for t in range(16)]),fractions

for learned in [False,True]:
    # Same random streams for both kernels: their detection times are paired.
    rng=np.random.default_rng(2026)
    dist=distances(learned)
    # Independent null traces calibrate the maximum over the entire horizon.
    pilot=np.array([trajectory(dist,False)[0] for _ in range(40)])
    center=float(pilot.mean()); drift=max(float(pilot.std())*.3,1e-8)
    null=np.array([trajectory(dist,False)[0] for _ in range(199)])
    def cusum(s):
        out=[]; value=0.
        for v in s:
            value=max(0.,value+v-center-drift);out.append(value)
        return np.array(out)
    null_max=null.max(axis=1); null_cus=np.array([cusum(row).max() for row in null])
    # Upper order statistic: rank 190 out of 199 for a 5% horizon-level test.
    threshold=np.sort(null_max)[189]; threshold_c=np.sort(null_cus)[189]
    observed,fractions=trajectory(dist,True); cs=cusum(observed)
    def first(mask):
        where=np.flatnonzero(mask); return int(where[0]+1) if len(where) else None
    print('kernel', 'aprendido' if learned else 'original')
    print('umbral de ventana',round(threshold,5),'umbral CUSUM',round(threshold_c,5))
    print('primera ventana MMD',first(observed>threshold),'CUSUM',first(cs>threshold_c))
    print('fracciones',np.round(fractions,2).tolist())
    print('MMD²',np.round(observed,4).tolist())
    print('CUSUM',np.round(cs,4).tolist())
