#!/usr/bin/env python3
"""Fictional methods example, Python 3.10+ standard library, no network.
Not participant software, a preregistration, or a validated analysis pipeline.
Run: python3 permutation_example.py --out reproduced
"""
import argparse
import csv
import hashlib
import itertools
import json
import math
import platform
import random
from collections import Counter, defaultdict
from dataclasses import asdict, dataclass, replace
from fractions import Fraction
from pathlib import Path

ACTIONS = ('up', 'down', 'left', 'right')
NONE = 'nothing_sent'
SEEDS = dict(data=20261022, target_shuffle=2201062,
             condition_shuffle=2201063, iid_target_redraw=2201064)

@dataclass(frozen=True)
class Trial:
    pair: str
    session: int
    trial: int
    condition: str
    target: str
    response: str
    eligible: bool

def groups(rows, fields):
    out = defaultdict(list)
    for j, r in enumerate(rows):
        out[tuple(getattr(r, f) for f in fields)].append(j)
    return dict(sorted(out.items()))

def synthetic(allow_none=False):
    """4 fictional pairs, 2 sessions, 12 trials/session; NOT a new schedule.
    6/6 condition allocation; iid uniform targets with replacement. Biased
    persistent guesses and fixed omissions/masks are independent of assignments.
    Optional none responses are added afterwards to preserve both allocations.
    """
    rng = random.Random(SEEDS['data'])
    rows = []
    for pair in range(4):
        for session in (1, 2):
            labels = ['S'] * 6 + ['C'] * 6
            rng.shuffle(labels)
            previous = ACTIONS[(pair + session) % 4]
            for trial, condition in enumerate(labels, 1):
                target = rng.choice(ACTIONS)
                if rng.random() >= .65:
                    previous = rng.choices(ACTIONS, weights=[7, 1, 1, 1])[0]
                response = previous
                if (pair * 24 + (session - 1) * 12 + trial) % 31 == 0:
                    response = ''
                eligible = (pair * 24 + session * 12 + trial) % 47 != 0
                rows.append(Trial(f'synthetic_pair_{pair+1}', session, trial,
                                  condition, target, response, eligible))
    if allow_none:
        rows = [replace(r, response=NONE) if r.response and j % 19 == 0 else r
                for j, r in enumerate(rows)]
    return rows

def hit(row, target):
    return int(row.eligible and row.response == target)

def statistic(rows, targets=None, conditions=None):
    """All scheduled denominators; equal pair weights; sessions retained."""
    totals = defaultdict(lambda: {'S': [0, 0], 'C': [0, 0]})
    for j, r in enumerate(rows):
        c = r.condition if conditions is None else conditions[j]
        t = r.target if targets is None else targets[j]
        totals[r.pair][c][0] += hit(r, t)
        totals[r.pair][c][1] += 1
    means = []
    for c in ('S', 'C'):
        means.append(sum(Fraction(v[c][0], v[c][1]) for v in totals.values()) / len(totals))
    return means[0], means[1], means[0] - means[1]

def expectations(rows, conditional=True):
    hits = defaultdict(lambda: {'S': Fraction(0), 'C': Fraction(0)})
    denominators = Counter((r.pair, r.condition) for r in rows)
    for (pair, session, c), indices in groups(rows, ('pair', 'session', 'condition')).items():
        targets = Counter(rows[j].target for j in indices)
        responses = Counter(rows[j].response for j in indices if rows[j].eligible)
        if conditional:
            hits[pair][c] += sum(Fraction(targets[a] * responses[a], len(indices)) for a in ACTIONS)
        else:
            hits[pair][c] += Fraction(sum(responses[a] for a in ACTIONS), 4)
    means = [sum(hits[p][c] / denominators[p, c] for p in hits) / len(hits) for c in ('S', 'C')]
    return means[0], means[1], means[0] - means[1]

def shuffled(rows, field, blocks, rng):
    values = [getattr(r, field) for r in rows]
    for indices in blocks.values():
        labels = [getattr(rows[j], field) for j in indices]
        rng.shuffle(labels)
        for j, label in zip(indices, labels):
            values[j] = label
    return values

def tail(observed, draws, expected):
    b = len(draws)
    extreme = sum(x >= observed for x in draws)
    p = (extreme + 1) / (b + 1)
    return dict(observed=float(observed), draws=b, extreme_or_tied_draws=extreme,
                p_plus_one=p, p_resolution=1/(b+1),
                approx_mc_se=math.sqrt(p*(1-p)/(b+1)),
                null_mean_simulated=sum(map(float, draws))/b,
                null_mean_analytic=float(expected), status='synthetic illustration only')

