import itertools
import math
import unittest
from decimal import Decimal, localcontext
from model import cohort, results


class ProbabilityTests(unittest.TestCase):
    def test_three_seconds_is_not_exclusion(self):
        row = cohort(20, 3, 1)
        self.assertAlmostEqual(row["expected_refresh_starts"], 20 * math.exp(-3), places=14)
        self.assertGreater(row["probability_multiple_refreshes"], 0.25)
        self.assertGreater(row["probability_no_refresh"], 0.35)

    def test_independent_convolution_oracle(self):
        for m, r, delta, beta in itertools.product(range(9), (0, 0.1, 1, 3, 10), (0.5, 2), (0.5, 1, 3)):
            with localcontext() as context:
                context.prec = 80
                p = (-Decimal(str(r)) / Decimal(str(delta)) / Decimal(str(beta))).exp()
                distribution = [Decimal(1)]
                for _ in range(m):
                    new = [Decimal(0)] * (len(distribution) + 1)
                    for k, mass in enumerate(distribution):
                        new[k] += mass * (1-p)
                        new[k+1] += mass * p
                    distribution = new
                actual = cohort(m, r, delta, beta)
                self.assertAlmostEqual(actual["probability_no_refresh"], float(distribution[0]), places=14)
                self.assertAlmostEqual(actual["probability_multiple_refreshes"], float(sum(distribution[2:])), places=14)

    def test_probabilities_sum_to_one(self):
        for row in results()["rows"]:
            total = sum(row[k] for k in ("probability_no_refresh", "probability_exactly_one", "probability_multiple_refreshes"))
            self.assertAlmostEqual(total, 1, places=15)

    def test_zero_and_one_request(self):
        self.assertEqual(cohort(0, 3, 1)["probability_no_refresh"], 1)
        self.assertEqual(cohort(1, 3, 1)["probability_multiple_refreshes"], 0)

    def test_deadline(self):
        for m in (0, 1, 20):
            row = cohort(m, 0, 1)
            self.assertEqual(row["expected_refresh_starts"], m)
            self.assertEqual(row["probability_multiple_refreshes"], int(m >= 2))

    def test_unit_invariance(self):
        for key in ("per_request_refresh_probability", "probability_multiple_refreshes"):
            self.assertEqual(cohort(20, 3, 1)[key], cohort(20, 3000, 1000)[key])

    def test_more_early_refresh_with_larger_scale(self):
        self.assertGreater(cohort(20, 3, 1, 2)["expected_refresh_starts"], cohort(20, 3, 1, 1)["expected_refresh_starts"])

    def test_small_tail_does_not_cancel(self):
        self.assertGreater(cohort(20, 50, 1)["probability_multiple_refreshes"], 0)
        self.assertAlmostEqual(cohort(20, 50, 1)["probability_multiple_refreshes"] / (190 * math.exp(-100)), 1, places=14)

    def test_float_boundary_scales(self):
        for m in (0, 1, 20, 1000):
            row = cohort(m, 1e308, 5e-324, 5e-324)
            self.assertEqual(row["probability_no_refresh"], 1)
            self.assertEqual(row["expected_refresh_starts"], 0)
            row = cohort(m, 5e-324, 1e308, 1e308)
            self.assertEqual(row["expected_refresh_starts"], m)

    def test_unrepresentable_decimal_inputs(self):
        for value in (Decimal("1e10000"), Decimal("1e-10000")):
            for field in (1, 2, 3):
                args = [20, 3, 1, 1]
                args[field] = value
                with self.assertRaises(ValueError):
                    cohort(*args)

    def test_invalid_inputs(self):
        for m in (-1, 1001, 1.5, True, "20"):
            with self.assertRaises(ValueError):
                cohort(m, 3, 1)
        for bad in (-1, float("inf"), float("nan"), True, "1", None):
            for field in (1, 2, 3):
                args = [20, 3, 1, 1]
                args[field] = bad
                with self.assertRaises(ValueError):
                    cohort(*args)
        for args in ((20, 3, 0), (20, 3, 1, 0)):
            with self.assertRaises(ValueError):
                cohort(*args)


if __name__ == "__main__":
    unittest.main()
