# -*- coding: utf-8 -*-
"""
Chronology-safe common-coordinate construction for Suite19.

Why this exists
---------------
Each prequential window fits an independent supervised encoder E_t. Raw latent
axis j from E_t has no guarantee of corresponding to axis j from E_{t+1}.

For global OOF probes we therefore do NOT concatenate raw latent coordinates.

Instead, every fitted encoder re-embeds the SAME fixed historical anchor rows.
We whiten that model-specific anchor cloud and express query rows by cosine
similarities to the SAME fixed anchor-landmark identities.

If two native representations differ by an invertible affine
reparameterization, whitening leaves only an orthogonal gauge; pairwise
dot-products/cosines to the same landmark identities are invariant to that
remaining orthogonal transform.

No labels are used to choose anchors or landmarks.
"""
from __future__ import annotations

from dataclasses import dataclass
import numpy as np

COORDINATE_SYSTEM = "anchor_whitened_landmark_v1"
COORDINATE_VERSION = 1


@dataclass
class CoordinateDiagnostics:
    coordinate_system: str
    anchor_rows: int
    landmark_rows: int
    native_dim: int
    whiten_rank: int
    covariance_condition: float
    min_eigenvalue_kept: float
    max_eigenvalue: float
    raw_procrustes_r2: float
    raw_procrustes_nrmse: float
    raw_procrustes_mean_cosine: float


def _balanced_sample(indices, faculty, n, seed):
    """Deterministic faculty-balanced sampling. Does not use y."""
    idx = np.asarray(indices, dtype=np.int64)
    fac = np.asarray(faculty)

    if len(idx) <= int(n):
        return np.sort(idx)

    rng = np.random.default_rng(int(seed))
    groups = sorted(np.unique(fac[idx]).tolist(), key=str)

    chosen = []
    per = max(1, int(np.ceil(int(n) / max(len(groups), 1))))

    for g in groups:
        gi = idx[fac[idx] == g]
        if len(gi) <= per:
            chosen.extend(gi.tolist())
        else:
            chosen.extend(
                rng.choice(gi, size=per, replace=False).astype(np.int64).tolist()
            )

    chosen = np.unique(np.asarray(chosen, dtype=np.int64))

    if len(chosen) > int(n):
        chosen = np.sort(
            rng.choice(chosen, size=int(n), replace=False).astype(np.int64)
        )
    elif len(chosen) < int(n):
        remain = np.setdiff1d(idx, chosen, assume_unique=False)
        need = min(int(n) - len(chosen), len(remain))
        if need:
            extra = rng.choice(remain, size=need, replace=False).astype(np.int64)
            chosen = np.sort(np.concatenate([chosen, extra]))

    return chosen.astype(np.int64)


def select_anchor_rows(train_indices, faculty, max_rows=1024, seed=20260905):
    """
    Choose fixed historical anchor identities from the first legal training
    prefix. Selection is label-free and faculty-balanced.
    """
    tr = np.asarray(train_indices, dtype=np.int64)
    if len(tr) == 0:
        raise ValueError("cannot establish common coordinate frame without history")

    return _balanced_sample(
        tr,
        np.asarray(faculty),
        min(int(max_rows), len(tr)),
        int(seed),
    )


def select_landmark_positions(anchor_indices, faculty, n_landmarks, seed=20260905):
    """
    Select positions INSIDE anchor_indices, again without labels.
    """
    anchor_indices = np.asarray(anchor_indices, dtype=np.int64)

    if len(anchor_indices) < int(n_landmarks):
        raise ValueError(
            f"need >= {n_landmarks} anchors, got {len(anchor_indices)}"
        )

    positions = np.arange(len(anchor_indices), dtype=np.int64)
    af = np.asarray(faculty)[anchor_indices]

    return _balanced_sample(
        positions,
        af,
        int(n_landmarks),
        int(seed) + 7919,
    )


