"""Confusable tables round: planted look-alike tables, the round's validator and prompts, and mechanical scoring.

The published warehouse (four source tables and two marts, unchanged) gains twelve look-alike tables: for each of
card_spend_daily, transactions and account_daily, an old copy built with a retired definition (<table>_v1), a stale
backup that stops before 2026-07-25 (<table>_backup), a staging copy with test rows (stg_<table>) and a copy with the
same name in a second schema that keeps only cards active at the snapshot (analytics.<table>). The question set, the
answer key, the bare-schema prompt and the scoring rubric are the published ones; the schema listing in the prompt
lists all eighteen tables, and the treatment adds one system message, the relationship note. No network or
credentials in this module.
"""
from contextlib import contextmanager
from pathlib import Path
import hashlib
import json
import random
import re
import sys

from bootstrap import dependency

sys.path.insert(0, str(dependency()))
import duckdb  # noqa: E402
import sqlglot  # noqa: E402
from sqlglot import exp  # noqa: E402
from sqlglot.errors import ParseError  # noqa: E402
import portfolio_eval.sandbox as archive_sandbox  # noqa: E402
from portfolio_eval.sandbox import FUNCTIONS, Sandbox  # noqa: E402
from portfolio_eval.contracts import rows_equal  # noqa: E402

from .build import build_database, RELATIONS as MAIN_RELATIONS  # noqa: E402
from .inputs import PROTOCOL  # noqa: E402
from .correction import PREDICATES  # noqa: E402
from .models_arm import ANSWER_SCHEMA  # noqa: E402

ROOT = Path(__file__).resolve().parents[1]
ARMS = ('no_note', 'note')
ARM_LABELS = {'no_note': 'Without the note', 'note': 'With the note'}
NOTE = 'documentation/relationship-note.md'
SCHEMA_LISTING = 'evals/confusable-schema.json'
CUTOFF = '2026-07-25'
SHADOWED = ('card_spend_daily', 'transactions', 'account_daily')
KINDS = ('old_definition', 'stale_backup', 'staging_test_rows', 'second_schema')
KIND_LABELS = {'old_definition': 'Old copy with a retired definition (_v1)',
               'stale_backup': 'Stale backup (_backup)',
               'staging_test_rows': 'Staging copy with test rows (stg_)',
               'second_schema': 'Same name in a second schema (analytics.)'}
KIND_SHORT = {'old_definition': 'Old copy', 'stale_backup': 'Stale backup',
              'staging_test_rows': 'Staging copy', 'second_schema': 'Second schema'}
SECOND_SCHEMA = 'analytics'


def decoy_name(table, kind):
    return {'old_definition': table + '_v1', 'stale_backup': table + '_backup',
            'staging_test_rows': 'stg_' + table, 'second_schema': SECOND_SCHEMA + '.' + table}[kind]


DECOYS = {decoy_name(t, k): {'shadows': t, 'kind': k} for t in SHADOWED for k in KINDS}
CURRENT = tuple(sorted(MAIN_RELATIONS))

# Test rows in the staging copies: two test accounts with test cards, no organization, posted in July.
TEST_ACCOUNTS = [('acct_test_01', 'org_test', 'CAD', 'open', 0), ('acct_test_02', 'org_test', 'USD', 'open', 0)]
TEST_EVENTS = [
    # transaction_id, account_id, card_id, category_id, event_kind, status, direction, amount_minor, currency,
    # occurred_at, posted_at, related_transaction_id, transfer_group_id
    ('txn_test_01', 'acct_test_01', None, None, 'deposit', 'posted', 'credit', 500000, 'CAD',
     '2026-07-02 09:00:00', '2026-07-02 09:05:00', None, None),
    ('txn_test_02', 'acct_test_01', 'card_test_01', None, 'purchase', 'posted', 'debit', 75000, 'CAD',
     '2026-07-08 10:00:00', '2026-07-08 12:00:00', None, None),
    ('txn_test_03', 'acct_test_01', 'card_test_01', None, 'purchase', 'posted', 'debit', 50000, 'CAD',
     '2026-07-08 11:00:00', '2026-07-08 13:00:00', None, None),
    ('txn_test_04', 'acct_test_01', 'card_test_01', None, 'refund', 'posted', 'credit', 25000, 'CAD',
     '2026-07-22 09:00:00', '2026-07-22 10:00:00', 'txn_test_02', None),
    ('txn_test_05', 'acct_test_01', None, None, 'withdrawal', 'posted', 'debit', 100000, 'CAD',
     '2026-07-15 09:00:00', '2026-07-15 09:30:00', None, None),
    ('txn_test_06', 'acct_test_02', None, None, 'deposit', 'posted', 'credit', 300000, 'USD',
     '2026-07-03 09:00:00', '2026-07-03 09:05:00', None, None),
    ('txn_test_07', 'acct_test_02', 'card_test_02', None, 'purchase', 'posted', 'debit', 87500, 'USD',
     '2026-07-08 14:00:00', '2026-07-08 16:00:00', None, None),
]

