#!/usr/bin/env python3
"""Usage: python3 verify.py certificate.json

Checks, with integer arithmetic only, that the set Gamma = N \\ semigroup_gaps
is a numerical semigroup with mu_Gamma <= 4 for which EVERY gap g has
W(g) = 2*delta(Delta_g) - c(Delta_g) < 0, where Delta_g = Gamma u (g + Gamma).
Standard library only.
"""
import json
import sys


def fail(msg):
    print("FAILED: " + msg)
    sys.exit(1)


def main():
    if len(sys.argv) != 2:
        fail("usage: python3 verify.py certificate.json")
    with open(sys.argv[1]) as f:
        cert = json.load(f)
    gaps = cert.get("semigroup_gaps")
    if not isinstance(gaps, list) or not gaps:
        fail("semigroup_gaps must be a non-empty list")
    for x in gaps:
        if type(x) is not int or x <= 0:
            fail("gaps must be positive integers (0 must belong to Gamma)")
    if len(set(gaps)) != len(gaps):
        fail("gaps must be distinct")
    if len(gaps) > 5000 or max(gaps) > 100000:
        fail("certificate too large for this verifier")
    G = frozenset(gaps)
    F = max(G)

    # Gamma = N \ G.  Finite complement holds by construction; 0 is in Gamma.
    def in_gamma(n):
        return n >= 0 and n not in G

    # Closure under addition: a+b > F is never a gap, so only a+b <= F matters.
    for a in range(F + 1):
        if in_gamma(a):
            for b in range(a, F + 1 - a):
                if in_gamma(b) and not in_gamma(a + b):
                    fail("not closed under addition: %d + %d" % (a, b))

    # Conductor: least c with c + N inside Gamma  =  (largest gap) + 1.
    c = F + 1
    delta = sum(1 for n in range(c) if in_gamma(n))
    print("Gamma: gaps =", sorted(G), " c =", c, " delta =", delta)

    # mu = min{k in N : k*delta - c >= 0}; search k = 0..4 only (need mu <= 4).
    mu = None
    for k in range(0, 5):
        if k * delta - c >= 0:
            mu = k
            break
    if mu is None:
        fail("mu_Gamma > 4, hypothesis of the question not met")
    print("mu_Gamma =", mu, "(<= 4)")

    # Every gap g: Delta_g = Gamma u (g + Gamma), a Gamma-semimodule in N.
    for g in sorted(G):
        def in_delta(n, g=g):
            return in_gamma(n) or in_gamma(n - g)
        # Every n >= c lies in Gamma, hence in Delta_g: all gaps of Delta_g are < c.
        non = [n for n in range(c) if not in_delta(n)]
        cd = (max(non) + 1) if non else 0          # conductor of Delta_g
        for n in range(cd, c + g + 1):              # redundant sanity check
            if not in_delta(n):
                fail("internal conductor error")
        if cd > 0 and in_delta(cd - 1):
            fail("internal conductor error")
        # semimodule property Delta + Gamma inside Delta (redundant; finite window)
        for x in range(c):
            if in_delta(x):
                for s in range(c - x):
                    if in_gamma(s) and not in_delta(x + s):
                        fail("Delta_g is not a Gamma-semimodule")
        dd = sum(1 for n in range(cd) if in_delta(n))  # delta(Delta_g)
        W = 2 * dd - cd
        print("gap g = %d: c(Delta) = %d, delta(Delta) = %d, W(g) = %d" % (g, cd, dd, W))
        if W >= 0:
            fail("gap %d has W(g) >= 0; not a counterexample" % g)

    print("All %d gaps have W(g) < 0 while mu_Gamma = %d <= 4." % (len(G), mu))
    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        raise
    except Exception as e:  # any unexpected problem is a failure
        print("FAILED: %r" % (e,))
        sys.exit(1)
