"""Toy zero-training transfer, v2: facet-overlap world + donor-free closed-form imprint.

World: entities with 8 independent latent 'facets' z. A relation reads one or two
facets: answer = argmax(z[dims] @ W_r) over 10 values. Donor A is trained on the
relations inside its facet set FA, recipient B on relations inside FB; |FA|=|FB|=4,
|FA & FB| = k (the overlap we sweep). Same entities, same world, different views.

Model (both): one-hot entity -> embedding e (d) -> enrichment MLP u=relu(e W_in+b)
(width f) -> key h = u W_down + b (no skip, so entity identity must pass through the MLP) -> readout relu(h W2 + Rel[r] + b2) W3.
The enrichment block depends only on the entity, like subject-token MLPs in an LLM.

Transfer: Procrustes (+scale) on anchor entities' keys; swap the mapped donor key into
B (donor plugged in), or imprint it into B's W_down in closed form with null-space
protection of background entities (donor unplugged). 'Shared-subspace' variants only
move B's key inside the subspace the two models actually share.
"""
import numpy as np, json, sys, itertools, time

D_Z, N_VAL = 8, 10

def relations():
    rels = [(i,) for i in range(D_Z)] + list(itertools.combinations(range(D_Z), 2))
    return rels

def make_world(seed, n_ent):
    rng = np.random.default_rng(10_000 + seed)
    z = rng.standard_normal((n_ent, D_Z))
    rels = relations()
    W = [rng.standard_normal((len(r), N_VAL)) for r in rels]
    Y = np.stack([(z[:, list(r)] @ W[j]).argmax(1) for j, r in enumerate(rels)], 1)  # (ent, rel)
    return z, rels, Y

def facet_sets(k):
    FA = [0, 1, 2, 3]
    FB = list(range(4 - k, 8 - k))
    return FA, FB

class Net:
    def __init__(s, seed, n_ent, n_rel, d, f, fr=256, de=None, b0=0.0, l1=0.0):
        de = de or d; s.l1 = l1; s.freeze = set()
        rng = np.random.default_rng(seed)
        g = lambda a, b: rng.standard_normal((a, b)) / np.sqrt(a)
        s.p = dict(E=rng.standard_normal((n_ent, de)) * .5, Win=g(de, f), bin=np.full(f, float(b0)),
                   Wd=g(f, d), bd=np.zeros(d), W2=g(d, fr), Rel=rng.standard_normal((n_rel, fr)) * .3,
                   b2=np.zeros(fr), W3=g(fr, N_VAL), b3=np.zeros(N_VAL))
    def enrich(s, ents=None):
        e = s.p['E'] if ents is None else s.p['E'][ents]
        u = np.maximum(e @ s.p['Win'] + s.p['bin'], 0)
        return e, u, u @ s.p['Wd'] + s.p['bd']
    def key(s, ents=None):
        return s.enrich(ents)[2]
    def logits(s, H, R):
        m = np.maximum(H @ s.p['W2'] + s.p['Rel'][R] + s.p['b2'], 0)
        return m @ s.p['W3'] + s.p['b3']
    def predict(s, I, R, Hall=None):
        Hall = s.key() if Hall is None else Hall
        return s.logits(Hall[I], R).argmax(1)
    def train(s, I, R, Y, steps=1500, lr=1e-2, wd=1e-4):
        p = s.p; m1 = {k: 0 for k in p}; m2 = {k: 0 for k in p}; n = len(I)
        for t in range(1, steps + 1):
            e, u, H = s.enrich()
            h = H[I]; a2 = h @ p['W2'] + p['Rel'][R] + p['b2']; m = np.maximum(a2, 0)
            lo = m @ p['W3'] + p['b3']; lo -= lo.max(1, keepdims=True)
            pr = np.exp(lo); pr /= pr.sum(1, keepdims=True); pr[np.arange(n), Y] -= 1; d = pr / n
            G = {'W3': m.T @ d, 'b3': d.sum(0)}
            dm = d @ p['W3'].T * (a2 > 0)
            G['W2'] = h.T @ dm; G['b2'] = dm.sum(0)
            G['Rel'] = np.zeros_like(p['Rel']); np.add.at(G['Rel'], R, dm)
            dh = dm @ p['W2'].T
            dH = np.zeros_like(H); np.add.at(dH, I, dh)
            G['Wd'] = u.T @ dH; G['bd'] = dH.sum(0)
            du = (dH @ p['Wd'].T + s.l1 * len(u) ** -1) * (u > 0)
            G['Win'] = e.T @ du; G['bin'] = du.sum(0)
            G['E'] = du @ p['Win'].T
            for k in p:
                if k in s.freeze: continue
                g = G[k] + wd * p[k]
                m1[k] = .9 * m1[k] + .1 * g; m2[k] = .999 * m2[k] + .001 * g * g
                p[k] -= lr * (m1[k] / (1 - .9 ** t)) / (np.sqrt(m2[k] / (1 - .999 ** t)) + 1e-8)

