#!/usr/bin/env python3
"""Intuitionist Edu · Project 01 · synthetic check (Python version).

Three hand-written readers of ordered-outcome model parameters, run on the
synthetic fixtures in fixtures.json. This demonstrates a check, not an AI
agent: it calls no model and uses no study data. Standard library only.

    python3 check.py                # all fixtures, all readers
    python3 check.py fixtures.json  # explicit path

Readers
  positional  takes slopes by position (first) and cut points by position
              (last), and tests the raw values. The shared assumption.
  always      reads by name, but always applies the log-increment conversion.
              The lesson repeated without checking.
  aware       reads by name, converts only when the stored form is declared
              as increments, and stops when it is not declared.

"increments" means: first cut point, then log of each gap. statsmodels 0.15.0
OrderedModel stores thresholds this way; its transform_threshold_params turns
them into cut points. Other libraries and versions may differ, so check the
documentation of the one you use.
"""
import json
import math
import sys
from pathlib import Path

READERS = ["positional", "always", "aware"]
TOL = 1e-4


def from_increments(stored):
    out, acc = [], 0.0
    for i, v in enumerate(stored):
        acc = v if i == 0 else acc + math.exp(v)
        out.append(round(acc, 6))
    return out


def increasing(xs):
    return all(b > a for a, b in zip(xs, xs[1:]))


def read(reader, fx):
    params = fx["params"]
    np_, nt = len(fx["predictors"]), len(fx["thresholds"])
    if reader == "positional":
        slopes = {name: params[i][1] for i, name in enumerate(fx["predictors"])}
        cut = [v for _, v in params[-nt:]]
    else:
        by_name = dict((k, v) for k, v in params)
        slopes = {name: by_name[name] for name in fx["predictors"]}
        stored = [by_name[t] for t in fx["thresholds"]]
        if reader == "always" or fx["storage"] == "increments":
            cut = from_increments(stored)
        elif fx["storage"] == "cutpoints":
            cut = list(stored)
        else:
            return {"slopes": slopes, "cutpoints": None, "verdict": "stopped"}
    return {"slopes": slopes, "cutpoints": cut, "verdict": "pass" if increasing(cut) else "fail"}


def assess(fx, r):
    """Compare a reading with the fixture's known truth (possible only because the data are synthetic)."""
    truth_ok = increasing(fx["truth"]["cutpoints"])
    if r["verdict"] == "stopped":
        return "Stopped and asked"
    slopes_ok = all(abs(r["slopes"][k] - v) <= TOL for k, v in fx["truth"]["slopes"].items())
    cut_ok = len(r["cutpoints"]) == len(fx["truth"]["cutpoints"]) and all(
        abs(a - b) <= TOL for a, b in zip(r["cutpoints"], fx["truth"]["cutpoints"]))
    if r["verdict"] == "fail" and truth_ok:
        return "False alarm"
    if r["verdict"] == "pass" and not truth_ok:
        return "Missed a real problem"
    if r["verdict"] == "pass" and not (slopes_ok and cut_ok):
        return "Passed, but read wrong"
    if r["verdict"] == "fail":
        return "Caught a real problem"
    if fx["storage"] is None:
        return "Right by assumption"
    return "Correct pass"


def main(path):
    data = json.loads(Path(path).read_text())
    for fx in data["fixtures"]:
        print(f"\n{fx['title']}  [{fx['id']}]")
        for reader in READERS:
            r = read(reader, fx)
            cut = "—" if r["cutpoints"] is None else ", ".join(f"{v:.3f}" for v in r["cutpoints"])
            slopes = ", ".join(f"{k} {v:.2f}" for k, v in r["slopes"].items())
            print(f"  {reader:<11} {r['verdict']:<8} {assess(fx, r):<23} cut points: {cut} | slopes: {slopes}")


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).with_name("fixtures.json"))
