#!/usr/bin/env python3
"""delegation_map.py — the runnable object behind the delegation-map piece.

Two jobs:

  audit   Score the published delegation frameworks (frameworks.json) on the six
          questions and print the coverage counts the piece cites.
  map     Sort a reader's tasks (a JSON file) into zones, with the standing order
          to paste into their AI and a re-test date for each task.

    python3 delegation_map.py audit
    python3 delegation_map.py map fixtures/<file>.json [--today YYYY-MM-DD]
    python3 delegation_map.py selftest

The zone rules are the article's extension, stated as code so they can be
attacked. Every threshold names its source in ZONE_RULES below.
"""
from __future__ import annotations

import datetime as dt
import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))

# --------------------------------------------------------------------------- audit

QUESTIONS = ["reach", "check", "stakes", "keep", "retest", "self"]


def audit(path: str = os.path.join(HERE, "frameworks.json")) -> dict:
    data = json.load(open(path))
    fw = data["frameworks"]
    n = len(fw)
    counts = {q: {"Y": 0, "P": 0, "N": 0} for q in QUESTIONS}
    for f in fw:
        for q in QUESTIONS:
            counts[q][f[q]] += 1
    all_core_y = [f["id"] for f in fw if all(f[q] == "Y" for q in ["reach", "check", "stakes", "keep", "retest"])]
    check_and_keep = [f["id"] for f in fw if f["check"] == "Y" and f["keep"] == "Y"]
    self_built = [f for f in fw if f["self"] == "Y"]
    classic_keep = [f["id"] for f in fw if f["family"] == "classic" and f["keep"] == "Y"]
    ai_era_keep = [f["id"] for f in fw if f["family"] == "ai-era" and f["keep"] == "Y"]
    return {
        "n": n,
        "counts": counts,
        "all_five_core_yes": all_core_y,
        "check_and_keep_yes": check_and_keep,
        "self_built": [f["id"] for f in self_built],
        "classic_keep_yes": classic_keep,
        "ai_era_keep_yes": ai_era_keep,
        "retest_yes": [f["id"] for f in fw if f["retest"] == "Y"],
        "frameworks": fw,
    }


def print_audit(a: dict) -> None:
    n = a["n"]
    print(f"Frameworks audited: {n}")
    print()
    print(f"{'question':8}  {'Y':>3} {'P':>3} {'N':>3}")
    for q in QUESTIONS:
        c = a["counts"][q]
        print(f"{q:8}  {c['Y']:>3} {c['P']:>3} {c['N']:>3}")
    print()
    print(f"Ask all five core questions (reach, check, stakes, keep, retest): {len(a['all_five_core_yes'])} of {n}")
    print(f"Give a per-task re-test: {len(a['retest_yes'])} of {n}")
    print(f"Weigh both check cost and what you lose: {len(a['check_and_keep_yes'])} of {n} -> {', '.join(a['check_and_keep_yes'])}")
    print(f"Built for a person deciding about their own tasks: {len(a['self_built'])} of {n} -> {', '.join(a['self_built'])}")
    print(f"Count what you lose by not doing it: classic {len(a['classic_keep_yes'])} ({', '.join(a['classic_keep_yes'])}); AI-era {len(a['ai_era_keep_yes'])}")
    selfm=[f['id'] for f in a['frameworks'] if f['self']=='Y' and f.get('measured')=='Y']
    meas=[f['id'] for f in a['frameworks'] if f.get('measured')=='Y']
    ai_era=[f for f in a['frameworks'] if f['family']=='ai-era']
    print(f"Backed by measured data: {len(meas)} of {a['n']}, built for yourself and measured: {len(selfm)} of {len(a['self_built'])}")
    print(f"AI-era research frameworks (family label) that count what you lose: {len(a['ai_era_keep_yes'])} of {len(ai_era)}")
    recent=[f for f in a['frameworks'] if f['year'] and f['year']>=2023]
    recent_keep=[f['id'] for f in recent if f['keep']=='Y']
    undated_keep=[f['id'] for f in a['frameworks'] if not f['year'] and f['keep']=='Y']
    print(f"Frameworks dated 2023 or later that count what you lose: {len(recent_keep)} of {len(recent)} -> {', '.join(recent_keep)}; undated that count it: {', '.join(undated_keep) or 'none'}")
    allfive=[f['id'] for f in a['frameworks'] if all(f[q]=='Y' for q in ['reach','check','stakes','keep','retest'])]
    print(f"The one(s) that ask all five: {', '.join(allfive) or 'none'}")
    selfp=[f['id'] for f in a['frameworks'] if f['self']=='Y' and f.get('measured')=='P']
    print(f"Built for yourself and partly measured (cites data it did not test its own rule on): {len(selfp)} -> {', '.join(selfp)}")


# ----------------------------------------------------------------------------- map