_BALANCES = """
SELECT a.account_id, a.currency, d.balance_date,
  a.opening_balance_minor + COALESCE(SUM(CASE WHEN CAST(t.posted_at AS DATE) < d.balance_date
    THEN CASE WHEN t.direction = 'credit' THEN t.amount_minor ELSE -t.amount_minor END ELSE 0 END), 0)::BIGINT AS opening_minor,
  COALESCE(SUM(CASE WHEN CAST(t.posted_at AS DATE) = d.balance_date AND t.direction = 'credit'
    THEN t.amount_minor ELSE 0 END), 0)::BIGINT AS posted_credit_minor,
  COALESCE(SUM(CASE WHEN CAST(t.posted_at AS DATE) = d.balance_date AND t.direction = 'debit'
    THEN t.amount_minor ELSE 0 END), 0)::BIGINT AS posted_debit_minor,
  a.opening_balance_minor + COALESCE(SUM(CASE WHEN t.direction = 'credit'
    THEN t.amount_minor ELSE -t.amount_minor END), 0)::BIGINT AS closing_minor
FROM {accounts} a CROSS JOIN (SELECT DATE '2026-07-01' + CAST(range AS INTEGER) AS balance_date FROM range(33)) d
LEFT JOIN ({events}) t ON t.account_id = a.account_id AND CAST(t.posted_at AS DATE) <= d.balance_date
GROUP BY a.account_id, a.currency, a.opening_balance_minor, d.balance_date
ORDER BY a.account_id, d.balance_date"""

_SPEND = """
SELECT CAST({date_of} AS DATE) AS spend_date, card_id, account_id, category_id, currency,
  SUM(CASE WHEN event_kind = 'purchase' THEN amount_minor ELSE 0 END)::BIGINT AS purchased_minor,
  SUM(CASE WHEN event_kind = 'refund' THEN amount_minor ELSE 0 END)::BIGINT AS refunded_minor,
  SUM(CASE WHEN event_kind = 'purchase' THEN amount_minor ELSE -amount_minor END)::BIGINT AS net_spend_minor,
  COUNT(CASE WHEN event_kind = 'purchase' THEN 1 END)::BIGINT AS purchase_count,
  COUNT(CASE WHEN event_kind = 'refund' THEN 1 END)::BIGINT AS refund_count
FROM {events}
WHERE status = 'posted' AND event_kind IN ('purchase', 'refund')
GROUP BY CAST({date_of} AS DATE), card_id, account_id, category_id, currency
ORDER BY spend_date, card_id, category_id"""

_ACTIVE_EVENTS = ("SELECT t.* FROM transactions t LEFT JOIN cards c ON c.card_id = t.card_id "
                  "WHERE t.card_id IS NULL OR c.card_status = 'active'")


def _columns(db, table):
    return [r[0] for r in db.execute('DESCRIBE ' + table).fetchall()]