def procrustes(X, Y):
    mx, my = X.mean(0), Y.mean(0); Xc, Yc = X - mx, Y - my
    U, S, Vt = np.linalg.svd(Xc.T @ Yc, full_matrices=False)
    R = U @ Vt; sc = np.linalg.norm(Yc) / np.linalg.norm(Xc @ R)
    return dict(mx=mx, my=my, R=R, s=sc, S=S, Vt=Vt)

def apply_map(M, X):
    return M['my'] + M['s'] * (X - M['mx']) @ M['R']

def shared_projector(XA, XB, tau=0.6):
    """Projector (in B's key space) onto directions B shares with A: canonical
    directions of the anchor keys with canonical correlation > tau."""
    Xc, Yc = XA - XA.mean(0), XB - XB.mean(0)
    def white(Z):
        U, S, Vt = np.linalg.svd(Z, full_matrices=False)
        keep = S > S[0] * 1e-3
        return U[:, keep], Vt[keep], S[keep]
    Ua, _, _ = white(Xc); Ub, Vb, Sb = white(Yc)
    _, rho, Qt = np.linalg.svd(Ua.T @ Ub, full_matrices=False)
    Qk = Qt[rho > tau]                        # canonical directions in B's whitened coords
    dirs = (Qk / Sb) @ Vb if len(Qk) else np.zeros((0, XB.shape[1]))   # B key-space directions (rows)
    if len(dirs) == 0:
        return np.zeros((XB.shape[1], XB.shape[1])), rho
    Qd, _ = np.linalg.qr(dirs.T)              # orthonormal basis of the shared subspace
    return Qd @ Qd.T, rho

def shared_projector_cca(XA, XB, tau=0.5, eps=0.1):
    """B-space projector onto canonical directions (ridge-regularised CCA) whose
    canonical correlation with A exceeds tau. Returns P (d_B x d_B), applied as delta @ P,
    with P = V V^T C_B (oblique, in B's covariance metric)."""
    Ac, Bc = XA - XA.mean(0), XB - XB.mean(0); n = len(Ac)
    Ca, Cb, Cab = Ac.T @ Ac / n, Bc.T @ Bc / n, Ac.T @ Bc / n
    Ca = Ca + eps * np.trace(Ca) / len(Ca) * np.eye(len(Ca)); Cbr = Cb + eps * np.trace(Cb) / len(Cb) * np.eye(len(Cb))
    def isqrt(C):
        w, V = np.linalg.eigh(C); return V @ np.diag(w ** -.5) @ V.T
    Ia, Ib = isqrt(Ca), isqrt(Cbr)
    U, rho, Wt = np.linalg.svd(Ia @ Cab @ Ib, full_matrices=False)
    V = Ib @ Wt[rho > tau].T                     # canonical weight vectors in B space (cols)
    V = V / np.sqrt(np.einsum('ij,ik,kj->j', V, Cb, V))  # normalise V^T Cb V = I (diag)
    return V @ V.T @ Cb, rho

def cka(X, Y):
    Xc, Yc = X - X.mean(0), Y - Y.mean(0)
    return np.linalg.norm(Xc.T @ Yc) ** 2 / (np.linalg.norm(Xc.T @ Xc) * np.linalg.norm(Yc.T @ Yc))

