#!/usr/bin/env python3
"""Precompute mpmath high-precision O3 vectors for engineering.tolerance.worst_case.

Independent of Node/V8 binary64 and of the IUT. stack = Σ|Tᵢ|, stack_rss = √Σ Tᵢ²
at 80 dps; round-to-nearest binary64. Does not pin a gmpy2 backend.

Re-run: python3 scripts/lib/cvp/oracles/generate-worst-case-o3.py
"""
from __future__ import annotations

import json
import math
import shutil
from pathlib import Path

import mpmath as mp

DPS = 80
GENERATOR_ID = "worst-case-mpmath-o3"
GENERATOR_VERSION = "1.0.0"
SEED = "20260916.wca-o3"


def f64(x: mp.mpf) -> float:
    return float(x)


def mag(tols: list[float]) -> dict:
    abs_t = [abs(mp.mpf(t)) for t in tols]
    stack = sum(abs_t, mp.mpf(0))
    stack_rss = mp.sqrt(sum((t * t for t in abs_t), mp.mpf(0)))
    return {
        "stack_f64": f64(stack),
        "stack_decimal": mp.nstr(stack, 40, strip_zeros=False),
        "stack_rss_f64": f64(stack_rss),
        "stack_rss_decimal": mp.nstr(stack_rss, 40, strip_zeros=False),
        "n": len(tols),
    }


def row(vid: str, inputs: dict, tols: list[float], *, kind: str) -> dict:
    return {"id": vid, "kind": kind, "inputs": inputs, **mag(tols)}


def vectors() -> list[dict]:
    return [
        row("o3-tol-fields", {"tol1": 0.1, "tol2": 0.2, "tol3": 0.1}, [0.1, 0.2, 0.1], kind="fields"),
        row("o3-array", {"tolerances": [0.1, 0.2, 0.1], "unit": "mm"}, [0.1, 0.2, 0.1], kind="canonical-array"),
        row("o3-signed", {"tol1": 0.1, "tol2": -0.2, "tol3": 0.3}, [0.1, -0.2, 0.3], kind="signed-rest"),
        row("o3-one", {"tolerances": [0.2]}, [0.2], kind="single"),
        row("o3-zeros", {"tol": [0, 0, 0]}, [0, 0, 0], kind="zeros"),
        row("o3-small", {"tolerances": [1e-12, 2e-12]}, [1e-12, 2e-12], kind="small"),
        row("o3-large", {"tolerances": [1e6, 2e6]}, [1e6, 2e6], kind="large"),
        row("o3-pythag", {"tolerances": [0.3, 0.4]}, [0.3, 0.4], kind="pythagorean"),
    ]


def main() -> None:
    mp.mp.dps = DPS
    here = Path(__file__).resolve().parent
    table = {
        "family": "worst_case",
        "generator_id": GENERATOR_ID,
        "generator_version": GENERATOR_VERSION,
        "seed": SEED,
        "mpmath_dps": DPS,
        "precision_bits": int(DPS * math.log2(10)),
        "library": f"mpmath {mp.__version__}",
        "notes": "1-D magnitude Σ|Tᵢ| and RSS √Σ Tᵢ²; independent of Node Math and the IUT.",
        "vectors": vectors(),
    }
    dest = here / "worst-case-o3-tables.json"
    dest.write_text(json.dumps(table, indent=2) + "\n", encoding="utf-8")
    public = here.parents[3] / "public/developers/cvp/reproduce"
    public.mkdir(parents=True, exist_ok=True)
    shutil.copy2(dest, public / "worst-case-o3-tables.json")
    shutil.copy2(Path(__file__), public / "generate-worst-case-o3.py")
    print(f"wrote {dest} ({len(table['vectors'])} vectors)")


if __name__ == "__main__":
    main()