def decoy_statements(db):
    """CREATE statements for the twelve look-alikes, in a fixed order. Each keeps its table's columns and types."""
    tx = _columns(db, 'transactions')
    signed = ', '.join("CASE WHEN direction = 'debit' THEN -amount_minor ELSE amount_minor END AS amount_minor"
                       if c == 'amount_minor' else c for c in tx)
    stale = ', '.join(
        f"CASE WHEN status = 'posted' AND posted_at >= TIMESTAMP '{CUTOFF}' THEN 'pending' ELSE status END AS status"
        if c == 'status' else f"CASE WHEN posted_at >= TIMESTAMP '{CUTOFF}' THEN NULL ELSE posted_at END AS posted_at"
        if c == 'posted_at' else c for c in tx)
    posted = "SELECT * FROM transactions WHERE status = 'posted'"
    with_pending = ("SELECT account_id, direction, amount_minor, COALESCE(posted_at, occurred_at) AS posted_at "
                    "FROM transactions WHERE status IN ('posted', 'pending')")
    test_events = 'SELECT * FROM test_events'
    return [
        ('card_spend_daily_v1', 'CREATE TABLE card_spend_daily_v1 AS ' + _SPEND.format(date_of='occurred_at', events='transactions')),
        ('card_spend_daily_backup', f"CREATE TABLE card_spend_daily_backup AS SELECT * FROM card_spend_daily "
                                    f"WHERE spend_date < DATE '{CUTOFF}' ORDER BY spend_date, card_id, category_id"),
        ('stg_card_spend_daily', 'CREATE TABLE stg_card_spend_daily AS SELECT * FROM card_spend_daily UNION ALL '
                                 + _SPEND.format(date_of='posted_at', events='test_events')),
        ('analytics.card_spend_daily', 'CREATE TABLE analytics.card_spend_daily AS SELECT s.* FROM card_spend_daily s '
                                       "JOIN cards c ON c.card_id = s.card_id WHERE c.card_status = 'active' "
                                       'ORDER BY s.spend_date, s.card_id, s.category_id'),
        ('transactions_v1', f'CREATE TABLE transactions_v1 AS SELECT {signed} FROM transactions ORDER BY transaction_id'),
        ('transactions_backup', f"CREATE TABLE transactions_backup AS SELECT {stale} FROM transactions "
                                f"WHERE occurred_at < TIMESTAMP '{CUTOFF}' ORDER BY transaction_id"),
        ('stg_transactions', 'CREATE TABLE stg_transactions AS SELECT * FROM transactions UNION ALL '
                             'SELECT * FROM test_events'),
        ('analytics.transactions', f'CREATE TABLE analytics.transactions AS {_ACTIVE_EVENTS} ORDER BY t.transaction_id'),
        ('account_daily_v1', 'CREATE TABLE account_daily_v1 AS ' + _BALANCES.format(accounts='accounts', events=with_pending)),
        ('account_daily_backup', f"CREATE TABLE account_daily_backup AS SELECT * FROM account_daily "
                                 f"WHERE balance_date < DATE '{CUTOFF}' ORDER BY account_id, balance_date"),
        ('stg_account_daily', 'CREATE TABLE stg_account_daily AS SELECT * FROM account_daily UNION ALL '
                              + _BALANCES.format(accounts='test_accounts',
                                                 events="SELECT * FROM test_events WHERE status = 'posted'")),
        ('analytics.account_daily', 'CREATE TABLE analytics.account_daily AS '
                                    + _BALANCES.format(accounts='accounts',
                                                       events=f"SELECT t.* FROM ({_ACTIVE_EVENTS}) t WHERE t.status = 'posted'")),
    ], posted


def build(path, root=ROOT):
    """The published database plus the twelve look-alikes, in a new file. Returns hashes, schema and row counts."""
    path = Path(path)
    base = build_database(path, root)
    db = duckdb.connect(str(path))
    try:
        db.execute('BEGIN TRANSACTION')
        db.execute('CREATE SCHEMA ' + SECOND_SCHEMA)
        tx_types = db.execute('DESCRIBE transactions').fetchall()
        db.execute('CREATE TEMP TABLE test_events (' + ', '.join(f'{c} {t}' for c, t, *_ in tx_types) + ')')
        db.executemany('INSERT INTO test_events VALUES (' + ', '.join('?' for _ in tx_types) + ')', TEST_EVENTS)
        acct_types = db.execute('DESCRIBE accounts').fetchall()
        db.execute('CREATE TEMP TABLE test_accounts (' + ', '.join(f'{c} {t}' for c, t, *_ in acct_types) + ')')
        db.executemany('INSERT INTO test_accounts VALUES (' + ', '.join('?' for _ in acct_types) + ')', TEST_ACCOUNTS)
        statements, _ = decoy_statements(db)
        if {n for n, _ in statements} != set(DECOYS) or len(statements) != len(DECOYS):
            raise ValueError('Look-alike statements do not match the declared list')
        for _, sql in statements:
            db.execute(sql)
        db.execute('DROP TABLE test_events')
        db.execute('DROP TABLE test_accounts')
        db.execute('COMMIT')
        db.execute('CHECKPOINT')
        schema = {}
        for name in sorted(set(MAIN_RELATIONS) | set(DECOYS)):
            schema[name] = [{'name': r[0], 'type': r[1]} for r in db.execute('DESCRIBE ' + name).fetchall()]
        counts = {name: db.execute('SELECT COUNT(*) FROM ' + name).fetchone()[0] for name in sorted(schema)}
        for name, info in DECOYS.items():
            if schema[name] != schema[info['shadows']]:
                raise ValueError('A look-alike must keep its table\'s columns and types: ' + name)
    finally:
        db.close()
    return {'database_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
            'base_database_sha256': base['database_sha256'], 'schema': schema, 'rows': counts}