def analyse(rows, b):
    tb = groups(rows, ('pair', 'session', 'condition'))
    cb = groups(rows, ('pair', 'session'))
    tr = random.Random(SEEDS['target_shuffle'])
    cr = random.Random(SEEDS['condition_shuffle'])
    rr = random.Random(SEEDS['iid_target_redraw'])
    target_s, condition_delta, redraw_s = [], [], []
    for _ in range(b):
        target_s.append(statistic(rows, targets=shuffled(rows, 'target', tb, tr))[0])
        condition_delta.append(statistic(rows, conditions=shuffled(rows, 'condition', cb, cr))[2])
        redraw_s.append(statistic(rows, targets=[rr.choice(ACTIONS) for _ in rows])[0])
    obs, cond, iid = statistic(rows), expectations(rows), expectations(rows, False)
    return dict(scheduled_trials=len(rows), pairs=len({r.pair for r in rows}),
        response_counts=dict(sorted(Counter(r.response or 'omitted' for r in rows).items())),
        observed_pair_mean_S_C_delta=list(map(float, obs)),
        conditional_null_mean_S_C_delta=list(map(float, cond)),
        iid_target_null_mean_S_C_delta=list(map(float, iid)),
        target_shuffle_sensitivity=tail(obs[0], target_s, cond[0]),
        condition_shuffle_sensitivity=tail(obs[2], condition_delta, Fraction(0)),
        iid_target_redraw_reference=tail(obs[0], redraw_s, iid[0]))

def exact_checks():
    targets = ['up', 'up', 'down', 'right']
    responses = ['up', 'up', 'up', 'right']
    permutations = set(itertools.permutations(targets))
    counts = [sum(a == b for a, b in zip(responses, p)) for p in permutations]
    assert len(permutations) == 12
    assert Fraction(sum(counts), len(counts)) == Fraction(7, 4)
    assert Fraction(sum(x >= 3 for x in counts), len(counts)) == Fraction(1, 4)
    # A deliberate invalid global shuffle crosses condition boundaries:
    bad_targets, fixed_responses = ['down']*4 + ['up']*4, ['up']*4 + ['down']*4
    bad_perms = set(itertools.permutations(bad_targets))
    assert sum(sum(a == b for a, b in zip(fixed_responses, p)) for p in bad_perms)/len(bad_perms) == 4
    # Restricted shuffle has exactly zero matches in this counterexample.
    assert sum(a == b for a, b in zip(fixed_responses, bad_targets)) == 0
    # Conditioning on all-up targets leaves no variation and gives p=1.
    assert set(itertools.permutations(['up']*4)) == {('up',)*4}
    assert sum(q*Fraction(1,4) for q in [Fraction(7,10), Fraction(1,10), Fraction(1,10), Fraction(1,10)]) == Fraction(1,4)
    rows = synthetic()
    before = tuple(rows)
    rng = random.Random(12345)
    for _ in range(20):
        for field, fields in [('target', ('pair','session','condition')), ('condition', ('pair','session'))]:
            blocks = groups(rows, fields)
            values = shuffled(rows, field, blocks, rng)
            for indices in blocks.values():
                assert Counter(values[j] for j in indices) == Counter(getattr(rows[j], field) for j in indices)
    assert tuple(rows) == before
    assert [(r.target,r.condition) for r in synthetic(True)] == [(r.target,r.condition) for r in rows]
    return dict(tiny_unique_target_permutations=12, tiny_observed_hits=3,
                tiny_exact_null_expected_hits=1.75, tiny_exact_upper_tail_p=.25,
                invalid_global_shuffle_expected_hits=4,
                correct_within_condition_shuffle_expected_hits=0,
                constant_target_conditional_p=1.0,
                invariants='response sequences, masks, order, pair and session membership fixed; assignment margins preserved within specified blocks')

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--out', type=Path, default=Path('reproduced'))
    parser.add_argument('--draws', type=int, default=9999)
    args = parser.parse_args()
    if args.draws < 1:
        parser.error('--draws must be positive')
    args.out.mkdir(parents=True, exist_ok=True)
    result = dict(status='SYNTHETIC ONLY: no participant testing or statistical validation',
                  python=platform.python_version(), date='2026-10-22', seeds=SEEDS,
                  draws_per_test=args.draws, checks=exact_checks(), examples={})
    for key, allow_none in [('four_action_current_design', False), ('optional_none_alternative_NOT_ADOPTED', True)]:
        rows = synthetic(allow_none)
        file = args.out / f'{key}.csv'
        with file.open('w', newline='', encoding='utf-8') as stream:
            writer = csv.DictWriter(stream, fieldnames=list(asdict(rows[0])))
            writer.writeheader()
            writer.writerows(asdict(r) for r in rows)
        result['examples'][key] = analyse(rows, args.draws)
        result['examples'][key]['csv_sha256'] = hashlib.sha256(file.read_bytes()).hexdigest()
    (args.out/'results.json').write_text(json.dumps(result, indent=2)+'\n', encoding='utf-8')
    print(json.dumps(result, indent=2))

if __name__ == '__main__':
    main()
