#!/usr/bin/env python3
"""Own offline algebraic model, not downloaded code or a DB test."""
import json, math, struct
from pathlib import Path
root = Path(__file__).resolve().parent.parent
evidence = json.loads((root / "storage-comparison.json").read_bytes())
rows = []
mismatches = []
for r in evidence["lanes"]["B"]["records"]:
    lex = r["original_lexeme"]
    if lex is None:
        rows.append({"case_id": r["case_id"], "column": r["column"], "input": None, "model": None})
        continue
    x = float(lex)
    whole = math.floor(x)
    fractional_scaled = (x - whole) * 100.0
    nearest_even_integer = round(fractional_scaled)
    before_clip = whole + nearest_even_integer / 100.0
    limit = 1000000.0 - 0.01
    clipped = min(max(before_clip, -limit), limit)
    physical32_candidate = struct.unpack("f", struct.pack("f", clipped))[0]
    mysqlnd_fixed2_candidate = float(format(physical32_candidate, ".2f"))
    decimal_projection_roundtrip = float(r["server_decimal30"])
    matches = (physical32_candidate == decimal_projection_roundtrip and
               mysqlnd_fixed2_candidate == r["native_value"])
    out = {"case_id": r["case_id"], "column": r["column"], "input": lex,
           "parse64": format(x, ".17g"), "fraction_scaled": format(fractional_scaled, ".17g"),
           "nearest_even_integer": nearest_even_integer, "before_clip": format(before_clip, ".17g"),
           "clipped": format(clipped, ".17g"), "model_storage32": format(physical32_candidate, ".17g"),
           "model_native_fixed2": mysqlnd_fixed2_candidate,
           "source_native": r["native_value"], "source_decimal30_float_roundtrip": decimal_projection_roundtrip,
           "model_range_warning": before_clip != clipped, "matches_existing_observation": matches}
    rows.append(out)
    if not matches:
        mismatches.append(out)
print(json.dumps({"status": "OFFLINE_MODEL_ONLY", "assumptions": [
    "binary64 parse and arithmetic", "rint nearest-even mode, not a measured FENV assertion",
    "post-quantization/clipping binary32 store", "mysqlnd fixed-decimal2 conversion",
    "decimal30 parsed-back double is a finite-vector observation, not physical DB bits"],
    "original_B_column_observations": len(rows),
    "non_NULL_observations": sum(x["input"] is not None for x in rows),
    "mismatches": mismatches, "rows": rows,
    "new_DB_queries": 0, "downloaded_external_code_executed": False},
    ensure_ascii=False, separators=(",", ":")))
