# -*- coding: utf-8 -*-
"""
Suite19 target chronology repair.

Suite17's extract_temporal_groups() is designed for temporal cross-fitting and
therefore requires >=2 distinct groups. A production target fold commonly has
exactly one future semester, so its `blocks` field can legitimately arrive as
all-NaN even though `target_semester` is available.

This module reconstructs audit-only target block IDs from chronology metadata.
It NEVER uses target labels.
"""
from __future__ import annotations

import numpy as np
import pandas as pd


def _numeric_semester(x):
    a = pd.to_numeric(
        pd.Series(np.asarray(x).reshape(-1)),
        errors="coerce",
    ).to_numpy(float)

    # Suite17 uses 0 when target_NHHK was unavailable.
    a[a <= 0] = np.nan
    return a


def repair_target_blocks(hist, target):
    """
    Return (target, audit_rows).

    If target.blocks is already fully finite, only validate it.

    Otherwise prove chronology using raw target semester metadata:
        min(target semester) > max(historical semester)

    Then create audit-only future block IDs immediately after the historical
    OOF block range. These IDs are used ONLY for chronology assertions /
    reporting; model features never receive absolute target time.
    """
    hb = np.asarray(hist.blocks, float)
    tb = np.asarray(target.blocks, float)

    if not np.isfinite(hb).all():
        raise RuntimeError(
            "Historical OOF blocks contain missing/non-finite values."
        )

    hist_block_max = float(np.max(hb))

    # ---------------------------------------------------------------
    # Existing target block IDs are trustworthy if they are complete
    # and strictly later than every historical row.
    # ---------------------------------------------------------------
    if len(tb) == len(target.y) and np.isfinite(tb).all():
        target_min = float(np.min(tb))

        if target_min <= hist_block_max:
            raise RuntimeError(
                "Existing target blocks violate chronology: "
                f"hist_max={hist_block_max:g}, target_min={target_min:g}"
            )

        audit = [{
            "scope": "global",
            "source": "existing_target_blocks",
            "historical_block_max": hist_block_max,
            "target_block_min": target_min,
            "target_block_max": float(np.max(tb)),
            "raw_hist_semester_max": np.nan,
            "raw_target_semester_min": np.nan,
            "target_rows": int(len(tb)),
            "strict_after_history": True,
        }]

        return target, audit

    # ---------------------------------------------------------------
    # Repair using the raw chronology metadata that Suite17 preserved.
    # ---------------------------------------------------------------
    if not hasattr(hist, "target_semester"):
        raise RuntimeError(
            "Cannot repair target chronology: hist.target_semester missing."
        )

    if not hasattr(target, "target_semester"):
        raise RuntimeError(
            "Cannot repair target chronology: target.target_semester missing."
        )

    hs = _numeric_semester(hist.target_semester)
    ts = _numeric_semester(target.target_semester)

    if len(hs) != len(hist.y):
        raise RuntimeError(
            "hist.target_semester length mismatch."
        )

    if len(ts) != len(target.y):
        raise RuntimeError(
            "target.target_semester length mismatch."
        )

    if not np.isfinite(ts).all():
        bad = int(np.sum(~np.isfinite(ts)))
        raise RuntimeError(
            "Target semester metadata is genuinely missing for "
            f"{bad}/{len(ts)} target rows; chronology cannot be proven."
        )

    finite_h = np.isfinite(hs)

    if not finite_h.any():
        raise RuntimeError(
            "Historical target semester metadata is unavailable."
        )

    hist_sem_max = float(np.max(hs[finite_h]))
    target_sem_min = float(np.min(ts))

    # This is the actual chronology proof.
    if target_sem_min <= hist_sem_max:
        raise RuntimeError(
            "Raw semester metadata does not prove target follows history: "
            f"historical_semester_max={hist_sem_max:g}, "
            f"target_semester_min={target_sem_min:g}"
        )

    # Preserve ordering if target contains >1 future semester.
    target_unique = np.sort(np.unique(ts))

    mapping = {
        semester: hist_block_max + 1.0 + i
        for i, semester in enumerate(target_unique)
    }

    repaired = np.asarray(
        [mapping[x] for x in ts],
        dtype=float,
    )

    if not np.isfinite(repaired).all():
        raise RuntimeError(
            "Internal target block repair produced non-finite values."
        )

    if float(np.min(repaired)) <= hist_block_max:
        raise RuntimeError(
            "Internal target block repair failed strict chronology."
        )

    target.blocks = repaired

    audit = [{
        "scope": "global",
        "source": "target_semester_rank_after_history",
        "historical_block_max": hist_block_max,
        "target_block_min": float(np.min(repaired)),
        "target_block_max": float(np.max(repaired)),
        "raw_hist_semester_max": hist_sem_max,
        "raw_target_semester_min": target_sem_min,
        "raw_target_semester_max": float(np.max(ts)),
        "target_semesters": "|".join(
            f"{x:g}" for x in target_unique
        ),
        "target_rows": int(len(ts)),
        "strict_after_history": True,
    }]

    # ---------------------------------------------------------------
    # Faculty-by-faculty confirmation.
    # ---------------------------------------------------------------
    for fi, faculty in enumerate(hist.faculty_names):
        hm = np.asarray(hist.faculty_idx) == fi
        tm = np.asarray(target.faculty_idx) == fi

        if not tm.any():
            continue

        hsf = hs[hm & np.isfinite(hs)]
        tsf = ts[tm]

        if not len(hsf):
            strict = None
            hmax = np.nan
        else:
            hmax = float(np.max(hsf))
            strict = bool(np.min(tsf) > hmax)

            if not strict:
                raise RuntimeError(
                    "Faculty-level raw chronology violation: "
                    f"faculty={faculty}, "
                    f"hist_semester_max={hmax:g}, "
                    f"target_semester_min={np.min(tsf):g}"
                )

        audit.append({
            "scope": "faculty",
            "faculty": faculty,
            "source": "target_semester",
            "historical_semester_max": hmax,
            "target_semester_min": float(np.min(tsf)),
            "target_semester_max": float(np.max(tsf)),
            "target_rows": int(tm.sum()),
            "strict_after_history": strict,
        })

    return target, audit