def _whiten_fit(anchor_z, ridge=1e-5, rank_tol=1e-7):
    A = np.asarray(anchor_z, dtype=np.float64)

    if A.ndim != 2 or len(A) < 3:
        raise ValueError("anchor latent matrix must be non-empty 2-D")

    if not np.isfinite(A).all():
        raise ValueError("non-finite anchor latent representation")

    mu = A.mean(axis=0)
    C = A - mu

    denom = max(len(A) - 1, 1)
    cov = (C.T @ C) / denom
    cov = (cov + cov.T) * 0.5

    eigval, eigvec = np.linalg.eigh(cov)
    order = np.argsort(eigval)[::-1]
    eigval = eigval[order]
    eigvec = eigvec[:, order]

    vmax = float(max(eigval[0], 0.0)) if len(eigval) else 0.0
    threshold = max(float(ridge), vmax * float(rank_tol))

    keep = eigval > threshold
    rank = int(np.sum(keep))

    if rank < 2:
        raise RuntimeError(
            f"common-coordinate whitening collapsed: rank={rank}"
        )

    vals = eigval[keep]
    vecs = eigvec[:, keep]

    W = vecs / np.sqrt(vals[None, :] + float(ridge))

    condition = float(vals.max() / max(vals.min(), 1e-12))

    return mu, W, {
        "whiten_rank": rank,
        "covariance_condition": condition,
        "min_eigenvalue_kept": float(vals.min()),
        "max_eigenvalue": float(vals.max()),
    }


def _unit_rows(X):
    X = np.asarray(X, dtype=np.float64)
    n = np.linalg.norm(X, axis=1, keepdims=True)
    return X / np.maximum(n, 1e-12)


def landmark_coordinates(
    anchor_z,
    query_z,
    landmark_positions,
    *,
    ridge=1e-5,
    rank_tol=1e-7,
):
    """
    Convert a model-specific latent representation to common coordinates.

    Output dimension = number of landmark identities.
    """
    A = np.asarray(anchor_z, dtype=np.float64)
    Q = np.asarray(query_z, dtype=np.float64)
    lp = np.asarray(landmark_positions, dtype=np.int64)

    if A.ndim != 2 or Q.ndim != 2:
        raise ValueError("anchor/query latent arrays must be 2-D")
    if A.shape[1] != Q.shape[1]:
        raise ValueError("anchor/query native latent dimensions differ")
    if not np.isfinite(Q).all():
        raise ValueError("query representation contains non-finite values")
    if np.any(lp < 0) or np.any(lp >= len(A)):
        raise ValueError("invalid landmark positions")

    mu, W, diag = _whiten_fit(A, ridge=ridge, rank_tol=rank_tol)

    Aw = (A - mu) @ W
    Qw = (Q - mu) @ W

    Aw = _unit_rows(Aw)
    Qw = _unit_rows(Qw)

    L = Aw[lp]
    Z = Qw @ L.T

    if not np.isfinite(Z).all():
        raise RuntimeError("canonical landmark coordinates became non-finite")

    return Z.astype(np.float32), diag


def procrustes_diagnostics(reference_anchor_z, current_anchor_z):
    """
    Diagnostic only. Never used to create the canonical probe coordinates.
    """
    if reference_anchor_z is None:
        return {
            "raw_procrustes_r2": np.nan,
            "raw_procrustes_nrmse": np.nan,
            "raw_procrustes_mean_cosine": np.nan,
        }

    A = np.asarray(reference_anchor_z, dtype=np.float64)
    B = np.asarray(current_anchor_z, dtype=np.float64)

    if A.shape != B.shape or A.ndim != 2 or len(A) < 3:
        return {
            "raw_procrustes_r2": np.nan,
            "raw_procrustes_nrmse": np.nan,
            "raw_procrustes_mean_cosine": np.nan,
        }

    Ac = A - A.mean(0)
    Bc = B - B.mean(0)

    sa = np.linalg.norm(Ac)
    sb = np.linalg.norm(Bc)

    if sa < 1e-12 or sb < 1e-12:
        return {
            "raw_procrustes_r2": np.nan,
            "raw_procrustes_nrmse": np.nan,
            "raw_procrustes_mean_cosine": np.nan,
        }

    Ac = Ac / sa
    Bc = Bc / sb

    U, _, Vt = np.linalg.svd(Bc.T @ Ac, full_matrices=False)
    R = U @ Vt
    Baligned = Bc @ R

    err = np.sum((Ac - Baligned) ** 2)
    denom = np.sum((Ac - Ac.mean(0)) ** 2)

    r2 = 1.0 - err / max(denom, 1e-12)
    nrmse = np.sqrt(np.mean((Ac - Baligned) ** 2)) / max(
        np.sqrt(np.mean(Ac ** 2)), 1e-12
    )

    au = _unit_rows(Ac)
    bu = _unit_rows(Baligned)
    cos = np.sum(au * bu, axis=1)

    return {
        "raw_procrustes_r2": float(r2),
        "raw_procrustes_nrmse": float(nrmse),
        "raw_procrustes_mean_cosine": float(np.mean(cos)),
    }