#!/usr/bin/env python3
"""mpmath O3 for mechanical.statics.beam_deflection."""
from __future__ import annotations
import json, math, shutil
from pathlib import Path
import mpmath as mp

def pick(inputs, *keys):
    for key in keys:
        if key in inputs and inputs[key] not in (None, ""):
            return mp.mpf(str(inputs[key]))
    return None


def compute(inputs):
    P = pick(inputs, "P", "load")
    L = pick(inputs, "L", "span")
    E = pick(inputs, "E", "modulus")
    I = pick(inputs, "I", "Ix")
    delta = (P * L ** 3) / (48 * E * I)
    return {"delta": delta, "P": P, "L": L, "E": E, "I": I}


def row(vid, inputs, kind):
    out = compute(inputs)
    packed = {"id": vid, "kind": kind, "inputs": inputs}
    for k, v in out.items():
        if isinstance(v, str):
            packed[k] = v
        else:
            packed[f"{k}_f64"] = float(v)
            packed[f"{k}_decimal"] = mp.nstr(v, 40, strip_zeros=False)
    return packed

def main():
    mp.mp.dps = 80
    here = Path(__file__).resolve().parent
    vectors = [
        row("o3-check", {"P": "480", "L": "2", "E": "1", "I": "1"}, "check"),
        row("o3-SI", {"P": "1000", "L": "4", "E": "200e9", "I": "1e-5"}, "SI"),
        row("o3-alias", {"load": "960", "span": "2", "modulus": "1", "Ix": "1"}, "alias"),
        row("o3-awkward", {"P": "137", "L": "3.5", "E": "2.1e5", "I": "0.83"}, "awkward"),
        row("o3-neg", {"P": "-480", "L": "2", "E": "1", "I": "1"}, "signed"),
        row("o3-small", {"P": "10", "L": "1", "E": "1000", "I": "0.01"}, "small"),
        row("o3-stiff", {"P": "5000", "L": "3", "E": "210e9", "I": "2e-4"}, "stiff"),
        row("o3-long", {"P": "200", "L": "8", "E": "70e9", "I": "5e-5"}, "long"),
    ]
    table = {
        "family": "beam_deflection",
        "generator_id": "beam-deflection-mpmath-o3",
        "generator_version": "1.0.0",
        "seed": "20260927.beam-deflection-o3",
        "mpmath_dps": 80,
        "precision_bits": int(80 * math.log2(10)),
        "library": f"mpmath {mp.__version__}",
        "notes": "Simply supported midspan δ = P L³/(48 E I); + O3 mpmath tabulated δ.",
        "vectors": vectors,
    }
    dest = here / "beam-deflection-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 / "beam-deflection-o3-tables.json")
    shutil.copy2(Path(__file__), public / "generate-beam-deflection-o3.py")
    print(f"wrote {dest} ({len(vectors)} vectors)")

if __name__ == "__main__":
    main()
