# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check fixture freshness, reference compatibility, and sensitivity to porting mistakes."""

import json
import math
import sys
import warnings
from pathlib import Path

# The two-stage fixture fit matches second order only approximately; the reference rightly warns,
# and the mutants below inherit that. The warning itself is tested in check_order_target.py.
warnings.filterwarnings("ignore", message="the fitted tableau matches", category=RuntimeWarning)

ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT / "checks"), str(ROOT / "reference")]
import check_port
from learned_rk import objective, squared_distance, step
from make_cases import REFERENCE, build
from taylor_series import cos, exp, sin
from train_rk import _project, classical_order_conditions, flow_derivatives, rk_derivatives, train


def adam_train(samples, a0, logits0, order, fit_weight, order_weight, max_iters, keep_order=None,
               iterations=3000, rate=0.01):
    """A first-order port, as in the paper: Adam on the objective, its own iteration count.

    With keep_order it uses projected gradient descent with backtracking instead, since
    Adam's momentum does not combine well with projection onto the order conditions."""
    starts = [i * (i - 1) // 2 for i in range(len(logits0) + 1)]
    params = [x for row in a0 for x in row] + list(logits0)
    tasks = [dict(s, target_derivatives=flow_derivatives(s["rhs"], s["state"], order)) for s in samples]

    def tableau(values):
        a = tuple(tuple(values[i:j]) for i, j in zip(starts, starts[1:]))
        logits = values[starts[-1]:]
        weights = [math.exp(z - max(logits)) for z in logits]
        return a, tuple(w / sum(weights) for w in weights)

    def loss(values):
        a, b = tableau(values)
        for task in tasks:
            if fit_weight:
                task["prediction"] = step(task["rhs"], task["state"], task["h"], a, b)
            task["prediction_derivatives"] = rk_derivatives(task["rhs"], task["state"], a, b, order)
        return objective(tasks, fit_weight, order_weight)

    if keep_order is not None:
        return _projected_descent(params, tableau, loss, keep_order, iterations)
    first, second = [0.0] * len(params), [0.0] * len(params)
    for t in range(1, (iterations if max_iters is None else max_iters) + 1):
        grad = []
        for j in range(len(params)):
            up, down = params.copy(), params.copy()
            up[j] += 1e-6
            down[j] -= 1e-6
            grad.append((loss(up) - loss(down)) / 2e-6)
        for j, g in enumerate(grad):
            first[j] = 0.9 * first[j] + 0.1 * g
            second[j] = 0.999 * second[j] + 0.001 * g * g
            params[j] -= rate * first[j] / (1 - 0.9**t) / (math.sqrt(second[j] / (1 - 0.999**t)) + 1e-12)
    return (*tableau(params), loss(params))


def _projected_descent(params, tableau, loss, keep_order, iterations):
    """First-order fit on the order-condition set: gradient step, project back, backtrack."""
    def project(values):
        return _project(lambda v: classical_order_conditions(*tableau(v), keep_order), values)

    params, rate = project(params), 1e-2
    current = loss(params)
    for _ in range(iterations):
        grad = []
        for j in range(len(params)):
            up, down = params.copy(), params.copy()
            up[j] += 1e-6
            down[j] -= 1e-6
            grad.append((loss(up) - loss(down)) / 2e-6)
        while rate > 1e-12:
            trial = project([p - rate * g for p, g in zip(params, grad)])
            value = loss(trial) if trial is not None else math.inf
            if value < current:
                params, current, rate = trial, value, rate * 2
                break
            rate /= 2
        else:
            break
    return (*tableau(params), current)


def wrong_order_constant(a, b, order):
    values = classical_order_conditions(a, b, order)
    return [values[0], values[1] + 1 / 3 - 1 / 6, *values[2:]] if order >= 3 else values


def ignore_keep_order(samples, a0, logits0, order, fit_weight, order_weight, max_iters, keep_order=None):
    return REFERENCE["train"](samples, a0, logits0, order, fit_weight, order_weight, max_iters)


def fit_then_project(samples, a0, logits0, order, fit_weight, order_weight, max_iters, keep_order=None):
    """Fit without the constraint, then move the result onto the order conditions."""
    a, b, _ = REFERENCE["train"](samples, a0, logits0, order, fit_weight, order_weight, max_iters)
    if keep_order is None:
        return a, b, _
    starts = [i * (i - 1) // 2 for i in range(len(b) + 1)]

    def tableau(values):
        rows = tuple(tuple(values[i:j]) for i, j in zip(starts, starts[1:]))
        logits = [*values[starts[-1]:], 0.0]
        weights = [math.exp(z - max(logits)) for z in logits]
        return rows, tuple(w / sum(weights) for w in weights)

    values = [x for row in a for x in row] + [math.log(w / b[-1]) for w in b[:-1]]
    values = _project(lambda v: classical_order_conditions(*tableau(v), keep_order), values)
    a, b = tableau(values)
    loss = REFERENCE["train"](samples, a, [math.log(w) for w in b], order, fit_weight, order_weight, 0)[2]
    return a, b, loss


def only_previous_stage(rhs, state, h, a, b):
    rows = [([0.0] * (len(row) - 1) + [row[-1]]) if row else [] for row in a]
    return step(rhs, state, h, rows, b)


def double_step_scaling(rhs, state, h, a, b):
    return step(rhs, state, h, a, [h * weight for weight in b])


def reverse_weights(rhs, state, h, a, b):
    return step(rhs, state, h, a, list(reversed(b)))


def pooled_baseline(samples, fit_weight, order_weight):
    loss = objective(samples, 0.0, order_weight)
    if fit_weight:
        model = sum(squared_distance(s["target"], s["prediction"]) for s in samples)
        baseline = sum(squared_distance(s["target"], s["baseline"]) for s in samples)
        loss += fit_weight * model / baseline
    return loss


def use_taylor_coefficients(samples, fit_weight, order_weight):
    def divide_factorials(derivatives):
        return [[value / math.factorial(k) for value in vector]
                for k, vector in enumerate(derivatives, start=1)]

    converted = [dict(s, target_derivatives=divide_factorials(s["target_derivatives"]),
                      prediction_derivatives=divide_factorials(s["prediction_derivatives"]))
                 for s in samples]
    return objective(converted, fit_weight, order_weight)


def shifted_flow_derivatives(rhs, state, order):
    return ((0.0,) * len(state), *flow_derivatives(rhs, state, order - 1))


def rk_coefficients(rhs, state, a, b, order):
    return tuple(tuple(x / math.factorial(k) for x in vector)
                 for k, vector in enumerate(rk_derivatives(rhs, state, a, b, order), start=1))


def unchanged_logits(samples, a0, logits0, order, fit_weight, order_weight, max_iters, **options):
    a, _, loss = train(samples, a0, logits0, order, fit_weight, order_weight, max_iters, **options)
    return a, logits0, loss


def skip_order_term(samples, a0, logits0, order, fit_weight, order_weight, max_iters, **options):
    return train(samples, a0, logits0, order, fit_weight, 0.0, max_iters, **options)


def skip_finite_step_term(samples, a0, logits0, order, fit_weight, order_weight, max_iters, **options):
    return train(samples, a0, logits0, order, 0.0, order_weight, max_iters, **options)


def exact_decay_fit(case):
    """Independent two-variable least squares using the polynomial form of the task."""
    # For scalar quadratic f, the step is y+h*f + u*h²*f'*f + v*h³*f''*f²/2,
    # with u=b2*a21, v=b2*a21². All residuals are affine in (u, v).
    q_values = {"decay": 0.0, "decay-quadratic-high": 0.4, "decay-quadratic-low": 0.15}
    rows = []
    scale_order = math.sqrt(case["order_weight"])
    for task in case["samples"]:
        q, y, h = q_values[task["rhs"]], task["state"][0], task["h"]
        f, fp, fpp = -0.5 * y - q * y * y, -0.5 - 2 * q * y, -2 * q
        decay = math.exp(-0.5 * h)
        exact = y * decay / (1 + 2 * q * y * (1 - decay))
        stage = y + h * f
        heun = y + h * (f - 0.5 * stage - q * stage**2) / 2
        assert check_port.close([exact, heun], task["target"] + task["baseline"], 1e-14)
        scale = math.sqrt(case["fit_weight"]) / abs(task["target"][0] - task["baseline"][0])
        rows.append((scale * h**2 * fp * f, scale * h**3 * fpp * f**2 / 2,
                     scale * (y + h * f - task["target"][0])))
        rows.append((scale_order * 2 * fp * f, 0.0, -scale_order * fp * f))
        rows.append((0.0, scale_order * 3 * fpp * f**2, -scale_order * (fpp * f**2 + fp**2 * f)))
    x, y, r = zip(*rows)
    xx, xy, yy = sum(v * v for v in x), sum(u * v for u, v in zip(x, y)), sum(v * v for v in y)
    xr, yr = sum(u * v for u, v in zip(x, r)), sum(u * v for u, v in zip(y, r))
    determinant = xx * yy - xy * xy
    u = (xy * yr - yy * xr) / determinant
    v = (xy * xr - xx * yr) / determinant
    a21, b2 = v / u, u**2 / v
    loss = sum((x * u + y * v + r) ** 2 for x, y, r in rows) / len(case["samples"])
    return ((), (a21,)), (1.0 - b2, b2), loss


if __name__ == "__main__":
    stored = json.loads(check_port.CASES.read_text())
    regenerated = json.loads(json.dumps(build()))
    assert {k: v for k, v in stored.items() if k != "cases"} == {k: v for k, v in regenerated.items() if k != "cases"}
    for old, new in zip(stored["cases"], regenerated["cases"], strict=True):
        assert {k: v for k, v in old.items() if k != "expected"} == {k: v for k, v in new.items() if k != "expected"}
        assert check_port.close(old["expected"], new["expected"], min(old["tol"], 1e-8))
    print("PASS stored fixtures match make_cases.py")
    assert check_port.run_checks(REFERENCE) == 0, "reference failed port checks"

    # Direct arithmetic with ratios (1/4, 5/8) and derivative residuals (7, 5).
    loss = next(case for case in stored["cases"] if case["name"] == "weighted per-sample loss and Taylor penalty")
    assert math.isclose(loss["expected"], 1.625, rel_tol=0.0, abs_tol=1e-12)
    print("PASS weighted objective matches hand calculation")

    training = next(case for case in stored["cases"] if case.get("max_iters", 0) != 0)
    assert training["max_iters"] is None, "the fitted case must not impose an iteration budget"
    assert check_port.close(training["expected"], exact_decay_fit(training), 1e-8)
    print("PASS fitted tableau and loss match an independent least-squares optimum")
    adam_log = []
    assert check_port.run_checks(dict(REFERENCE, train=adam_train), out=adam_log.append) == 0, adam_log
    print("PASS a first-order (Adam) port with its own iteration count passes every port check")

    import random
    rng = random.Random(11)
    for stages, order in ((2, 2), (3, 3), (4, 4), (5, 4)):
        for _ in range(50):
            a = [[rng.uniform(-1, 1) for _ in range(i)] for i in range(stages)]
            raw = [rng.uniform(0.1, 1) for _ in range(stages)]
            b = [x / sum(raw) for x in raw]
            assert check_port.close(classical_order_conditions(a, b, order),
                                    check_port.classical_conditions(a, b, order), 1e-14)
    print("PASS order conditions agree with the checker's rooted-tree sums on 200 random tableaus")

    nonlinear = next(case for case in stored["cases"] if case["operation"] == "flow_derivatives")
    expected_vectors = [(-41 / 16, -1 / 8), (283 / 32, -5 / 4), (-5803 / 128, 43 / 8)]
    assert check_port.close(nonlinear["expected"], expected_vectors, 1e-12)
    print("PASS coupled flow derivatives match direct chain-rule arithmetic")

    def transcendental_rhs(y):
        x, z, w = y
        return sin(z), cos(x), exp(x) / (1 + w)

    assert check_port.close(flow_derivatives(transcendental_rhs, (0.0, 0.0, 0.0), 3),
                            ((0.0, 1.0, 1.0), (1.0, 0.0, -1.0), (0.0, 0.0, 4.0)), 1e-12)
    print("PASS flow through series sine, cosine, exponential and division")

    for label, operation, mutant in (
        ("only the immediately previous stage", "step", only_previous_stage),
        ("multiply final weights by h twice", "step", double_step_scaling),
        ("reverse output weights", "step", reverse_weights),
        ("pool baseline errors before dividing", "objective", pooled_baseline),
        ("compare Taylor coefficients instead of derivatives", "objective", use_taylor_coefficients),
        ("forget the factorial in the RK derivatives", "rk_derivatives", rk_coefficients),
        ("shift the exact flow derivative indices", "flow_derivatives", shifted_flow_derivatives),
        ("skip softmax on logits", "train", unchanged_logits),
        ("skip the order term during training", "train", skip_order_term),
        ("skip the finite-step term during training", "train", skip_finite_step_term),
        ("use 1/3 instead of 1/6 for the b.Ac condition", "order_conditions", wrong_order_constant),
        ("ignore keep_order during training", "train", ignore_keep_order),
        ("fit without keep_order, then project onto the conditions", "train", fit_then_project),
    ):
        ports = dict(REFERENCE, **{operation: mutant})
        caught = [case["name"] for case in stored["cases"]
                  if not check_port.passes_case(case, ports)]
        assert caught, f"fixed cases missed mutant {label}"
        print(f"PASS caught {label} ({len(caught)} fixed cases)")
