"""One-at-a-time sensitivity sweep of the E1 base case, with the study's own plan() and rollout_probability().

Each row changes one input and keeps every other input at its value in assumptions.json. Two outputs per row: the
accounts needed for the target power (plan), and the chance that a test of the base-case size reaches a rollout decision
at the row's true gain (rollout_probability). Standard library only; nothing is random.
"""
import argparse
import json
import math
from pathlib import Path
from power import plan, rollout_probability

ROOT = Path(__file__).resolve().parent
INPUTS = ('gain', 'p0', 'users_per_account', 'icc')


def sweep(assumptions, declared):
    """The sweep rows, in declared order, for every input in INPUTS."""
    p0, m, power = assumptions['p0'], assumptions['users_per_account'], assumptions['power']
    gain, icc = assumptions.get('practical_threshold', assumptions['p1'] - p0), assumptions['base_icc']
    alpha = assumptions['family_alpha'] / assumptions['primary_hypotheses']
    base_arm = plan(p0, p0 + gain, alpha, power, m, icc)['accounts_per_arm']
    base = {'gain': gain, 'p0': p0, 'users_per_account': m, 'icc': icc}
    values = {'gain': declared['gain_values'], 'p0': declared['p0_values'],
              'users_per_account': declared['users_per_account_values'], 'icc': declared['icc_values']}
    sweeps = []
    for name in INPUTS:
        if len(set(values[name])) != len(values[name]):
            raise ValueError('Sweep values must be unique: ' + name)
        rows = []
        for value in values[name]:
            row = base | {name: value}
            sized = plan(row['p0'], row['p0'] + row['gain'], alpha, power, row['users_per_account'], row['icc'])
            chance = rollout_probability(row['p0'], row['gain'], alpha, base_arm, row['users_per_account'], row['icc'])
            rows.append({'value': value, 'is_base': math.isclose(value, base[name], abs_tol=1e-12), 'p0': row['p0'], 'gain': row['gain'],
                         'users_per_account': row['users_per_account'], 'icc': row['icc'],
                         'accounts_per_arm': sized['accounts_per_arm'], 'total_accounts': sized['total_accounts'],
                         'chance_at_base_size': chance})
        sweeps.append({'input': name, 'rows': rows})
    return {'status': 'Hypothetical planning sweep, not observed outcomes',
            'method': declared['method'], 'seed': declared['seed'],
            'base': base | {'alpha': alpha, 'power': power, 'accounts_per_arm': base_arm, 'total_accounts': base_arm * 2},
            'sweeps': sweeps}


def calculate_sweep():
    load = lambda name: json.loads((ROOT / name).read_text(encoding='utf-8'))
    return sweep(load('assumptions.json'), load('sensitivity-inputs.json'))


def main():
    argparse.ArgumentParser(description='Print the sensitivity sweep as JSON; writes nothing.').parse_args()
    print(json.dumps(calculate_sweep(), indent=2))


if __name__ == '__main__':
    main()
