"""Expected counts in a synthetic population, not vendor performance."""
from math import isclose


def audit(n, prevalence, tpr, fpr):
    if not isinstance(n, int) or isinstance(n, bool) or n <= 0:
        raise ValueError('n must be a positive integer')
    if not all(0 <= x <= 1 for x in (prevalence, tpr, fpr)):
        raise ValueError('Rates must be in [0, 1]')
    tp = n * prevalence * tpr
    fn = n * prevalence * (1 - tpr)
    fp = n * (1 - prevalence) * fpr
    tn = n * (1 - prevalence) * (1 - fpr)
    precision = tp / (tp + fp) if tp + fp else None
    return tp, fp, fn, tn, precision


if __name__ == '__main__':
    tp, fp, fn, tn, precision = audit(100000, .001, .95, .01)
    assert isclose(tp, 95)
    assert isclose(fp, 999)
    assert isclose(fn, 5)
    assert isclose(tp + fp + fn + tn, 100000)
    assert isclose(precision, 95/1094)
    assert audit(100, 0, 1, 0)[4] is None
    assert audit(100, 1, 1, 0)[4] == 1
    try:
        audit(100, -.1, .95, .01)
    except ValueError:
        pass
    else:
        raise AssertionError('Invalid rate accepted')
    print(f'TP={tp:.0f}, FP={fp:.0f}, FN={fn:.0f}, TN={tn:.0f}')
    print(f'Alert precision={100*precision:.2f}%')
    print('8 checks passed')