def table_digest(path):
    """Content hash per relation (sorted rows), stable across rebuilds of the same inputs."""
    db = duckdb.connect(str(path), read_only=True)
    try:
        out = {}
        for name in sorted(set(MAIN_RELATIONS) | set(DECOYS)):
            rows = sorted(json.dumps([str(v) for v in r]) for r in db.execute('SELECT * FROM ' + name).fetchall())
            out[name] = hashlib.sha256('\n'.join(rows).encode()).hexdigest()
    finally:
        db.close()
    return out


# The round's validator: the corrected validator (EXISTS treated like AND, OR and NOT) with the relation check
# extended to the declared tables, so that a look-alike can be read and scored instead of being denied.
def _allowed(table):
    name, schema = table.name, table.db
    if schema in ('', 'main'):
        return name in MAIN_RELATIONS or name in DECOYS
    return schema == SECOND_SCHEMA and (SECOND_SCHEMA + '.' + name) in DECOYS


def validate_round(sql, relations=None):
    if not isinstance(sql, str) or len(sql) > 32000:
        raise ValueError('Invalid SQL size')
    try:
        statements = sqlglot.parse(sql, read='duckdb')
    except ParseError as error:
        raise ValueError('SQL parse rejected') from error
    if len(statements) != 1 or not isinstance(statements[0], exp.Select):
        raise ValueError('One SELECT is required')
    tree = statements[0]
    if any(isinstance(n, (exp.Command, exp.Insert, exp.Delete, exp.Update, exp.Create, exp.Drop, exp.Copy, exp.Attach))
           for n in tree.walk()):
        raise ValueError('Statement denied')
    ctes = {cte.alias for cte in tree.find_all(exp.CTE)}
    for table in tree.find_all(exp.Table):
        if not isinstance(table.this, exp.Identifier):
            raise ValueError('Relation denied')
        if table.catalog not in ('', 'eval'):
            raise ValueError('Namespace denied')
        if table.db == '' and table.name in ctes:
            continue
        if not _allowed(table):
            raise ValueError('Relation denied' if table.db in ('', 'main', SECOND_SCHEMA) else 'Namespace denied')
    for func in tree.find_all(exp.Func):
        if isinstance(func, PREDICATES):
            continue
        name = func.name.upper() if isinstance(func, exp.Anonymous) else func.sql_name().upper()
        if name not in FUNCTIONS:
            raise ValueError('Function denied: ' + name)
    if any(isinstance(n, exp.With) and n.args.get('recursive') for n in tree.walk()):
        raise ValueError('Recursion denied')
    return tree


@contextmanager
def _round_module_validator():
    original = archive_sandbox.validate
    archive_sandbox.validate = validate_round
    try:
        yield
    finally:
        archive_sandbox.validate = original


class RoundSandbox(Sandbox):
    """The archive's namespace sandbox over the round's database; only the host-side validator differs."""

    def run(self, sql=None, probe=False):
        if probe:
            return super().run(probe=True)
        validate_round(sql)
        with _round_module_validator():
            return super().run(sql)


def tables_read(sql):
    """The relations a SQL answer reads, as listed in the prompt (look-alikes in the second schema keep the prefix).

    Parsed with the duckdb dialect; CTE names are not relations. When the SQL does not parse, every listed name that
    appears as a whole identifier is counted, longest names first so that a prefix match is not double counted.
    """
    if not isinstance(sql, str):
        return set()
    listed = set(MAIN_RELATIONS) | set(DECOYS)
    try:
        statements = [s for s in sqlglot.parse(sql, read='duckdb') if s is not None]
    except (ParseError, Exception):  # noqa: BLE001  (any parser failure falls back to the identifier scan)
        statements = None
    if statements:
        found = set()
        for s in statements:
            ctes = {cte.alias for cte in s.find_all(exp.CTE)}
            for t in s.find_all(exp.Table):
                if t.db == '' and t.name in ctes:
                    continue
                key = (SECOND_SCHEMA + '.' + t.name) if t.db == SECOND_SCHEMA else t.name
                if key in listed:
                    found.add(key)
        return found
    found, text = set(), sql
    for name in sorted(listed, key=len, reverse=True):
        pattern = r'(?<![A-Za-z0-9_.])' + re.escape(name).replace(r'\.', r'\s*\.\s*') + r'(?![A-Za-z0-9_])'
        if re.search(pattern, text, flags=re.I):
            found.add(name)
            text = re.sub(pattern, ' ', text, flags=re.I)
    return found