def imprint(B, ents, targets, bg_ents, lam, mu_rel=1e-8):
    """Closed-form null-space edit of B.Wd: for edited entities, e + u (Wd+dW) = target;
    keep u_bg dW ~ 0 for background entities. Woodbury / push-through form."""
    e, u, H = B.enrich()
    Ue, Ub = u[ents], u[bg_ents]
    Rgap = targets - H[ents]
    A = np.vstack([Ue, np.sqrt(lam) * Ub / np.sqrt(len(bg_ents))])
    G = A @ A.T; mu = mu_rel * np.trace(G) / len(G)
    rhs = np.vstack([Rgap, np.zeros((len(bg_ents), Rgap.shape[1]))])
    beta = np.linalg.lstsq(G + mu * np.eye(len(G)), rhs, rcond=1e-10)[0]
    return A.T @ beta                          # dW (f x d)

def run(seed, k, n_ent=400, n_held=100, dA=48, dB=64, fA=512, fB=1024, deB=256, freezeE=True, n_seen=3,
        lams=(10.0, 100.0, 1000.0), taus=(0.5,), steps=1500, export=False):
    t0 = time.time()
    z, rels, Y = make_world(seed, n_ent)
    FA, FB = facet_sets(k)
    rA = [j for j, r in enumerate(rels) if set(r) <= set(FA)]
    rB = [j for j, r in enumerate(rels) if set(r) <= set(FB)]
    shared_f = set(FA) & set(FB)
    cat = {j: ('shared' if set(rels[j]) <= shared_f else 'partial' if set(rels[j]) & shared_f else 'unshared') for j in rB}
    rng = np.random.default_rng(seed)
    held = np.arange(n_ent - n_held, n_ent); anchors = np.arange(n_ent - n_held)
    # donor: all entities x its relations
    IA, RA = [a.ravel() for a in np.meshgrid(np.arange(n_ent), rA, indexing='ij')]
    A = Net(100 + seed, n_ent, len(rels), dA, fA); A.train(IA, RA, Y[IA, RA], steps=steps)
    # recipient: anchors x all its relations; held entities x n_seen random relations
    IB, RB = [a.ravel() for a in np.meshgrid(np.arange(n_ent), rB, indexing='ij')]
    seen = np.ones(len(IB), bool)
    for i in held:
        idx = np.where(IB == i)[0]; keep = rng.choice(idx, n_seen, replace=False)
        seen[np.setdiff1d(idx, keep)] = False
    B = Net(200 + seed, n_ent, len(rels), dB, fB, de=deB)
    if freezeE: B.freeze = {'E'}; B.p['E'] *= 2.0 / np.sqrt(deB) / .5
    B.train(IB[seen], RB[seen], Y[IB[seen], RB[seen]], steps=steps)
    HA, HB = A.key(), B.key()
    tI, tR = IB[~seen], RB[~seen]; ty = Y[tI, tR]
    tcat = np.array([cat[r] for r in tR])
    b_pred0 = B.predict(tI, tR)
    miss = b_pred0 != ty
    # donor 'knows' is only defined where A has the relation (shared category)
    a_has = np.isin(tR, rA)
    a_ok = np.zeros(len(tI), bool); a_ok[a_has] = A.predict(tI[a_has], tR[a_has]) == ty[a_has]
    known_I, known_R = IB[seen], RB[seen]; known_y = Y[known_I, known_R]
    known_ok0 = B.predict(known_I, known_R) == known_y
    M = procrustes(HA[anchors], HB[anchors])
    P, rho = shared_projector_cca(HA[anchors], HB[anchors], taus[0])
    out = dict(seed=seed, k=k, FA=FA, FB=FB, cka=float(cka(HA[anchors], HB[anchors])),
               canon_corr=[round(float(x), 3) for x in rho[:12]], shared_dim=int((rho > taus[0]).sum()),
               A_train=float((A.predict(IA, RA) == Y[IA, RA]).mean()), B_train=float(known_ok0.mean()),
               B_test_acc=float((~miss).mean()), n_test=int(len(tI)),
               n_miss={c: int((miss & (tcat == c)).sum()) for c in ['shared', 'partial', 'unshared']})
    def score(Hnew, name):
        pred = B.predict(tI, tR, Hnew); ok = pred == ty
        res = {}
        for c in ['shared', 'partial', 'unshared']:
            msk = miss & (tcat == c)
            res[c] = float(ok[msk].mean()) if msk.any() else None
            # also: test facts B already got right (does the transfer break them?)
            msk2 = (~miss) & (tcat == c)
            res[c + '_keptright'] = float(ok[msk2].mean()) if msk2.any() else None
        msk = miss & (tcat == 'shared') & a_ok
        res['shared_donorknows'] = float(ok[msk].mean()) if msk.any() else None
        kp = B.predict(known_I, known_R, Hnew) == known_y
        hk = np.isin(known_I, held)
        res['retain_other'] = float((kp & known_ok0)[~hk].sum() / known_ok0[~hk].sum())
        res['retain_same_entity'] = float((kp & known_ok0)[hk].sum() / known_ok0[hk].sum())
        out[name] = res
    mapped = apply_map(M, HA)
    def onheld(Hrep):
        H = HB.copy(); H[held] = Hrep[held]; return H
    score(HB, 'baseline')
    score(onheld(mapped), 'swap_full')
    score(onheld(HB + (mapped - HB) @ P), 'swap_shared')
    def score_avg(Hs, name):
        for j, H in enumerate(Hs):
            score(H, f'_tmp{j}')
        tmp = [out.pop(f'_tmp{j}') for j in range(len(Hs))]
        out[name] = {kk: (float(np.mean([t[kk] for t in tmp])) if tmp[0][kk] is not None else None) for kk in tmp[0]}
    NC = 5
    rr = []
    for _ in range(NC):
        Q, _ = np.linalg.qr(rng.standard_normal((dB, dB))); Mr = dict(M); Mr['R'] = Q[:dA]
        rr.append(onheld(HB + (apply_map(Mr, HA) - HB) @ P))
    score_avg(rr, 'ctl_randrot')
    score_avg([onheld(HB + (apply_map(procrustes(HA[anchors], HB[anchors][rng.permutation(len(anchors))]), HA) - HB) @ P) for _ in range(NC)], 'ctl_shufanchor')
    perms = [held[rng.permutation(n_held)] for _ in range(NC)]
    delta = (mapped - HB) @ P
    score_avg([onheld(HB + np.vstack([np.zeros((n_ent - n_held, dB)), delta[pp]])) for pp in perms], 'ctl_shufdonor')
    # relation prior: answer every test fact with that relation's most common answer among anchors
    prior = {r: np.bincount(Y[anchors, r], minlength=N_VAL).argmax() for r in rB}
    okp = np.array([prior[r] for r in tR]) == ty
    out['relation_prior'] = {c: float(okp[miss & (tcat == c)].mean()) if (miss & (tcat == c)).any() else None for c in ['shared', 'partial', 'unshared']}
    perm = perms[0]
    # imprint (donor unplugged): edit B.Wd; evaluate the edited model on its own
    Wd0 = B.p['Wd'].copy()
    for lam in lams:
        for tag, tgt in [('full', mapped), ('shared', HB + (mapped - HB) @ P)]:
            for ctl in [False, True]:
                T = tgt[held] if not ctl else (tgt[perm] - HB[perm] + HB[held])  # control: another held entity's update
                dW = imprint(B, held, T, anchors, lam)
                B.p['Wd'] = Wd0 + dW
                score(B.key(), f'imprint_{tag}_lam{lam:g}' + ('_shufdonor' if ctl else ''))
                B.p['Wd'] = Wd0
    out['secs'] = round(time.time() - t0, 1)
    if export:
        return out, dict(A=A, B=B, M=M, P=P, rels=rels, rA=rA, rB=rB, Y=Y, held=held, anchors=anchors,
                         tI=tI, tR=tR, tcat=tcat, miss=miss, known=(known_I, known_R), perm=perm)
    return out

if __name__ == '__main__':
    seed, k = int(sys.argv[1]), int(sys.argv[2])
    steps = int(sys.argv[3]) if len(sys.argv) > 3 else 1500
    o = run(seed, k, steps=steps)
    import os; os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'results'), exist_ok=True)
    json.dump(o, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'results', f'r_{seed}_{k}.json'), 'w'), indent=1)
    print(json.dumps(o)[:3000])
