"""Synthetic observation-rate sensitivity; no military capacity estimation."""
import argparse
import json
import math
from pathlib import Path


def adjusted_shares(counts, inclusion_rates):
    if not isinstance(counts, dict) or not isinstance(inclusion_rates, dict):
        raise ValueError('Expected count and rate mappings')
    if not counts or set(counts) != set(inclusion_rates):
        raise ValueError('Supply identical nonempty category sets')
    weighted = {}
    for category, count in counts.items():
        rate = inclusion_rates[category]
        if not isinstance(category, str) or not category:
            raise ValueError('Expected category labels')
        if type(count) is not int or count < 0:
            raise ValueError('Expected nonnegative integer observations')
        if type(rate) not in (int, float) or not math.isfinite(rate) or not 0 < rate <= 1:
            raise ValueError('Inclusion rate must be finite and greater than 0 through 1')
        weighted[category] = count / rate
        if not math.isfinite(weighted[category]):
            raise ValueError('Weighted count exceeds numeric range')
    total = sum(weighted.values())
    if not math.isfinite(total):
        raise ValueError('Total exceeds numeric range')
    return dict(adjusted_shares={key: value / total if total else None
                                for key, value in weighted.items()},
                inclusion_rates_assumed=True, production_estimated=False)


def self_test():
    counts = {'type-a': 20, 'type-b': 5}
    equal = adjusted_shares(counts, {'type-a': 1, 'type-b': 1})
    biased = adjusted_shares(counts, {'type-a': 0.2, 'type-b': 0.05})
    assert equal['adjusted_shares']['type-a'] == 0.8
    assert biased['adjusted_shares']['type-a'] == 0.5
    assert sum(biased['adjusted_shares'].values()) == 1
    assert biased['production_estimated'] is False
    assert adjusted_shares({'a': 0}, {'a': 1})['adjusted_shares']['a'] is None
    for rates in ({'type-a': 0, 'type-b': 1}, {'type-a': 1},
                  {'type-a': float('nan'), 'type-b': 1}):
        try:
            adjusted_shares(counts, rates)
        except ValueError:
            pass
        else:
            raise AssertionError('Invalid or unidentified observation rate accepted')
    print('8 synthetic checks passed; no external data or production estimate')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--self-test', action='store_true')
    parser.add_argument('--file', type=Path)
    args = parser.parse_args()
    if args.self_test:
        self_test()
    elif args.file:
        data = json.loads(args.file.read_text())
        print(json.dumps(adjusted_shares(data['counts'], data['inclusion_rates']), indent=2))
    else:
        parser.error('Choose --self-test or --file SYNTHETIC_INPUT_JSON')
