#!/usr/bin/env python3
"""Summarise v1 results-*.json into summary.json.

Agrees = the conclusion points the same way as the background line. Every effect is a mean over
the 20 invented items (each item averaged over both backgrounds and, where stated, both kinds of
evidence), with a 95% bootstrap interval over items. Ratings are parsed exactly as in v0: a bare
number, else the first number 0-100 on the first line.
"""
import glob, json, random, re, statistics as st

def rating(reply):
    m = re.fullmatch(r"\s*(\d{1,3}(?:\.\d+)?)\s*%?\.?\s*", reply)
    if m and float(m.group(1)) <= 100:
        return float(m.group(1)), False
    line = reply.strip().split("\n")[0]
    for tok in re.findall(r"(?<![\d,.])\d{1,3}(?![\d,])", line):
        if float(tok) <= 100:
            return float(tok), True
    return None, True

def boot(vals, n=4000, seed=1):
    rng = random.Random(seed)
    means = sorted(st.mean(rng.choices(vals, k=len(vals))) for _ in range(n))
    return [round(st.mean(vals), 1), round(means[int(.025 * n)], 1), round(means[int(.975 * n)], 1)]

AGREE = {"lowers": "lower", "raises": "higher"}
OTHER = {"lower": "higher", "higher": "lower"}
summary = {}
for path in sorted(glob.glob("results-*.json")):
    d = json.load(open(path))
    out = {"belief_check": {}, "prompts": {}}
    B = {(b["item"], b["background"], b["conclusion"]): b["answer"] for b in d["beliefs"]}
    for bg in ("none", "lowers", "raises"):
        ans = [B[k] for k in B if k[1] == bg]
        row = {"answered": sum(a is not None for a in ans), "asked": len(ans)}
        if bg != "none":
            row["matches_background"] = sum(B[(i, bg, AGREE[bg])] is True and B[(i, bg, OTHER[AGREE[bg]])] is False for i in range(1, 21))
        else:
            row["true_for_lower"] = sum(B[(i, "none", "lower")] is True for i in range(1, 21))
            row["true_for_higher"] = sum(B[(i, "none", "higher")] is True for i in range(1, 21))
        out["belief_check"][bg] = row
    for prompt in ("plain", "instructed"):
        R, loose, missing = {}, 0, 0
        for r in d["verdicts"]:
            if r["prompt"] != prompt:
                continue
            v, was_loose = rating(r["reply"])
            loose += was_loose and v is not None
            missing += v is None
            R[(r["item"], r["background"], r["conclusion"], r["evidence"])] = v
        items = [i for i in range(1, 21) if all(v is not None for k, v in R.items() if k[0] == i)]
        g = lambda i, bg, c, e: R[(i, bg, c, e)]
        A = lambda i, bg, e: g(i, bg, AGREE[bg], e)          # conclusion agrees with background
        D = lambda i, bg, e: g(i, bg, OTHER[AGREE[bg]], e)   # conclusion contradicts it
        N = lambda i, bg, e: g(i, "none", AGREE[bg], e)      # same conclusion, no background
        BG = ("lowers", "raises")
        mean2 = lambda f: st.mean(f(bg) for bg in BG)
        agree = [mean2(lambda bg: st.mean(A(i, bg, e) - D(i, bg, e) for e in ("strong", "weak"))) for i in items]
        agree_strong = [mean2(lambda bg: A(i, bg, "strong") - D(i, bg, "strong")) for i in items]
        quality = [mean2(lambda bg: st.mean(g(i, bg, c, "strong") - g(i, bg, c, "weak") for c in ("lower", "higher"))) for i in items]
        quality_none = [st.mean(g(i, "none", c, "strong") - g(i, "none", c, "weak") for c in ("lower", "higher")) for i in items]
        lift = [mean2(lambda bg: st.mean(A(i, bg, e) - N(i, bg, e) for e in ("strong", "weak"))) for i in items]
        drop = [mean2(lambda bg: st.mean(g(i, bg, OTHER[AGREE[bg]], e) - g(i, "none", OTHER[AGREE[bg]], e) for e in ("strong", "weak"))) for i in items]
        conflict = [(i, bg, A(i, bg, "weak") - D(i, bg, "strong")) for i in items for bg in BG]
        cells = {}
        for name, f in (("agrees/strong", lambda i, bg: A(i, bg, "strong")), ("agrees/weak", lambda i, bg: A(i, bg, "weak")),
                        ("contradicts/strong", lambda i, bg: D(i, bg, "strong")), ("contradicts/weak", lambda i, bg: D(i, bg, "weak")),
                        ("no background/strong", lambda i, bg: N(i, bg, "strong")), ("no background/weak", lambda i, bg: N(i, bg, "weak"))):
            cells[name] = round(st.mean(f(i, bg) for i in items for bg in BG), 1)
        out["prompts"][prompt] = {
            "items_used": len(items), "sentence_replies": loose, "no_number": missing, "cell_means": cells,
            "agreement_effect_agrees_minus_contradicts": boot(agree),
            "agreement_effect_strong_evidence_only": boot(agree_strong),
            "agreement_effect_by_background": {bg: {e: boot([A(i, bg, e) - D(i, bg, e) for i in items]) for e in ("strong", "weak")} for bg in BG},
            "quality_effect_strong_minus_weak_with_background": boot(quality),
            "quality_effect_strong_minus_weak_no_background": boot(quality_none),
            "agreeing_conclusion_vs_no_background": boot(lift),
            "contradicting_conclusion_vs_no_background": boot(drop),
            "conflict_hearsay_agreeing_minus_study_contradicting": boot([c for _, _, c in conflict]),
            "conflict_cases_hearsay_rated_higher": sum(c > 0 for *_, c in conflict),
            "conflict_cases_tied": sum(c == 0 for *_, c in conflict),
            "conflict_cases": len(conflict)}
    summary[d["model"]] = out
json.dump(summary, open("summary.json", "w"), indent=1)
print(json.dumps(summary, indent=1))