ZONES = {
    "test-first": {
        "label": "Test it first",
        "order": "Run the ten-minute trial on one finished example before deciding.",
    },
    "hand-over": {
        "label": "Hand it over",
        "order": ("For {tasks}: do the whole task. Show your sources and any figure you used, "
                  "so I can check it in a few minutes."),
    },
    "hand-over-keep-hand-in": {
        "label": "Hand it over, keep your hand in",
        "order": ("For {tasks}: do the task, but once a quarter I will do one myself first. "
                  "When I say 'practice round', don't produce an answer; wait for mine, then compare it with yours "
                  "and tell me where they differ."),
    },
    "make-checkable": {
        "label": "Make it checkable first",
        "order": ("For {tasks}: don't hand me a finished answer. Give me the parts I can check: each claim "
                  "with its source and the exact words it rests on, each number with where it came from, "
                  "and anything you inferred marked as inferred."),
    },
    "you-lead": {
        # Self-attack 11 (wave 1, red team R5): an AI shown your answer first anchors on it
        # (Everett et al. 2026: full overlap 48% of cases when it went second vs 3% first).
        "label": "Two answers, then compare",
        "order": ("For {tasks}: first write your own answer from the inputs, before you see mine. "
                  "Then I'll paste my version: list where the two differ and what in mine is wrong, "
                  "missing or weakest, most serious first. Don't rewrite mine."),
    },
    "keep": {
        "label": "Keep it",
        "order": ("For {tasks}: only help with the chores around it (finding files, formatting, "
                  "summarising inputs I name). Don't attempt the task itself."),
    },
}

# Sources for each rule (research notes of 2026-11-16):
#  - who wins alone decides more than anything else: Vaccaro, Almaatouq & Malone 2024
#    (combination gained when the human was better alone, g=+0.46; lost when the AI
#    was better, g=-0.54).  -> "you-lead" when the person wins.
#  - check ratio vs success rate: GDPval try-review-fix model (review 109 of 404 min);
#    handing over pays only when checking takes less than the share of tries the AI
#    gets right (expected time = check + (1 - success) * do < do  <=>  ratio < success).
#  - can't catch it -> don't "work on it together": Steyvers et al. 2025 (people judge
#    AI correctness barely above chance), Vasconcelos et al. 2023 (overreliance falls
#    only when checking gets cheaper), Goh et al. 2024 / Agarwal et al. (the
#    combination is often the worst of three).
#  - keep your hand in: Bainbridge 1983; Bastani et al. 2025; Fine & Whitney 1996
#    (dependence for knowledge); Tatel & Ackerman 2025 (unused skills lose about half
#    their gains over 6.5-13 months) -> practise at least monthly to quarterly.
#  - re-test: every framework says capability moves; none sets a per-task date.

RETEST_DAYS = 90
# Self-attack 2 (2026-11-16): was 30. Tatel & Ackerman 2025 put the loss of half an
# unused skill's gains at 6.5-13 months, so monthly practice over-prescribes. One
# quarterly ritual: re-run the test card and do one by hand, on the same day.
PRACTICE_DAYS = 90


def zone_for(t: dict) -> tuple[str, list[str]]:
    """Return (zone id, reasons) for one task."""
    why: list[str] = []
    wins = t.get("who_wins", "untested")
    if wins == "untested":
        return "test-first", ["no trial yet"]
    if wins == "ai_unusable":
        return "keep", ["the AI's attempt was unusable"]
    if wins == "me":
        why.append("you did it better alone: the pair beats both when the person is the better one, if neither sees the other's answer first")
        return "you-lead", why
    # AI better or about the same
    do_min = float(t.get("do_min") or 0)
    check_min = float(t.get("check_min") or 0)
    success = t.get("success_rate")
    ratio = (check_min / do_min) if do_min > 0 else None
    caught = t.get("caught", "unsure")
    miss = t.get("miss_cost", "medium")
    if caught != "yes":
        if miss == "low":
            why.append("you could not be sure of catching its mistakes, but a miss is cheap")
        else:
            # Self-attack 1 (2026-11-16): when the AI beats you and you cannot catch its
            # errors, your edit can make the answer worse (Vaccaro et al. 2024, g=-0.54
            # when the AI was better alone; Goh et al. 2024). "Check it" is not a remedy.
            why.append("you could not be sure of catching its mistakes, and a miss costs something; "
                       "nodding it through adds nothing, so change what you ask for until you can check it, "
                       "or get a check that does not depend on you")
            return "make-checkable", why
    if ratio is not None:
        bar = float(success) if success is not None else 0.5
        if ratio >= bar:
            why.append(f"checking took {ratio:.0%} of the time to do it, at or above its success rate ({bar:.0%})")
            return "make-checkable", why
        why.append(f"checking took {ratio:.0%} of the time to do it, below its success rate ({bar:.0%})")
    if t.get("judge_in_a_year", "unsure") != "yes":
        why.append("if you stopped doing it, you might not be able to judge it")
        return "hand-over-keep-hand-in", why
    return "hand-over", why


