# -*- coding: utf-8 -*-
"""
Suite19 exact expanding-fold reuse.

A previous fold may be reused ONLY if every previous historical row maps
exactly to the current expanding fold and all chronology-sensitive inputs
are identical.

A mismatch disables reuse and falls back to normal computation.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any
import hashlib

import numpy as np


@dataclass
class IncrementalFoldContext:
    previous_fold: int
    current_fold: int

    previous_hist: Any

    # previous historical row index -> current historical row index
    previous_to_current: np.ndarray

    shared_blocks: tuple[float, ...]

    exact: bool
    reason: str

    key_scheme: str

    mapped_rows: int
    mapping_sha1: str

    def summary(self):
        return {
            "previous_fold": int(self.previous_fold),
            "current_fold": int(self.current_fold),
            "exact": bool(self.exact),
            "reason": str(self.reason),
            "key_scheme": str(self.key_scheme),
            "mapped_rows": int(self.mapped_rows),
            "shared_blocks": list(self.shared_blocks),
            "mapping_sha1": str(self.mapping_sha1),
        }


def _stable_keys(bundle):
    """
    Construct stable row identities.

    Prefer faculty + row_index when row_index is unique.
    Otherwise use:
        faculty + student + course + target_semester + occurrence
    """
    n = len(bundle.y)

    fac = np.asarray(
        bundle.faculty_idx,
        int,
    )

    row_index = getattr(
        bundle,
        "row_index",
        None,
    )

    if (
        row_index is not None
        and len(row_index) == n
    ):
        ri = np.asarray(row_index)

        keys = [
            (
                "row_index",
                int(fac[i]),
                str(ri[i]),
            )
            for i in range(n)
        ]

        if len(set(keys)) == n:
            return (
                keys,
                "faculty+row_index",
            )

    sid = np.asarray(
        bundle.student_id,
        object,
    )

    cid = np.asarray(
        bundle.course_id,
        object,
    )

    semester = np.asarray(
        bundle.target_semester,
        object,
    )

    counts = {}
    keys = []

    for i in range(n):
        base = (
            int(fac[i]),
            str(sid[i]),
            str(cid[i]),
            str(semester[i]),
        )

        occurrence = counts.get(
            base,
            0,
        )

        counts[base] = (
            occurrence + 1
        )

        keys.append(
            (
                "identity",
                *base,
                occurrence,
            )
        )

    if len(set(keys)) != n:
        raise RuntimeError(
            "Could not construct unique "
            "historical row identities."
        )

    return (
        keys,
        (
            "faculty+student+course+"
            "semester+occurrence"
        ),
    )


def _equal_array(a, b):
    a = np.asarray(a)
    b = np.asarray(b)

    if a.shape != b.shape:
        return False

    if (
        np.issubdtype(
            a.dtype,
            np.number,
        )
        and np.issubdtype(
            b.dtype,
            np.number,
        )
    ):
        return bool(
            np.allclose(
                a,
                b,
                rtol=0.0,
                atol=0.0,
                equal_nan=True,
            )
        )

    return bool(
        np.array_equal(
            a.astype(str),
            b.astype(str),
        )
    )


def build_incremental_context(
    previous_hist,
    current_hist,
    previous_fold: int,
    current_fold: int,
):
    """
    Prove that previous_hist is an exact historical subset
    of current_hist.

    No target labels are inspected.
    """

    try:
        prev_keys, prev_scheme = (
            _stable_keys(
                previous_hist
            )
        )

        cur_keys, cur_scheme = (
            _stable_keys(
                current_hist
            )
        )

    except Exception as exc:
        return IncrementalFoldContext(
            previous_fold=previous_fold,
            current_fold=current_fold,
            previous_hist=previous_hist,
            previous_to_current=np.full(
                len(previous_hist.y),
                -1,
                dtype=int,
            ),
            shared_blocks=(),
            exact=False,
            reason=(
                "row_identity_error: "
                f"{type(exc).__name__}: {exc}"
            ),
            key_scheme="unavailable",
            mapped_rows=0,
            mapping_sha1="",
        )

    current_lookup = {
        key: i
        for i, key
        in enumerate(cur_keys)
    }

    mapping = np.asarray(
        [
            current_lookup.get(
                key,
                -1,
            )
            for key in prev_keys
        ],
        dtype=int,
    )

    if np.any(mapping < 0):
        missing = int(
            np.sum(mapping < 0)
        )

        return IncrementalFoldContext(
            previous_fold=previous_fold,
            current_fold=current_fold,
            previous_hist=previous_hist,
            previous_to_current=mapping,
            shared_blocks=(),
            exact=False,
            reason=(
                f"{missing} previous historical "
                "rows are absent from the "
                "current fold"
            ),
            key_scheme=(
                f"{prev_scheme}"
                f"->{cur_scheme}"
            ),
            mapped_rows=int(
                np.sum(mapping >= 0)
            ),
            mapping_sha1="",
        )

    checks = [
        (
            "y",
            previous_hist.y,
            current_hist.y[mapping],
        ),
        (
            "blocks",
            previous_hist.blocks,
            current_hist.blocks[mapping],
        ),
        (
            "faculty_idx",
            previous_hist.faculty_idx,
            current_hist.faculty_idx[
                mapping
            ],
        ),
        (
            "flat",
            previous_hist.flat,
            current_hist.flat[mapping],
        ),
        (
            "teacher",
            previous_hist.teacher,
            current_hist.teacher[mapping],
        ),
        (
            "mechanism_targets",
            previous_hist.mechanism_targets,
            current_hist.mechanism_targets[
                mapping
            ],
        ),
        (
            "student_id",
            previous_hist.student_id,
            current_hist.student_id[
                mapping
            ],
        ),
        (
            "course_id",
            previous_hist.course_id,
            current_hist.course_id[
                mapping
            ],
        ),
        (
            "target_semester",
            previous_hist.target_semester,
            current_hist.target_semester[
                mapping
            ],
        ),
    ]

    for name, old, new in checks:
        if not _equal_array(
            old,
            new,
        ):
            return IncrementalFoldContext(
                previous_fold=
                    previous_fold,
                current_fold=
                    current_fold,
                previous_hist=
                    previous_hist,
                previous_to_current=
                    mapping,
                shared_blocks=(),
                exact=False,
                reason=(
                    "historical field "
                    f"mismatch: {name}"
                ),
                key_scheme=(
                    f"{prev_scheme}"
                    f"->{cur_scheme}"
                ),
                mapped_rows=len(mapping),
                mapping_sha1="",
            )

    shared_blocks = tuple(
        float(x)
        for x in sorted(
            v
            for v in np.unique(
                np.asarray(
                    previous_hist.blocks,
                    float,
                )
            )
            if np.isfinite(v)
        )
    )

    digest = hashlib.sha1(
        mapping.astype(
            np.int64
        ).tobytes()
    ).hexdigest()

    return IncrementalFoldContext(
        previous_fold=previous_fold,
        current_fold=current_fold,
        previous_hist=previous_hist,
        previous_to_current=mapping,
        shared_blocks=shared_blocks,
        exact=True,
        reason=(
            "exact historical subset "
            "verified"
        ),
        key_scheme=(
            f"{prev_scheme}"
            f"->{cur_scheme}"
        ),
        mapped_rows=len(mapping),
        mapping_sha1=digest,
    )


def identity_context(
    hist,
    fold: int,
):
    """
    Same-fold identity mapping.

    Used when production seed 42 reuses its already-computed
    historical selection representation.
    """
    mapping = np.arange(
        len(hist.y),
        dtype=int,
    )

    blocks = tuple(
        float(x)
        for x in sorted(
            v
            for v in np.unique(
                np.asarray(
                    hist.blocks,
                    float,
                )
            )
            if np.isfinite(v)
        )
    )

    digest = hashlib.sha1(
        mapping.astype(
            np.int64
        ).tobytes()
    ).hexdigest()

    return IncrementalFoldContext(
        previous_fold=fold,
        current_fold=fold,
        previous_hist=hist,
        previous_to_current=mapping,
        shared_blocks=blocks,
        exact=True,
        reason=(
            "same-fold exact identity"
        ),
        key_scheme="identity",
        mapped_rows=len(mapping),
        mapping_sha1=digest,
    )