def lookalikes_read(sql):
    return sorted(tables_read(sql) & set(DECOYS))


def schema_listing():
    return json.loads((ROOT / SCHEMA_LISTING).read_text(encoding='utf-8'))


def note_text():
    return (ROOT / NOTE).read_text(encoding='utf-8')


def common_message():
    """The published bare-schema system message, with the round's eighteen-table listing as the physical schema."""
    common = PROTOCOL + '\nAllowed functions: ' + ', '.join(sorted(FUNCTIONS))
    return common + '\nPhysical schema (names and types):\n' + json.dumps(schema_listing(), sort_keys=True)


def messages(question, arm):
    if arm not in ARMS:
        raise ValueError('Unknown arm')
    result = [{'role': 'system', 'content': common_message()}]
    if arm == 'note':
        result.append({'role': 'system', 'content': note_text()})
    result.append({'role': 'user', 'content': question['text']})
    return result


def api_request(question, arm, model):
    """The request body for a hosted model: the published settings of that model, system text as system blocks."""
    prompt = messages(question, arm)
    settings = model['settings']
    body = {'model': model['id'], 'max_tokens': settings['max_tokens'],
            'system': [{'type': 'text', 'text': m['content']} for m in prompt[:-1]],
            'messages': [{'role': 'user', 'content': prompt[-1]['content']}]}
    if settings.get('thinking') is not None:
        body['thinking'] = settings['thinking']
    body['output_config'] = {'effort': settings['effort'], 'format': {'type': 'json_schema', 'schema': ANSWER_SCHEMA}}
    return body


def cli_prompt(question, arm):
    """The same text for a command-line agent, as one message: the system text, then the question."""
    prompt = messages(question, arm)
    return '\n\n'.join(m['content'] for m in prompt[:-1]) + '\n\nQuestion: ' + prompt[-1]['content'] + '\n'


def request_hash(obj):
    return hashlib.sha256(json.dumps(obj, sort_keys=True, ensure_ascii=False).encode()).hexdigest()


def assert_arm_contract(question, model):
    """The note request equals the no-note request plus exactly one system block at position 1."""
    bare, noted = api_request(question, 'no_note', model), api_request(question, 'note', model)
    inserted = noted['system'].pop(1)
    assert inserted == {'type': 'text', 'text': note_text()}
    assert noted == bare, 'Arm differences exceed the note'
    return True


# Scoring: the published rubric (banking/scoring.py) over the round's database, plus the tables each answer read.
def substitute(sql, shadow, decoy):
    """The answer-key SQL with one table swapped for a look-alike (used to declare which questions each one changes)."""
    schema, _, name = decoy.rpartition('.')

    def swap(node):
        if isinstance(node, exp.Table) and node.name == shadow and node.db == '':
            swapped = exp.to_table(decoy if schema else name, dialect='duckdb')
            swapped.set('alias', node.args.get('alias') or exp.TableAlias(this=exp.to_identifier(shadow)))
            return swapped
        return node
    return sqlglot.parse_one(sql, read='duckdb').transform(swap).sql(dialect='duckdb')


def detectability(questions, sandbox):
    """For each look-alike: the analytical questions whose answer-key SQL reads its table, and those where reading
    the look-alike instead gives a different answer (a wrong table that is visible in the score)."""
    out = {}
    for decoy, info in DECOYS.items():
        uses, changes = [], []
        for q in questions:
            if q['kind'] != 'analytical' or info['shadows'] not in tables_read(q['gold_sql']):
                continue
            uses.append(q['id'])
            gold = sandbox.run(q['gold_sql'])['rows']
            swapped = sandbox.run(substitute(q['gold_sql'], info['shadows'], decoy))['rows']
            if not rows_equal(swapped, gold, ordered=q['ordered'], atol=0, rtol=0):
                changes.append(q['id'])
        out[decoy] = {'kind': info['kind'], 'shadows': info['shadows'], 'questions_reading_table': uses,
                      'questions_answer_changes': changes}
    return out


