"""Reproduce WSI event sensitivity release 0.11 with Python's standard library.

Save wsi-event-catalogue-v0.11.json beside this script, then run:
    python3 wsi-event-sensitivity-v0.11.py
The output contains every combined scenario and every single-input comparison.
Source counts are held fixed. These are illustrative assumptions, not statistical
confidence intervals, probabilities, or bounds on possible burden.
"""
import json
import math
from pathlib import Path


def calculate(data):
    profiles = {p['id']: p for p in data['profiles']}
    reference = data['reference']
    output = []
    for event in data['events']:
        components = event['components']
        scenarios = []
        for scenario in ['lower', 'central', 'higher']:
            parts = []
            for component in components:
                p = profiles[component['profile']]
                days = p['days'] if scenario == 'central' else p['lowDays' if scenario == 'lower' else 'highDays']
                intensity = p['intensity'] if scenario == 'central' else p['lowIntensity' if scenario == 'lower' else 'highIntensity']
                total = component['count'] * days * 24 * intensity / reference
                parts.append({'componentId': component['id'], 'profile': p['id'], 'count': component['count'],
                              'days': days, 'intensity': intensity, 'estimatedUSU': total})
            scenarios.append({'id': scenario, 'components': parts,
                              'estimatedUSU': sum(p['estimatedUSU'] for p in parts)})
        individual = []
        for component in components:
            p = profiles[component['profile']]
            for variable in ['days', 'intensity']:
                result = {'componentId': component['id'], 'variable': variable}
                for direction, prefix in [('lower', 'low'), ('higher', 'high')]:
                    value = p[prefix + ('Days' if variable == 'days' else 'Intensity')]
                    total = 0
                    for other in components:
                        days, intensity = other['days'], other['intensity']
                        if other['id'] == component['id']:
                            if variable == 'days':
                                days = value
                            else:
                                intensity = value
                        total += other['count'] * days * 24 * intensity / reference
                    result[direction + 'Input'] = value
                    result[direction + 'EstimatedUSU'] = total
                individual.append(result)
        assert math.isclose(scenarios[1]['estimatedUSU'], event['estimatedUSU'], rel_tol=1e-12)
        output.append({'eventId': event['id'], 'slug': event['slug'], 'scenarios': scenarios, 'oneAtATime': individual})
    return {'dataRelease': data['version'], 'referenceIntensityHours': reference,
            'countsHeldFixed': True, 'interpretation': data['sensitivityPolicy']['interpretation'], 'events': output}


if __name__ == '__main__':
    source = Path(__file__).with_name('wsi-event-catalogue-v0.11.json')
    print(json.dumps(calculate(json.loads(source.read_text())), indent=2))