def build_map(tasks: list[dict], today: dt.date) -> dict:
    rows = []
    for t in tasks:
        z, why = zone_for(t)
        retest = today + dt.timedelta(days=RETEST_DAYS)
        practice = today + dt.timedelta(days=PRACTICE_DAYS) if z == "hand-over-keep-hand-in" else None
        rows.append({"task": t["task"], "zone": z, "label": ZONES[z]["label"], "why": why,
                     "retest": retest.isoformat(), "practice": practice.isoformat() if practice else None})
    by_zone: dict[str, list[str]] = {}
    for r in rows:
        by_zone.setdefault(r["zone"], []).append(r["task"])
    orders = {}
    for z, ts in by_zone.items():
        if z == "test-first":
            continue
        names = "; ".join(ts)
        orders[z] = ZONES[z]["order"].format(tasks=names)
    return {"rows": rows, "orders": orders}


def print_map(m: dict) -> None:
    for r in m["rows"]:
        extra = f" · by hand by {r['practice']}" if r["practice"] else ""
        print(f"- {r['task']}: {r['label']} (re-test by {r['retest']}{extra})")
        for w in r["why"]:
            print(f"    · {w}")
    print()
    print("Standing orders to paste into your AI's instructions:")
    for z, o in m["orders"].items():
        print(f"  [{ZONES[z]['label']}] {o}")


# ------------------------------------------------------------------------ selftest

def selftest() -> int:
    """Cases written to break the rules, not to demo them."""
    cases = [
        ({"task": "a", "who_wins": "untested"}, "test-first"),
        ({"task": "b", "who_wins": "ai_unusable"}, "keep"),
        ({"task": "c", "who_wins": "me", "miss_cost": "high"}, "you-lead"),
        # AI better, cheap to check, still able to judge -> hand over
        ({"task": "d", "who_wins": "ai", "do_min": 60, "check_min": 10, "success_rate": 0.8,
          "caught": "yes", "miss_cost": "high", "judge_in_a_year": "yes"}, "hand-over"),
        # same but judging depends on doing -> keep hand in
        ({"task": "e", "who_wins": "ai", "do_min": 60, "check_min": 10, "success_rate": 0.8,
          "caught": "yes", "miss_cost": "low", "judge_in_a_year": "no"}, "hand-over-keep-hand-in"),
        # AI better but you cannot catch its errors and a miss costs -> make checkable
        ({"task": "f", "who_wins": "ai", "do_min": 60, "check_min": 5, "success_rate": 0.9,
          "caught": "no", "miss_cost": "high", "judge_in_a_year": "yes"}, "make-checkable"),
        # cannot catch, but a miss is cheap -> may hand over
        ({"task": "g", "who_wins": "same", "do_min": 30, "check_min": 3, "success_rate": 0.7,
          "caught": "unsure", "miss_cost": "low", "judge_in_a_year": "yes"}, "hand-over"),
        # checking costs as much as doing -> make checkable (handing over saves nothing)
        ({"task": "h", "who_wins": "ai", "do_min": 40, "check_min": 40, "success_rate": 0.9,
          "caught": "yes", "miss_cost": "low", "judge_in_a_year": "yes"}, "make-checkable"),
        # GDPval-like numbers: review 109 of 404 min (27%), success 39% -> hand over pays, barely
        ({"task": "i", "who_wins": "same", "do_min": 404, "check_min": 109, "success_rate": 0.39,
          "caught": "yes", "miss_cost": "medium", "judge_in_a_year": "yes"}, "hand-over"),
        # same review time, success 25% -> it does not pay
        ({"task": "j", "who_wins": "same", "do_min": 404, "check_min": 109, "success_rate": 0.25,
          "caught": "yes", "miss_cost": "medium", "judge_in_a_year": "yes"}, "make-checkable"),
        # missing timings, caught, judge unsure -> keep hand in (no ratio evidence either way)
        ({"task": "k", "who_wins": "ai", "caught": "yes", "miss_cost": "medium"}, "hand-over-keep-hand-in"),
    ]
    bad = 0
    for t, want in cases:
        got, why = zone_for(t)
        flag = "ok " if got == want else "BAD"
        if got != want:
            bad += 1
        print(f"{flag} {t['task']}: want {want:24} got {got:24} {'; '.join(why)}")
    print(f"\nselftest: {len(cases) - bad}/{len(cases)} cases as intended")
    return 1 if bad else 0


def main(argv: list[str]) -> int:
    if not argv or argv[0] in ("-h", "--help"):
        print(__doc__)
        return 0
    cmd = argv[0]
    if cmd == "audit":
        print_audit(audit())
        return 0
    if cmd == "map":
        today = dt.date.today()
        if "--today" in argv:
            today = dt.date.fromisoformat(argv[argv.index("--today") + 1])
        path = argv[1]
        if not os.path.isabs(path):
            path = os.path.join(HERE, path)
        tasks = json.load(open(path))["tasks"]
        print_map(build_map(tasks, today))
        return 0
    if cmd == "selftest":
        return selftest()
    print(__doc__)
    return 1


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