def is_method_failure(record):
    """Provider or harness failures: no answer reached the scorer for a reason outside the model's answer."""
    if record.get('error'):
        return True
    if record.get('response') is None:
        return True
    if record.get('stop_reason') == 'max_tokens':
        try:
            json.loads(record['response'])
        except (TypeError, ValueError):
            return True
    return False


def score_record(question, record, gold, sandbox):
    from .scoring import score
    if is_method_failure(record):
        return {'question_id': question['id'], 'arm': record['arm'], 'kind': question['kind'], 'correct': False,
                'status': 'method_failure', 'sql': None, 'rows': None, 'lookalikes': []}
    result = score(question, {'arm': record['arm'], 'status': 'response', 'response': record['response']}, gold, sandbox)
    result['lookalikes'] = lookalikes_read(result.get('sql'))
    return result


def mean_interval(diffs, replicates=10000, seed=7):
    """Paired percentile bootstrap of the mean per-question difference (the published current-model method)."""
    rng = random.Random(seed)
    n = len(diffs)
    boot = sorted(sum(rng.choices(diffs, k=n)) / n for _ in range(replicates))
    return [boot[int(.025 * (replicates - 1))], boot[int(.975 * (replicates - 1))]]


def model_summary(questions, outcomes, model_id, repeats):
    """outcomes: dicts with question_id, arm, repeat, status, correct, lookalikes (one per run, reruns resolved)."""
    index = {(o['question_id'], o['arm'], o['repeat']): o for o in outcomes if o['model'] == model_id}
    analytical = [q['id'] for q in questions if q['kind'] == 'analytical']
    ids = [q['id'] for q in questions]
    arms = {}
    for arm in ARMS:
        runs = [index[i, arm, r] for i in ids for r in repeats if (i, arm, r) in index]
        valid = [o for o in runs if o['status'] != 'method_failure']
        a_valid = [o for o in valid if o['question_id'] in analytical]
        read = [o for o in a_valid if o['lookalikes']]
        by_kind = {k: sum(any(DECOYS[d]['kind'] == k for d in o['lookalikes']) for o in a_valid) for k in KINDS}
        by_table = {t: sum(any(DECOYS[d]['shadows'] == t for d in o['lookalikes']) for o in a_valid) for t in SHADOWED}
        by_decoy = {d: sum(d in o['lookalikes'] for o in a_valid) for d in DECOYS}
        per_repeat = [sum(index[i, arm, r]['correct'] for i in ids if (i, arm, r) in index) for r in repeats]
        all_read = [o for o in valid if o['lookalikes']]
        arms[arm] = {
            'runs': len(runs), 'method_failures': len(runs) - len(valid),
            'analytical_answers': len(a_valid), 'lookalike_answers': len(read),
            'lookalike_share': (len(read) / len(a_valid)) if a_valid else None,
            'lookalike_answers_correct': sum(o['correct'] for o in read),
            'lookalike_answers_all_questions': len(all_read),
            'sql_answers_analytical': sum(o['sql'] is not None for o in a_valid),
            'by_kind': by_kind, 'by_table': by_table, 'by_decoy': by_decoy,
            'correct_per_repeat': per_repeat, 'mean_correct': sum(per_repeat) / len(per_repeat),
            'statuses': _count(o['status'] for o in runs),
        }

    def share(i, arm, field):
        vals = [index[i, arm, r] for r in repeats if (i, arm, r) in index and index[i, arm, r]['status'] != 'method_failure']
        if not vals:
            return None
        return sum((bool(o['lookalikes']) if field == 'read' else bool(o['correct'])) for o in vals) / len(vals)

    comparison = {}
    for field, pool in (('read', analytical), ('correct', ids)):
        pairs = [(share(i, 'no_note', field), share(i, 'note', field)) for i in pool]
        kept = [(a, b) for a, b in pairs if a is not None and b is not None]
        diffs = [b - a for a, b in kept]
        comparison[field] = {'questions': len(kept), 'dropped_questions': len(pairs) - len(kept),
                             'no_note_mean': sum(a for a, _ in kept) / len(kept), 'note_mean': sum(b for _, b in kept) / len(kept),
                             'difference': sum(diffs) / len(diffs), 'interval': mean_interval(diffs)}
    return {'model': model_id, 'arms': arms, 'note_minus_no_note': comparison}


def _count(values):
    out = {}
    for v in values:
        out[v] = out.get(v, 0) + 1
    return dict(sorted(out.items()))

