# -*- coding: utf-8 -*-
"""
Strict chronology-safe prequential representation ledger.

IMPORTANT
---------
hist_z / target_z are NOT raw native latent coordinates.

Every independent temporal encoder is mapped into the fixed
anchor-whitened-landmark coordinate system before entering any global probe.

Native model predictions remain model-native.
"""
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Any

import inspect
import time

import joblib
import numpy as np
import gc

from suite19_common import (
    PrefixPreprocessor,
    cache_signature,
    matrix_fingerprint,
    runtime_snapshot,
)
from suite19_coordinates import (
    COORDINATE_SYSTEM,
    COORDINATE_VERSION,
    select_anchor_rows,
    select_landmark_positions,
    landmark_coordinates,
    procrustes_diagnostics,
)


@dataclass
class PrequentialRepresentationLedger:
    hist_z: np.ndarray
    hist_available: np.ndarray
    hist_native: np.ndarray
    hist_direct: np.ndarray

    target_z: np.ndarray | None
    target_available: np.ndarray | None
    target_native: np.ndarray | None
    target_direct: np.ndarray | None

    chronology_audit: list[dict]
    chronology_violations: int
    model_metadata: list[dict]
    production_metadata: dict | None

    signature: str | None = None

    coordinate_system: str = COORDINATE_SYSTEM
    coordinate_audit: list[dict] | None = None
    anchor_indices: np.ndarray | None = None
    landmark_positions: np.ndarray | None = None

    reference_native_anchor: np.ndarray | None = None
    reused_hist_blocks: list[float] | None = None
    reuse_summary: dict | None = None
    score_policy: str = "full"


def _can_fit(y, min_rows, min_fail):
    y = np.asarray(y, int)

    return (
        len(y) >= int(min_rows)
        and np.unique(y).size == 2
        and int(y.sum()) >= int(min_fail)
        and int((y == 0).sum()) >= int(min_fail)
    )


def _fit_encoder(enc, X, y, committee, mechanism, faculty):
    params = inspect.signature(enc.fit).parameters
    kw = {}

    if "committee" in params:
        kw["committee"] = committee
    if "mechanism" in params:
        kw["mechanism"] = mechanism
    if "faculty" in params:
        kw["faculty"] = faculty

    return enc.fit(X, y, **kw)


def _scores(enc, X, memory_X, memory_y):
    native = direct = None

    if hasattr(enc, "native_predict"):
        try:
            native = enc.native_predict(
                X,
                memory_X=memory_X,
                memory_y=memory_y,
                exclude_self=False,
            )
        except TypeError:
            native = enc.native_predict(X, memory_X, memory_y)

    if hasattr(enc, "direct_predict"):
        try:
            direct = enc.direct_predict(X)
        except Exception:
            direct = None
    elif hasattr(enc, "predict_proba"):
        try:
            direct = enc.predict_proba(X)
        except Exception:
            direct = None

    if native is None:
        native = direct
    if direct is None:
        direct = native

    return native, direct


def _transform_encoder(enc, X):
    z = np.asarray(enc.transform(X), np.float32)

    if z.ndim != 2 or len(z) != len(X):
        raise RuntimeError(
            f"encoder emitted invalid latent shape {z.shape}"
        )

    if not np.isfinite(z).all():
        raise RuntimeError("encoder emitted non-finite latent values")

    return z


