# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Run the fixed fixtures and integration properties on a user's port_adapter.py."""

import json
import math
import sys
from pathlib import Path

CASES = Path(__file__).with_name("cases.json")


def affine(y):
    x, z = y
    return (2 * x - z + 1, x + 3 * z - 2)


def nonlinear(y):
    x, z = y
    return (-x**2 + z, x * z - 2 * z)


def square(y):
    return (-0.4 * y[0] ** 2,)


def decay(y):
    return (-0.5 * y[0],)


def decay_quadratic_low(y):
    return (-0.5 * y[0] - 0.15 * y[0] ** 2,)


def decay_quadratic_high(y):
    return (-0.5 * y[0] - 0.4 * y[0] ** 2,)


def duffing(stiffness):
    return lambda y: (y[1], -y[0] - stiffness * y[0] ** 3)


RHS = {"affine": affine, "nonlinear": nonlinear, "square": square, "decay": decay,
       "decay-quadratic-low": decay_quadratic_low, "decay-quadratic-high": decay_quadratic_high,
       "duffing-0.5": duffing(0.5), "duffing-1": duffing(1.0), "duffing-2": duffing(2.0)}
OPERATIONS = ("step", "objective", "rk_derivatives", "flow_derivatives", "train", "order_conditions")


def classical_conditions(a, b, order):
    """The checker's own order-2..4 conditions, written as the rooted-tree sums."""
    s = len(b)
    A = [[a[i][j] if j < i else 0.0 for j in range(s)] for i in range(s)]
    c = [sum(row) for row in A]
    Ac = [sum(A[i][j] * c[j] for j in range(s)) for i in range(s)]
    tree = {
        2: [(sum(b[i] * c[i] for i in range(s)), 1 / 2)],
        3: [(sum(b[i] * c[i] ** 2 for i in range(s)), 1 / 3), (sum(b[i] * Ac[i] for i in range(s)), 1 / 6)],
        4: [(sum(b[i] * c[i] ** 3 for i in range(s)), 1 / 4),
            (sum(b[i] * c[i] * Ac[i] for i in range(s)), 1 / 8),
            (sum(b[i] * A[i][j] * c[j] ** 2 for i in range(s) for j in range(s)), 1 / 12),
            (sum(b[i] * A[i][j] * Ac[j] for i in range(s) for j in range(s)), 1 / 24)],
    }
    return [value - exact for q in range(2, order + 1) for value, exact in tree[q]]


def evaluate_case(case, ports):
    operation = case["operation"]
    port = ports[operation]
    if operation == "objective":
        return port(case["samples"], case["fit_weight"], case["order_weight"])
    if operation == "order_conditions":
        return port(case["a"], case["b"], case["order"])
    if operation == "train":
        samples = [dict(sample, rhs=RHS[sample["rhs"]]) for sample in case["samples"]]
        options = {"keep_order": case["keep_order"]} if "keep_order" in case else {}
        return port(samples, case["a0"], case["logits0"], case["order"], case["fit_weight"],
                    case["order_weight"], case["max_iters"], **options)
    rhs, state = RHS[case["rhs"]], case["state"]
    if operation == "step":
        return port(rhs, state, case["h"], case["a"], case["b"])
    if operation == "rk_derivatives":
        return port(rhs, state, case["a"], case["b"], case["order"])
    return port(rhs, state, case["order"])


def close(actual, expected, tol):
    if isinstance(expected, (tuple, list)):
        actual = tuple(actual)
        return len(actual) == len(expected) and all(close(x, y, tol) for x, y in zip(actual, expected))
    return math.isclose(actual, expected, rel_tol=0.0, abs_tol=tol)


def passes_case(case, ports):
    try:
        actual = evaluate_case(case, ports)
    except Exception:  # a port that raises fails the case
        return False
    if case.get("compare") == "loss and order conditions":
        # The optimum is a flat valley: compare the loss, and check the order conditions
        # of the returned tableau with the checker's own formulas.
        a, b, loss = actual
        held = max(map(abs, classical_conditions(a, b, case["keep_order"]))) <= 1e-12
        return held and close(loss, case["expected"][2], case["tol"])
    return close(actual, case["expected"], case["tol"])


def constant_rhs_check(step):
    calls = []

    def rhs(y):
        calls.append(tuple(y))
        return (2.0, -4.0)

    result = tuple(step(rhs, (1.0, 2.0), 0.25, ((), (2.0,)), (0.75, 0.25)))
    return result == (1.5, 1.0) and calls == [(1.0, 2.0), (2.0, 0.0)]


def square_order_check(step):
    errors = []
    for n_steps in (25, 50):
        state = (2.0,)
        h = 1.0 / n_steps
        for _ in range(n_steps):
            state = step(square, state, h, ((), (2.0,)), (0.75, 0.25))
        errors.append(abs(state[0] - 2.0 / 1.8))
    return errors[1] > 0 and 7.5 < errors[0] / errors[1] < 8.6


def run_checks(ports, out=print):
    data = json.loads(CASES.read_text())
    failures = 0
    for case in data["cases"]:
        passed = passes_case(case, ports)
        out(f"{'PASS' if passed else 'FAIL'} {case['name']}")
        failures += not passed
    for check, name in ((constant_rhs_check, "consistent constant-RHS step with two stages"),
                        (square_order_check, "third-order convergence on the square family")):
        passed = check(ports["step"])
        out(f"{'PASS' if passed else 'FAIL'} {name}")
        failures += not passed
    out(f"{len(data['cases']) + 2 - failures} passed, {failures} failed")
    return failures


if __name__ == "__main__":
    sys.path.insert(0, str(Path.cwd()))
    adapter_path = Path.cwd() / "port_adapter.py"
    if not adapter_path.is_file():
        raise SystemExit("Create port_adapter.py in the working directory. "
                         "See checks/cases.json for the five signatures.")
    import port_adapter

    sys.exit(int(run_checks({name: getattr(port_adapter, name) for name in OPERATIONS}) != 0))
