"""Optional source audit, separate from the offline reproducibility command.

Usage: python code/extract_registry.py /path/to/downloaded/NCT04510194.json
The full source is a public GET at the URL recorded in data/registry-source.json.
The saved SHA-256 identifies the version inspected; future updates may differ.
"""
import hashlib
import json
from pathlib import Path
import sys

blob = Path(sys.argv[1]).read_bytes()
root = Path(__file__).resolve().parents[1]
expected = json.loads((root/'data/registry-source.json').read_text())
record = json.loads(blob)
assert record['protocolSection']['identificationModule']['nctId'] == expected['nct_id']
outcome = record['resultsSection']['outcomeMeasuresModule']['outcomeMeasures'][expected['outcome_index']]
assert outcome['title'] == 'Progression'
assert outcome['timeFrame'] == '28 days'
assert outcome['paramType'] == 'COUNT_OF_PARTICIPANTS'
groups = {g['id']:g['title'] for g in outcome['groups']}
assert groups['OG002'] == 'Active Ivermectin'
assert groups['OG003'] == 'Ivermectin Placebo'
assert len(outcome['denoms']) == len(outcome['classes']) == 1
assert len(outcome['classes'][0]['categories']) == 1
denoms = {r['groupId']:int(r['value']) for r in outcome['denoms'][0]['counts']}
events = {r['groupId']:int(r['value']) for r in outcome['classes'][0]['categories'][0]['measurements']}
counts = {'events_t':events['OG002'],'n_t':denoms['OG002'],'events_c':events['OG003'],'n_c':denoms['OG003']}
assert counts == expected['counts']
print(json.dumps({'counts':counts,'source_hash_matches':hashlib.sha256(blob).hexdigest()==expected['response_sha256']}))