def build_prequential_ledger(
    X,
    y,
    blocks,
    faculty,
    committee,
    mechanism,
    encoder_factory: Callable[[int], Any],
    *,
    latent_dim,
    target_X=None,
    target_committee=None,
    target_mechanism=None,
    target_blocks=None,
    min_prior_blocks=4,
    min_train_rows=5000,
    min_failures=50,
    seed=42,
    feature_names=None,
    cache_path=None,
    cache_config=None,
    source_fingerprints=None,
    force=False,
    clip_z=12.0,
    min_coverage_guard=0.0,
    max_runtime_seconds=0.0,
    coordinate_anchor_rows=1024,
    coordinate_anchor_seed=20260905,
    coordinate_ridge=1e-5,
    coordinate_rank_tol=1e-7,
    reuse_context=None,
    compute_historical_scores=True,
):
    X = np.asarray(X, np.float32)
    y = np.asarray(y, int)
    b = np.asarray(blocks, float)
    fac = np.asarray(faculty, int)
    q = np.asarray(committee, np.float32)
    mech = (
        None
        if mechanism is None
        else np.asarray(mechanism, np.float32)
    )

    if not (len(X) == len(y) == len(b) == len(fac) == len(q)):
        raise ValueError("historical alignment mismatch")

    if mech is not None and len(mech) != len(y):
        raise ValueError("mechanism alignment mismatch")

    names = (
        list(feature_names)
        if feature_names is not None
        else [f"x{i}" for i in range(X.shape[1])]
    )

    cfg = {
        "ledger_schema": 7,
        "coordinate_system": COORDINATE_SYSTEM,
        "coordinate_version": COORDINATE_VERSION,
        "coordinate_anchor_rows": int(coordinate_anchor_rows),
        "coordinate_anchor_seed": int(coordinate_anchor_seed),
        "coordinate_ridge": float(coordinate_ridge),
        "coordinate_rank_tol": float(coordinate_rank_tol),
        "latent_dim": int(latent_dim),
        "min_prior_blocks": int(min_prior_blocks),
        "min_train_rows": int(min_train_rows),
        "min_failures": int(min_failures),
        "clip_z": float(clip_z),
        **(cache_config or {}),
    }

    if target_X is not None:
        cfg["target_rows"] = int(len(target_X))
        cfg["target_matrix_fingerprint"] = matrix_fingerprint(target_X)

        if target_committee is not None:
            cfg["target_committee_fingerprint"] = matrix_fingerprint(
                np.asarray(target_committee, np.float32).reshape(-1, 1)
            )

        if target_blocks is not None:
            cfg["target_blocks_fingerprint"] = matrix_fingerprint(
                np.asarray(target_blocks, float).reshape(-1, 1)
            )

    sig = cache_signature(
        getattr(encoder_factory, "__name__", str(encoder_factory)),
        names,
        y,
        b,
        cfg,
        seed,
        matrix_fingerprint(X),
        source_fingerprints,
    )

    cp = Path(cache_path) if cache_path else None

    if cp and cp.exists() and not force:
        try:
            obj = joblib.load(cp)

            if (
                isinstance(obj, PrequentialRepresentationLedger)
                and obj.signature == sig
                and getattr(obj, "coordinate_system", None)
                == COORDINATE_SYSTEM
            ):
                print(
                    f"[REP CACHE] reuse common-coordinate ledger {cp}"
                )
                return obj
        except Exception:
            pass

    # The GLOBAL probe space has exactly latent_dim coordinates:
    # one fixed historical landmark identity per coordinate.
    hz = np.zeros((len(X), int(latent_dim)), np.float32)
    hav = np.zeros(len(X), bool)

    hn = np.full(len(X), np.nan, np.float32)
    hd = np.full(len(X), np.nan, np.float32)

    chronology = []
    coordinate_audit = []
    metadata = []

    violations = 0
    started = time.perf_counter()

    vals = np.asarray(
        sorted(v for v in np.unique(b) if np.isfinite(v)),
        float,
    )

    anchor_indices = None
    landmark_positions = None
    reference_native_anchor = None

    reuse_ledger = None
    reuse_fold_context = None
    reuse_source = None

    reused_hist_blocks = []
    reused_hist_rows = 0
    estimated_saved_seconds = 0.0

    if reuse_context:
        reuse_ledger = (
            reuse_context.get(
                "ledger"
            )
        )

        reuse_fold_context = (
            reuse_context.get(
                "fold_context"
            )
        )

        reuse_source = (
            reuse_context.get(
                "source"
            )
        )

        valid_reuse = bool(
            reuse_ledger is not None
            and reuse_fold_context
                is not None
            and reuse_fold_context.exact
            and getattr(
                reuse_ledger,
                "coordinate_system",
                None,
            )
            == COORDINATE_SYSTEM
        )

        if not valid_reuse:
            reuse_ledger = None
            reuse_fold_context = None

    if reuse_ledger is not None:
        previous_anchor = getattr(
            reuse_ledger,
            "anchor_indices",
            None,
        )

        previous_landmarks = getattr(
            reuse_ledger,
            "landmark_positions",
            None,
        )

        if (
            previous_anchor
            is not None
            and previous_landmarks
            is not None
        ):
            mapped_anchor = (
                reuse_fold_context
                .previous_to_current[
                    np.asarray(
                        previous_anchor,
                        int,
                    )
                ]
            )

            if np.all(
                mapped_anchor >= 0
            ):
                anchor_indices = (
                    mapped_anchor
                    .astype(int)
                )

                landmark_positions = (
                    np.asarray(
                        previous_landmarks,
                        int,
                    ).copy()
                )

        reference_native_anchor = (
            getattr(
                reuse_ledger,
                "reference_native_anchor",
                None,
            )
        )

        print(
            "[INCREMENTAL REPRESENTATION PREFIX] "
            f"source={reuse_source} "
            f"mapped_rows="
            f"{reuse_fold_context.mapped_rows:,} "
            f"shared_blocks="
            f"{list(reuse_fold_context.shared_blocks)}"
        )

    for wi, qb in enumerate(vals):
        qi = np.where(b == qb)[0]
        tr = np.where(b < qb)[0]

        prior = np.unique(b[tr][np.isfinite(b[tr])])

        available = (
            len(prior) >= int(min_prior_blocks)
            and _can_fit(y[tr], min_train_rows, min_failures)
        )

        row = {
            "scope": "hist",
            "window": wi,
            "query_blocks": str(qb),
            "query_min_block": float(qb),
            "query_max_block": float(qb),
            "query_rows": int(len(qi)),
            "query_failures": int(y[qi].sum()),
            "query_prevalence": (
                float(y[qi].mean()) if len(qi) else np.nan
            ),
            "train_rows": int(len(tr)),
            "train_failures": int(y[tr].sum()),
            "train_prevalence": (
                float(y[tr].mean()) if len(tr) else np.nan
            ),
            "train_max_block": (
                float(np.max(b[tr])) if len(tr) else np.nan
            ),
            "available": bool(available),
            "coordinate_system": COORDINATE_SYSTEM,
        }

        if not available:
            row[
                "strict_train_before_query"
            ] = True

            row[
                "coordinate_available"
            ] = False

            chronology.append(row)
            continue

        strict = bool(
            np.max(b[tr])
            < np.min(b[qi])
        )

        # ----------------------------------------------------------
        # Exact cross-fold historical representation reuse.
        # ----------------------------------------------------------
        reused = False

        if (
            strict
            and reuse_ledger
                is not None
            and float(qb)
                in set(
                    reuse_fold_context
                    .shared_blocks
                )
        ):
            previous_blocks = (
                np.asarray(
                    reuse_fold_context
                    .previous_hist.blocks,
                    float,
                )
            )

            previous_qi = np.where(
                previous_blocks == qb
            )[0]

            mapped_qi = (
                reuse_fold_context
                .previous_to_current[
                    previous_qi
                ]
            )

            current_qi = np.where(
                b == qb
            )[0]

            exact_query_population = (
                len(previous_qi)
                == len(current_qi)
                and np.all(
                    mapped_qi >= 0
                )
                and set(
                    mapped_qi.tolist()
                )
                == set(
                    current_qi.tolist()
                )
            )

            previous_available = (
                len(previous_qi) > 0
                and np.all(
                    np.asarray(
                        reuse_ledger
                        .hist_available,
                        bool,
                    )[
                        previous_qi
                    ]
                )
            )

            if (
                exact_query_population
                and previous_available
            ):
                hz[mapped_qi] = (
                    reuse_ledger
                    .hist_z[
                        previous_qi
                    ]
                )

                hav[mapped_qi] = True

                old_native = np.asarray(
                    reuse_ledger
                    .hist_native
                )

                if (
                    len(old_native)
                    == len(
                        previous_blocks
                    )
                ):
                    hn[mapped_qi] = (
                        old_native[
                            previous_qi
                        ]
                    )

                old_direct = np.asarray(
                    reuse_ledger
                    .hist_direct
                )

                if (
                    len(old_direct)
                    == len(
                        previous_blocks
                    )
                ):
                    hd[mapped_qi] = (
                        old_direct[
                            previous_qi
                        ]
                    )

                old_row = next(
                    (
                        dict(r)
                        for r in
                        reuse_ledger
                        .chronology_audit
                        if (
                            r.get("scope")
                            == "hist"
                            and float(
                                r.get(
                                    "query_min_block",
                                    r.get(
                                        "query_block",
                                        np.nan,
                                    ),
                                )
                            )
                            == float(qb)
                        )
                    ),
                    None,
                )

                if old_row is None:
                    raise RuntimeError(
                        "Incremental representation "
                        "reuse found embeddings "
                        "without chronology metadata."
                    )

                old_row[
                    "window"
                ] = wi

                old_row[
                    "incremental_reuse"
                ] = True

                old_row[
                    "incremental_source"
                ] = str(
                    reuse_source
                )

                chronology.append(
                    old_row
                )

                old_coord = next(
                    (
                        dict(r)
                        for r in (
                            getattr(
                                reuse_ledger,
                                "coordinate_audit",
                                [],
                            )
                            or []
                        )
                        if (
                            r.get("scope")
                            == "hist"
                            and float(
                                r.get(
                                    "query_block",
                                    np.nan,
                                )
                            )
                            == float(qb)
                        )
                    ),
                    None,
                )

                if old_coord is not None:
                    old_coord[
                        "window"
                    ] = wi

                    old_coord[
                        "incremental_reuse"
                    ] = True

                    old_coord[
                        "incremental_source"
                    ] = str(
                        reuse_source
                    )

                    coordinate_audit.append(
                        old_coord
                    )

                old_md = next(
                    (
                        dict(r)
                        for r in
                        reuse_ledger
                        .model_metadata
                        if float(
                            r.get(
                                "query_block",
                                np.nan,
                            )
                        )
                        == float(qb)
                    ),
                    None,
                )

                if old_md is not None:
                    old_md[
                        "incremental_reuse"
                    ] = True

                    old_md[
                        "incremental_source"
                    ] = str(
                        reuse_source
                    )

                    metadata.append(
                        old_md
                    )

                    estimated_saved_seconds += (
                        float(
                            old_md.get(
                                "fit_seconds_observed",
                                0.0,
                            )
                        )
                        + float(
                            old_md.get(
                                "transform_seconds_observed",
                                0.0,
                            )
                        )
                        + float(
                            old_md.get(
                                "native_score_seconds",
                                0.0,
                            )
                        )
                    )

                reused_hist_blocks.append(
                    float(qb)
                )

                reused_hist_rows += int(
                    len(mapped_qi)
                )

                print(
                    "  [INCREMENTAL REP HIT] "
                    f"block={qb:g} "
                    f"rows="
                    f"{len(mapped_qi):,} "
                    f"source="
                    f"{reuse_source}"
                )

                reused = True

        if reused:
            continue
        row["strict_train_before_query"] = strict

        if not strict:
            violations += 1
            raise RuntimeError(
                f"historical chronology violation: "
                f"train_max={np.max(b[tr])}, query={qb}"
            )

        # Freeze the landmark identities from the FIRST legal historical
        # prefix. They are historical for every later window and target.
        if anchor_indices is None:
            anchor_indices = select_anchor_rows(
                tr,
                fac,
                max_rows=coordinate_anchor_rows,
                seed=coordinate_anchor_seed,
            )

            landmark_positions = select_landmark_positions(
                anchor_indices,
                fac,
                n_landmarks=int(latent_dim),
                seed=coordinate_anchor_seed,
            )

            print(
                "[COMMON COORDINATE FRAME] "
                f"first_legal_query_block={qb:g} "
                f"anchor_rows={len(anchor_indices)} "
                f"landmarks={len(landmark_positions)} "
                f"anchor_block_min={np.min(b[anchor_indices]):g} "
                f"anchor_block_max={np.max(b[anchor_indices]):g}"
            )

            fac_counts = {
                int(f): int(np.sum(fac[anchor_indices] == f))
                for f in np.unique(fac[anchor_indices])
            }
            print(
                "[COMMON COORDINATE ANCHOR FACULTY COUNTS] "
                + str(fac_counts)
            )

        prep = PrefixPreprocessor(clip_z).fit(X[tr])

        xtr = prep.transform(X[tr])
        xq = prep.transform(X[qi])
        xa = prep.transform(X[anchor_indices])

        enc = encoder_factory(int(seed) + wi * 1009)

        snap0 = runtime_snapshot()
        t0 = time.perf_counter()

        _fit_encoder(
            enc,
            xtr,
            y[tr],
            q[tr],
            None if mech is None else mech[tr],
            fac[tr],
        )

        fit_seconds = time.perf_counter() - t0

        t1 = time.perf_counter()
        native_query_z = _transform_encoder(enc, xq)
        native_anchor_z = _transform_encoder(enc, xa)
        transform_seconds = time.perf_counter() - t1

        canonical_z, cdiag = landmark_coordinates(
            native_anchor_z,
            native_query_z,
            landmark_positions,
            ridge=coordinate_ridge,
            rank_tol=coordinate_rank_tol,
        )

        if canonical_z.shape != (len(qi), int(latent_dim)):
            raise RuntimeError(
                f"canonical representation shape mismatch: "
                f"{canonical_z.shape}"
            )

        pdiag = procrustes_diagnostics(
            reference_native_anchor,
            native_anchor_z,
        )

        if (
            reference_native_anchor
            is None
            and reuse_ledger
                is None
        ):
            reference_native_anchor = (
                native_anchor_z.copy()
            )

        hz[qi] = canonical_z
        hav[qi] = True

        if compute_historical_scores:
            ts = time.perf_counter()

            native_score, direct_score = (
                _scores(
                    enc,
                    xq,
                    xtr,
                    y[tr],
                )
            )

            score_seconds = (
                time.perf_counter()
                - ts
            )

        else:
            native_score = None
            direct_score = None
            score_seconds = 0.0

        if native_score is not None:
            hn[qi] = np.asarray(
                native_score, np.float32
            ).reshape(-1)

        if direct_score is not None:
            hd[qi] = np.asarray(
                direct_score, np.float32
            ).reshape(-1)

        coord_row = {
            "scope": "hist",
            "window": wi,
            "query_block": float(qb),
            "coordinate_system": COORDINATE_SYSTEM,
            "anchor_rows": int(len(anchor_indices)),
            "landmarks": int(len(landmark_positions)),
            "native_dim": int(native_query_z.shape[1]),
            **cdiag,
            **pdiag,
        }

        coordinate_audit.append(coord_row)

        md = dict(
            enc.metadata()
            if hasattr(enc, "metadata")
            else {}
        )

        md.update(
            scope="hist",
            window=wi,
            query_block=float(qb),
            fit_seconds_observed=float(fit_seconds),
            transform_seconds_observed=float(transform_seconds),
            native_score_seconds=float(score_seconds),
            preprocessor=prep.metadata(),
            query_preprocessing=prep.transform_diagnostics(X[qi]),
            coordinate_system=COORDINATE_SYSTEM,
            coordinate_diagnostics=coord_row,
            anchor_rows=int(len(anchor_indices)),
            landmark_rows=int(len(landmark_positions)),
            rss_before_mb=snap0.get("rss_mb"),
            rss_after_mb=runtime_snapshot().get("rss_mb"),
        )

        metadata.append(md)

        row.update(
            encoder_fit_seconds=float(fit_seconds),
            encoder_transform_seconds=float(transform_seconds),
            native_score_seconds=float(score_seconds),
            native_latent_dim=int(native_query_z.shape[1]),
            latent_dim=int(canonical_z.shape[1]),
            coordinate_available=True,
            whiten_rank=int(cdiag["whiten_rank"]),
            covariance_condition=float(
                cdiag["covariance_condition"]
            ),
            raw_procrustes_r2=float(
                pdiag["raw_procrustes_r2"]
            ),
        )

        chronology.append(row)

        print(
            "  [COORDINATE WINDOW] "
            f"block={qb:g} "
            f"native_dim={native_query_z.shape[1]} "
            f"canonical_dim={canonical_z.shape[1]} "
            f"rank={cdiag['whiten_rank']} "
            f"cond={cdiag['covariance_condition']:.3g} "
            f"rawProcrustesR2={pdiag['raw_procrustes_r2']:+.4f}"
        )

        if (
            max_runtime_seconds > 0
            and time.perf_counter() - started
            > float(max_runtime_seconds)
        ):
            raise TimeoutError(
                f"encoder ledger exceeded "
                f"{max_runtime_seconds}s safety limit"
            )

    # ------------------------------------------------------------------
    # Production target
    # ------------------------------------------------------------------
    tz = tav = tn = td = None
    production = None

    if target_X is not None:
        Xt = np.asarray(target_X, np.float32)
        tr = np.where(np.isfinite(b))[0]

        model_available = (
            len(np.unique(b[tr])) >= int(min_prior_blocks)
            and _can_fit(y[tr], min_train_rows, min_failures)
        )

        tz = np.zeros(
            (len(Xt), int(latent_dim)),
            np.float32,
        )
        tav = np.zeros(len(Xt), bool)
        tn = np.full(len(Xt), np.nan, np.float32)
        td = np.full(len(Xt), np.nan, np.float32)

        if target_blocks is None:
            raise RuntimeError(
                "Suite19 target_blocks are unavailable. "
                "Target chronology must be auditable; refusing "
                "fail-open production encoding."
            )

        tb = np.asarray(target_blocks, float)
        finite_tb = tb[np.isfinite(tb)]

        if len(finite_tb) != len(tb) or len(finite_tb) == 0:
            raise RuntimeError(
                "Suite19 target temporal blocks contain missing values; "
                "cannot prove train_max < target_min."
            )

        if not len(tr):
            raise RuntimeError("no historical rows available for target")

        strict_target = bool(
            np.max(b[tr]) < np.min(finite_tb)
        )

        if model_available and not strict_target:
            violations += 1
            raise RuntimeError(
                f"target chronology violation: "
                f"train_max={np.max(b[tr])}, "
                f"target_min={np.min(finite_tb)}"
            )

        canonical_available = (
            model_available
            and anchor_indices is not None
            and landmark_positions is not None
        )

        row = {
            "scope": "target",
            "window": "production",
            "query_blocks": ",".join(
                str(x)
                for x in sorted(np.unique(finite_tb))
            ),
            "query_min_block": float(np.min(finite_tb)),
            "query_max_block": float(np.max(finite_tb)),
            "query_rows": int(len(Xt)),
            "train_rows": int(len(tr)),
            "train_failures": int(y[tr].sum()),
            "train_prevalence": float(y[tr].mean()),
            "train_max_block": float(np.max(b[tr])),
            "available": bool(canonical_available),
            "model_available": bool(model_available),
            "coordinate_available": bool(canonical_available),
            "strict_train_before_query": strict_target,
            "coordinate_system": COORDINATE_SYSTEM,
        }

        if model_available:
            prep = PrefixPreprocessor(clip_z).fit(X[tr])

            xtr = prep.transform(X[tr])
            xt = prep.transform(Xt)

            enc = encoder_factory(int(seed) + 900001)

            snap0 = runtime_snapshot()
            t0 = time.perf_counter()

            _fit_encoder(
                enc,
                xtr,
                y[tr],
                q[tr],
                None if mech is None else mech[tr],
                fac[tr],
            )

            fit_seconds = time.perf_counter() - t0

            t1 = time.perf_counter()
            native_target_z = _transform_encoder(enc, xt)
            transform_seconds = time.perf_counter() - t1

            if canonical_available:
                xa = prep.transform(X[anchor_indices])
                native_anchor_z = _transform_encoder(enc, xa)

                canonical_z, cdiag = landmark_coordinates(
                    native_anchor_z,
                    native_target_z,
                    landmark_positions,
                    ridge=coordinate_ridge,
                    rank_tol=coordinate_rank_tol,
                )

                pdiag = procrustes_diagnostics(
                    reference_native_anchor,
                    native_anchor_z,
                )

                tz[:] = canonical_z
                tav[:] = True

                coord_row = {
                    "scope": "target",
                    "window": "production",
                    "query_min_block": float(
                        np.min(finite_tb)
                    ),
                    "coordinate_system": COORDINATE_SYSTEM,
                    "anchor_rows": int(len(anchor_indices)),
                    "landmarks": int(
                        len(landmark_positions)
                    ),
                    "native_dim": int(
                        native_target_z.shape[1]
                    ),
                    **cdiag,
                    **pdiag,
                }

                coordinate_audit.append(coord_row)

                row.update(
                    latent_dim=int(canonical_z.shape[1]),
                    native_latent_dim=int(
                        native_target_z.shape[1]
                    ),
                    whiten_rank=int(
                        cdiag["whiten_rank"]
                    ),
                    covariance_condition=float(
                        cdiag["covariance_condition"]
                    ),
                    raw_procrustes_r2=float(
                        pdiag["raw_procrustes_r2"]
                    ),
                )
            else:
                cdiag = {}
                pdiag = {}

            ts = time.perf_counter()
            native_score, direct_score = _scores(
                enc,
                xt,
                xtr,
                y[tr],
            )
            score_seconds = time.perf_counter() - ts

            if native_score is not None:
                tn[:] = np.asarray(
                    native_score, np.float32
                ).reshape(-1)

            if direct_score is not None:
                td[:] = np.asarray(
                    direct_score, np.float32
                ).reshape(-1)

            production = dict(
                enc.metadata()
                if hasattr(enc, "metadata")
                else {}
            )

            production.update(
                scope="target",
                fit_seconds_observed=float(fit_seconds),
                transform_seconds_observed=float(
                    transform_seconds
                ),
                native_score_seconds=float(score_seconds),
                preprocessor=prep.metadata(),
                query_preprocessing=prep.transform_diagnostics(
                    Xt
                ),
                coordinate_system=COORDINATE_SYSTEM,
                coordinate_available=bool(
                    canonical_available
                ),
                anchor_rows=(
                    int(len(anchor_indices))
                    if anchor_indices is not None
                    else 0
                ),
                landmark_rows=(
                    int(len(landmark_positions))
                    if landmark_positions is not None
                    else 0
                ),
                coordinate_diagnostics=(
                    coordinate_audit[-1]
                    if canonical_available
                    else {}
                ),
                rss_before_mb=snap0.get("rss_mb"),
                rss_after_mb=runtime_snapshot().get(
                    "rss_mb"
                ),
            )

            if hasattr(enc, "neighbor_examples"):
                try:
                    production["neighbor_examples"] = (
                        enc.neighbor_examples(
                            xt,
                            xtr,
                            y[tr],
                            k=5,
                            max_queries=12,
                        )
                    )
                except Exception as exc:
                    production[
                        "neighbor_examples_error"
                    ] = repr(exc)

            row.update(
                encoder_fit_seconds=float(fit_seconds),
                encoder_transform_seconds=float(
                    transform_seconds
                ),
                native_score_seconds=float(score_seconds),
            )

        chronology.append(row)

    coverage = (
        float(hav.mean()) if len(hav) else 0.0
    )

    if (
        min_coverage_guard > 0
        and coverage < float(min_coverage_guard)
    ):
        raise RuntimeError(
            f"OOF representation coverage "
            f"{coverage:.3f} < guard "
            f"{float(min_coverage_guard):.3f}"
        )

    if violations:
        raise RuntimeError(
            f"Suite19 chronology violations={violations}"
        )

    reuse_summary = {
        "enabled": bool(
            reuse_ledger is not None
        ),
        "source": reuse_source,
        "reused_hist_blocks":
            reused_hist_blocks,
        "reused_hist_rows":
            int(reused_hist_rows),
        "computed_hist_blocks": [
            float(
                r.get(
                    "query_min_block",
                    np.nan,
                )
            )
            for r in chronology
            if (
                r.get("scope")
                == "hist"
                and r.get(
                    "available",
                    False,
                )
                and not r.get(
                    "incremental_reuse",
                    False,
                )
            )
        ],
        "estimated_saved_seconds":
            float(
                estimated_saved_seconds
            ),
    }

    ledger = PrequentialRepresentationLedger(
        hist_z=hz,
        hist_available=hav,
        hist_native=hn,
        hist_direct=hd,
        target_z=tz,
        target_available=tav,
        target_native=tn,
        target_direct=td,
        chronology_audit=chronology,
        chronology_violations=violations,
        model_metadata=metadata,
        production_metadata=production,
        signature=sig,
        coordinate_system=COORDINATE_SYSTEM,
        coordinate_audit=coordinate_audit,
        anchor_indices=anchor_indices,
        landmark_positions=landmark_positions,
        reference_native_anchor=
            reference_native_anchor,

        reused_hist_blocks=
            reused_hist_blocks,

        reuse_summary=
            reuse_summary,

        score_policy=(
            "full"
            if compute_historical_scores
            else
            "representation_only"
        ),
    )

    if cp:
        cp.parent.mkdir(
            parents=True,
            exist_ok=True,
        )
        joblib.dump(ledger, cp, compress=3)

    print(
        "[COMMON COORDINATE ASSERT] "
        f"system={COORDINATE_SYSTEM} "
        f"coverage={coverage:.1%} "
        f"anchor_rows="
        f"{0 if anchor_indices is None else len(anchor_indices)} "
        f"landmarks="
        f"{0 if landmark_positions is None else len(landmark_positions)} "
        f"chronology_violations={violations}"
    )

    if reuse_ledger is not None:
        print(
            "[INCREMENTAL REPRESENTATION SUMMARY] "
            f"hits="
            f"{len(reused_hist_blocks)} "
            f"rows="
            f"{reused_hist_rows:,} "
            f"new_blocks="
            f"{reuse_summary['computed_hist_blocks']} "
            f"estimated_saved="
            f"{estimated_saved_seconds / 3600:.2f}h"
        )

    return ledger