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

Independent of Node/V8 binary64 and of the IUT. Tabulated field is u_B:
rectangular a/√3, triangular a/√6. Not GUM combination, not trapezoidal.

80 dps, round-to-nearest binary64. Does not pin a gmpy2 backend.

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

import json
import math
import shutil
from pathlib import Path

import mpmath as mp

DPS = 80
GENERATOR_ID = "type-b-mpmath-o3"
GENERATOR_VERSION = "1.0.0"
SEED = "20260916.type-b-o3"


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


def type_b(a, dist: str) -> dict:
    a = mp.mpf(a)
    if dist == "triangular":
        u = a / mp.sqrt(6)
    else:
        u = a / mp.sqrt(3)
    return {
        "u_B_f64": f64(u),
        "u_B_decimal": mp.nstr(u, 40, strip_zeros=False),
        "a_f64": f64(a),
        "a_decimal": mp.nstr(a, 40, strip_zeros=False),
    }


def row(vid: str, inputs: dict, extra: dict, *, kind: str) -> dict:
    return {"id": vid, "kind": kind, "inputs": inputs, **extra}


def vectors() -> list[dict]:
    return [
        row("o3-rect", {"a": 3, "distribution": "rectangular"}, type_b(3, "rectangular"), kind="rectangular"),
        row("o3-tri", {"a": 3, "distribution": "triangular"}, type_b(3, "triangular"), kind="triangular"),
        row("o3-default", {"a": 3}, type_b(3, "rectangular"), kind="default-rectangular"),
        row("o3-uniform", {"a": 3, "distribution": "uniform"}, type_b(3, "rectangular"), kind="uniform-alias"),
        row("o3-one", {"a": 1, "distribution": "rectangular"}, type_b(1, "rectangular"), kind="unit-rect"),
        row("o3-half", {"a": 0.5, "distribution": "triangular"}, type_b("0.5", "triangular"), kind="half-tri"),
        row("o3-scale", {"a": 6, "distribution": "rectangular"}, type_b(6, "rectangular"), kind="scale"),
        row("o3-hw", {"half_width": 3}, type_b(3, "rectangular"), kind="half-width-alias"),
    ]


def main() -> None:
    mp.mp.dps = DPS
    here = Path(__file__).resolve().parent
    table = {
        "family": "type_b_uncertainty",
        "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": "Type B u_B only. Independent of Node Math and the IUT. Trapezoidal is not tabulated.",
        "vectors": vectors(),
    }
    dest = here / "type-b-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 / "type-b-o3-tables.json")
    shutil.copy2(Path(__file__), public / "generate-type-b-o3.py")
    print(f"wrote {dest} ({len(table['vectors'])} vectors)")


if __name__ == "__main__":
    main()
