"""Sanity check for the bounds on the minimum random-arc subcover.

Circle of circumference 1. Arc j (j >= m) is open, has length c/j and a uniform
random centre. N = least number of arcs whose union is the whole circle.

For each trial we draw arcs m..J, and compute
  K  = number of arcs not contained in any single earlier arc   (upper bound on N)
  NJ = least number of arcs among m..J that cover the circle     (>= N; exact greedy)
  I  = (1/c) * integral of T(x), T(x) = first index covering x    (lower bound on N)
Theory (c > 1):  (m-1)/(c-1) = E[I] <= E[N] <= E[K] <= (e-1)m + 2 + e*m/(c-1).
"""
import math, random, sys


def trial(m, c, J, rng):
    arcs = []                                   # (start, length, index), start in [0,1)
    for j in range(m, J + 1):
        L = c / j
        arcs.append(((rng.random() - L / 2) % 1.0, L, j))

    # K: arcs not inside one earlier arc
    K = 0
    for a, (s, L, j) in enumerate(arcs):
        inside = False
        for (s2, L2, _) in arcs[:a]:
            if (s - s2) % 1.0 <= L2 - L:      # arc starts after s2 and ends before s2+L2
                inside = True
                break
        K += not inside

    # T(x) integral: sweep over breakpoints, earliest arc covering each piece
    pts = sorted({s for s, _, _ in arcs} | {(s + L) % 1.0 for s, L, _ in arcs} | {0.0})
    integral, covered = 0.0, True
    for a, b in zip(pts, pts[1:] + [1.0 + pts[0]]):
        mid = ((a + b) / 2) % 1.0
        first = next((j for s, L, j in arcs if 0 < (mid - s) % 1.0 < L), None)
        if first is None:
            covered = False
            first = J + 1                       # still a lower bound on T
        integral += (b - a) * first
    I = integral / c

    # NJ: exact minimum circular cover (try each arc as the first one, then greedy)
    NJ = None
    if covered:
        best = len(arcs) + 1
        for s0, L0, _ in arcs:
            reach, used = L0, 1                 # positions measured from s0
            rel = sorted(((s - s0) % 1.0, L) for s, L, _ in arcs)
            i, far = 0, L0
            while reach < 1.0 and used < best:
                while i < len(rel) and rel[i][0] < reach:
                    far = max(far, rel[i][0] + rel[i][1])
                    i += 1
                if far <= reach:
                    used = None
                    break
                reach, used = far, used + 1
            if used is not None and reach >= 1.0:
                best = min(best, used)
        NJ = best if best <= len(arcs) else None
    return K, NJ, I


def main():
    c = float(sys.argv[1]) if len(sys.argv) > 1 else 2.0
    trials = int(sys.argv[2]) if len(sys.argv) > 2 else 300
    rng = random.Random(1)
    print(f"c = {c}, {trials} trials, arcs m..60m")
    for m in (3, 5, 10, 20):
        J = 60 * m
        Ks, Ns, Is, bad = [], [], [], 0
        for _ in range(trials):
            K, NJ, I = trial(m, c, J, rng)
            Ks.append(K); Is.append(I)
            if NJ is None: bad += 1
            else: Ns.append(NJ)
        lo = (m - 1) / (c - 1)
        hi = (math.e - 1) * m + 2 + math.e * m / (c - 1)
        print(f"m={m:3d}  lower {lo:6.2f} | mean I {sum(Is)/trials:6.2f} | mean N_J {sum(Ns)/max(1,len(Ns)):6.2f}"
              f" | mean K {sum(Ks)/trials:6.2f} | upper {hi:6.2f} | uncovered by m..J: {bad}")


if __name__ == "__main__":
    main()
