"""Figures computed AFTER the results were known, from the cached answers and results-confusable.json. No key, no model call.

None of these is a declared measure of the frozen protocol (evals/confusable-protocol.json); the page labels them that way.

  python3 -B analysis_confusable.py           # write results-confusable-after.json
  python3 -B analysis_confusable.py --check   # recompute and compare with the committed file byte for byte

1. Clarifications on the answerable questions: per model, the share of runs that asked for clarification although the question
   was answerable, without and with the note, and the paired change with the same percentile bootstrap as the protocol's
   measures (questions resampled, 10,000 resamples, seed 7, 95% interval).
2. The command-line runs that were replaced after their stream reported an error: each original already held a complete
   answer, so the originals are scored as they stand and compared with the re-run answer that was used.
3. Right answers over the answers that came back: the mean per-question share of right answers among the scored runs, over the
   questions scored in both arms, so a left-out answer is neither right nor wrong.
"""
from pathlib import Path
import argparse
import concurrent.futures as cf
import json
import shutil
import sys
import uuid

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
import replay_confusable as R  # noqa: E402
import collect_confusable as K  # noqa: E402
from banking import confusable as C  # noqa: E402

OUT = 'results-confusable-after.json'


def clarifications(questions, outcomes):
    analytical = [q['id'] for q in questions if q['kind'] == 'analytical']
    out = {}
    for m in K.MODELS:
        idx = {(o['question_id'], o['arm'], o['repeat']): o for o in outcomes if o['model'] == m['id']}
        counts, share = {}, {}
        for arm in C.ARMS:
            valid = [idx[i, arm, r] for i in analytical for r in range(1, K.REPEATS + 1)
                     if (i, arm, r) in idx and idx[i, arm, r]['status'] != 'method_failure']
            counts[arm] = {'runs': len(valid), 'unneeded_clarifications': sum(o['status'] == 'wrong_clarification' for o in valid)}
            share[arm] = {}
            for i in analytical:
                v = [idx[i, arm, r] for r in range(1, K.REPEATS + 1) if (i, arm, r) in idx and idx[i, arm, r]['status'] != 'method_failure']
                share[arm][i] = (sum(o['status'] == 'wrong_clarification' for o in v) / len(v)) if v else None
        kept = [i for i in analytical if share['no_note'][i] is not None and share['note'][i] is not None]
        diffs = [share['note'][i] - share['no_note'][i] for i in kept]
        out[m['id']] = {'arms': counts, 'questions': len(kept),
                        'difference': sum(diffs) / len(diffs), 'interval': C.mean_interval(diffs)}
    return out


def accuracy_over_answers(questions, outcomes):
    ids = [q['id'] for q in questions]
    out = {}
    for m in K.MODELS:
        idx = {(o['question_id'], o['arm'], o['repeat']): o for o in outcomes if o['model'] == m['id']}

        def share(i, arm):
            v = [idx[i, arm, r] for r in range(1, K.REPEATS + 1) if (i, arm, r) in idx and idx[i, arm, r]['status'] != 'method_failure']
            return (sum(bool(o['correct']) for o in v) / len(v)) if v else None
        kept = [i for i in ids if share(i, 'no_note') is not None and share(i, 'note') is not None]
        out[m['id']] = {'questions': len(kept),
                        'no_note_right': sum(share(i, 'no_note') for i in kept),
                        'note_right': sum(share(i, 'note') for i in kept)}
    return out


def originals(questions, proto, gold, sandbox, outcomes):
    cache = ROOT / K.CACHE
    qindex = {q['id']: q for q in questions}
    used = {(o['model'], o['arm'], o['question_id'], o['repeat']): o for o in outcomes}
    rows = []
    for m in K.MODELS:
        for arm in C.ARMS:
            for q in questions:
                for r in range(1, K.REPEATS + 1):
                    rec = json.loads(K.cache_path(cache, m['id'], arm, q['id'], r).read_text(encoding='utf-8'))
                    if not C.is_method_failure(rec) or K.cache_path(cache, m['id'], arm, q['id'], r, rerun=True).exists() is False:
                        continue
                    rows.append((m['id'], arm, q['id'], r, rec))

    def score(x):
        m, arm, qid, r, rec = x
        has_answer = rec.get('response') is not None and rec.get('error') == 'turn failed'
        if not has_answer:
            return m, arm, qid, r, None
        clean = dict(rec)
        clean['error'] = None
        return m, arm, qid, r, C.score_record(qindex[qid], clean, gold[qid], sandbox)
    with cf.ThreadPoolExecutor(max_workers=R.WORKERS) as pool:
        scored = list(pool.map(score, rows))
    by_model = {}
    for m, arm, qid, r, s in scored:
        d = by_model.setdefault(m, {'replaced_runs': 0, 'original_held_an_answer': 0, 'original_right': 0, 'replacement_right': 0,
                                    'same_correctness': 0, 'original_read_lookalike': 0})
        d['replaced_runs'] += 1
        if s is None:
            continue
        rep = used[m, arm, qid, r]
        d['original_held_an_answer'] += 1
        d['original_right'] += bool(s['correct'])
        d['replacement_right'] += bool(rep['correct'])
        d['same_correctness'] += bool(s['correct']) == bool(rep['correct'])
        d['original_read_lookalike'] += bool(s['lookalikes'])
    return by_model


def compute():
    proto = R.verified_protocol()
    questions = R.read('evals/questions.json')
    outcomes = R.read('results-confusable.json')['outcomes']
    runtime = ROOT / 'runtime' / ('confusable-after-' + uuid.uuid4().hex)
    runtime.mkdir(parents=True)
    try:
        database = runtime / 'round.duckdb'
        C.build(database)
        if C.table_digest(database) != proto['table_contents_sha256']:
            raise ValueError('Rebuilt tables differ from the frozen contents')
        sandbox = C.RoundSandbox(database)
        guard = C._round_module_validator()
        guard.__enter__()
        try:
            needed = sorted({q['gold_sql'] for q in questions if q['gold_sql'] is not None})
            with cf.ThreadPoolExecutor(max_workers=R.WORKERS) as pool:
                rows = dict(zip(needed, pool.map(lambda sql: sandbox.run(sql)['rows'], needed)))
            gold = {q['id']: (None if q['gold_sql'] is None else rows[q['gold_sql']]) for q in questions}
            replaced = originals(questions, proto, gold, sandbox, outcomes)
        finally:
            guard.__exit__(None, None, None)
    finally:
        shutil.rmtree(runtime, ignore_errors=True)
    return {'note': 'Computed after the results were known; not a declared measure of the frozen protocol.',
            'clarifications': clarifications(questions, outcomes),
            'right_answers_over_answers_that_came_back': accuracy_over_answers(questions, outcomes),
            'replaced_command_line_runs': replaced}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--check', action='store_true')
    args = ap.parse_args()
    text = json.dumps(compute(), indent=1, sort_keys=True) + '\n'
    path = ROOT / OUT
    if args.check:
        if not path.exists() or path.read_text(encoding='utf-8') != text:
            raise SystemExit('VERDICT: FAIL (' + OUT + ' differs from the recomputed file)')
        print('VERDICT: PASS (' + OUT + ' reproduced)')
        return
    path.write_text(text, encoding='utf-8')
    print('VERDICT: PASS (' + OUT + ' written)')


if __name__ == '__main__':
    main()
