"""Measure real numeric crossings against an exact rational oracle.

Each value is defined exactly (as a Fraction), sent through a real encoding, decoded,
and compared exactly. Claim tested: "relative error stays within the consumer's tolerance".
Predictor (the contract rule): pass if the format's nominal relative precision <= tolerance.
That rule ignores range limits, subnormals and text formatting, which is where it fails.

Writes numeric_crossings.json.
"""
from __future__ import annotations

import hashlib
import json
import math
from fractions import Fraction
from pathlib import Path

import numpy as np

VALUES = [  # (label, exact value)
    ("Sensor reading 0.1", Fraction(1, 10)),
    ("One third", Fraction(1, 3)),
    ("Speed of light, m/s", Fraction(299792458)),
    ("Avogadro constant", Fraction(602214076) * 10 ** 15),
    ("Price 19.99", Fraction(1999, 100)),
    ("Angle 359.9999 deg", Fraction(3599999, 10000)),
    ("Dose 0.00002 g", Fraction(2, 100000)),
    ("Tiny weight 3e-8", Fraction(3, 10 ** 8)),
    ("Sample count 70,000", Fraction(70000)),
    ("Order id 16,777,217", Fraction(16777217)),
    ("Account id 9,007,199,254,740,993", Fraction(9007199254740993)),
    ("Ratio 22/7", Fraction(22, 7)),
    ("Gain 0.7071", Fraction(7071, 10000)),
    ("Latitude -33.8688", Fraction(-338688, 10000)),
]
TOLS = [Fraction(1, 10 ** 3), Fraction(1, 10 ** 6)]


def f16(x): return Fraction(float(np.float16(float(x))))
def f32(x): return Fraction(float(np.float32(float(x))))
def f64(x): return Fraction(float(x))


def bf16(x):
    b = np.array([float(x)], dtype=np.float32).view(np.uint32)
    lsb = (b >> 16) & 1
    b = ((b + 0x7FFF + lsb) >> 16) << 16  # round to nearest even
    return Fraction(float(b.view(np.float32)[0]))


def json64(x): return Fraction(json.loads(json.dumps(float(x))))
def text6(x): return Fraction(float("%.6g" % float(x)))


def int8(x):  # symmetric 8-bit quantisation over a declared range of [-1, 1]
    q = max(-127, min(127, round(float(x) * 127)))
    return Fraction(q, 127)


FORMATS = [  # (label, fn, nominal relative precision the contract rule believes)
    ("float16", f16, Fraction(1, 2 ** 11)),
    ("bfloat16", bf16, Fraction(1, 2 ** 8)),
    ("float32", f32, Fraction(1, 2 ** 24)),
    ("JSON float64", json64, Fraction(1, 2 ** 53)),
    ("Text %.6g", text6, Fraction(5, 10 ** 6)),
    ("int8 over [-1,1]", int8, Fraction(1, 254)),
]


def rel_err(exact: Fraction, got) -> float:
    if isinstance(got, Exception):
        return math.inf
    if exact == 0:
        return float(abs(got))
    return float(abs(got - exact) / abs(exact))


def main():
    records = []
    for vlabel, v in VALUES:
        for flabel, fn, eps in FORMATS:
            try:
                got = fn(v)
            except (OverflowError, ValueError) as e:  # inf/nan cannot become a Fraction
                got = e
            err = rel_err(v, got)
            for tol in TOLS:
                records.append({
                    "id": f"N-{len(records) + 1:03d}", "substrate": "numeric", "value": vlabel, "format": flabel,
                    "tolerance": float(tol), "nominal_precision": float(eps),
                    "relative_error": err if math.isfinite(err) else "inf",
                    "holds": bool(math.isfinite(err) and err <= tol),
                    "contract_says_safe": eps <= tol,
                })
    meta = {"oracle": "exact rational arithmetic (Python fractions.Fraction)", "numpy": np.__version__,
            "claim": "relative error <= declared tolerance", "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
    Path("numeric_crossings.json").write_text(json.dumps({"meta": meta, "records": records}, indent=1))
    n = len(records); h = sum(r["holds"] for r in records)
    safe = [r for r in records if r["contract_says_safe"]]
    print(f"{n} crossings, {h} hold; contract approves {len(safe)}, of which {sum(not r['holds'] for r in safe)} fail")
    for r in safe:
        if not r["holds"]:
            print("  contract wrong:", r["value"], r["format"], r["tolerance"], r["relative_error"])


if __name__ == "__main__":
    main()
