#!/usr/bin/env python3
"""mpmath O3 for mechanical.statics.incline_slip_or_tip."""
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):
    mu = pick(inputs, "mu", "mu_s")
    b = pick(inputs, "b", "width")
    h = pick(inputs, "h", "height")
    theta_slip = mp.atan(mu) * (180 / mp.pi)
    theta_tip = mp.atan(b / h) * (180 / mp.pi)
    scale = 1 + abs(theta_slip) + abs(theta_tip)
    mode = "either" if abs(theta_slip - theta_tip) <= mp.mpf("1e-8") * scale else ("slip" if theta_slip < theta_tip else "tip")
    theta = theta_tip if mode == "tip" else theta_slip
    return {"theta_deg": theta, "theta_slip_deg": theta_slip, "theta_tip_deg": theta_tip, "mode": mode}


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-either", {"mu": "1", "b": "2", "h": "2"}, "either"),
        row("o3-slip", {"mu": "0.25", "b": "2", "h": "1"}, "slip"),
        row("o3-tip", {"mu": "0.8", "b": "1", "h": "2"}, "tip"),
        row("o3-alias", {"mu_s": "0.5", "width": "3", "height": "3"}, "alias"),
        row("o3-awkward", {"mu": "0.37", "b": "2.5", "h": "1.8"}, "awkward"),
        row("o3-steep", {"mu": "0.1", "b": "0.5", "h": "4"}, "steep"),
        row("o3-flat", {"mu": "0.9", "b": "4", "h": "0.5"}, "flat"),
        row("o3-mild", {"mu": "0.3", "b": "1.5", "h": "1.5"}, "mild"),
    ]
    table = {
        "family": "incline_slip_or_tip",
        "generator_id": "incline-slip-or-tip-mpmath-o3",
        "generator_version": "1.0.0",
        "seed": "20260927.incline-slip-or-tip-o3",
        "mpmath_dps": 80,
        "precision_bits": int(80 * math.log2(10)),
        "library": f"mpmath {mp.__version__}",
        "notes": "θ_slip = arctan(μ), θ_tip = arctan(b/h); θ is the smaller. + O3 mpmath tabulated θ.",
        "vectors": vectors,
    }
    dest = here / "incline-slip-or-tip-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 / "incline-slip-or-tip-o3-tables.json")
    shutil.copy2(Path(__file__), public / "generate-incline-slip-or-tip-o3.py")
    print(f"wrote {dest} ({len(vectors)} vectors)")

if __name__ == "__main__":
    main()
