"""Perception track, version 1: compile records into deck cards in the crossing desk's card format, with a label on
every card, and write MANIFEST.json with the SHA-256 of every file. Frozen once published: a new measurement is a
new version, not an edit.
Usage: python3 build_deck.py <dir>"""
import hashlib, json, os, sys

LOOKS = {
    "muller_lyer": "top shaft looks longer", "ponzo": "upper bar looks longer",
    "ebbinghaus": "right disc looks larger", "contrast": "left square looks lighter",
    "necker": "lower-left face looks in front", "schroeder": "stairs look seen from above",
}
NAMES = {"muller_lyer": "Mueller-Lyer", "ponzo": "Ponzo", "ebbinghaus": "Ebbinghaus", "contrast": "Simultaneous contrast",
         "necker": "Necker cube", "schroeder": "Reversible staircase"}
HARM = "Not dealt in the game: this deck is a reference gallery, so harm is unused and set to the game's floor."


def result(r):
    if r["class"] == "bistable":
        return f"UNRESOLVED: {r['edges']} edges in one stroke width and colour, none broken, equally dark; nothing in the drawing decides depth"
    m, u = r["measured"], r["unit"]
    return f"{r['verdict'].replace('_', ' ')}: measured " + ", ".join(f"{k} {v:g} {u}" for k, v in m.items()) + f" (difference {r['difference']:g}, tolerance {r['tolerance']:g})"


def label(r, meta):
    if r["class"] == "bistable":
        return {"is": f"A {NAMES[r['kind']]} line drawing that supports two depth readings, rendered by cairosvg {meta['cairosvg']}, with no stroke, occlusion or shading cue favouring either (checked from the pixels).",
                "isnt": "Evidence about which reading people see first or more often, or a claim that the readings are equally likely for any viewer.",
                "stops": "The claim asks for a fact the drawing does not contain, so the correct answer is UNRESOLVED; the desk's true/false card format can show that only as not holding.",
                "harm": HARM}
    return {"is": f"A {NAMES[r['kind']]} figure drawn by this deck's generator with a set true difference of {r['delta']:+.0%} at scale {r['scale']}, rendered by cairosvg {meta['cairosvg']} and measured from its pixels with fins, surrounds and rails removed.",
            "isnt": "A measurement of how anyone perceives it: no viewer was tested. 'Looks' is the direction this construction is documented to push most viewers, not an observation.",
            "stops": "The true difference was chosen by the author on a fixed grid, so how often the look is wrong here reflects that grid, not perception. One construction, one size, one renderer; differences below 1 pixel or 1 grey level cannot be resolved.",
            "harm": HARM}


def main(d):
    rec = json.load(open(f"{d}/records.json")); meta = rec["meta"]
    cards = []
    for r in rec["records"]:
        cards.append({"id": r["id"], "track": f"Perception · {r['class']}", "claim": r["claim"], "read": LOOKS[r["kind"]], "unit": "default reading",
                      "gauge": 100, "rule": True, "holds": r["holds"], "verdict": r["verdict"], "harm": 0.3, "result": result(r), "undeclared": None,
                      "kind": r["kind"], "image": f"perception-v1/svg/{r['id']}.svg", "label": label(r, meta)})
    files = ["generate.py", "measure.py", "build_deck.py", "stimuli.json", "records.json", "README.md"] + [f"svg/{x}" for x in sorted(os.listdir(f"{d}/svg"))] + [f"png/{x}" for x in sorted(os.listdir(f"{d}/png"))]
    sha = lambda p: hashlib.sha256(open(f"{d}/{p}", "rb").read()).hexdigest()
    deck = {"version": "nt-perception-deck:v1", "house_rule": "Trust how it looks: take the documented default reading as true",
            "oracle": meta, "sources_sha256": {p: sha(p) for p in ("stimuli.json", "records.json")}, "cards": cards}
    json.dump(deck, open(f"{d}/deck.json", "w"), indent=1)
    files.append("deck.json")
    json.dump({"manifest_version": "nt-perception-deck:v1", "note": "SHA-256 of every file in this folder except this manifest. tests/perception.test.ts fails if any hash changes.",
               "files": {p: sha(p) for p in files}}, open(f"{d}/MANIFEST.json", "w"), indent=1)
    print(len(cards), "cards;", len(files), "files hashed")


if __name__ == "__main__":
    main(sys.argv[1])
