#!/usr/bin/env python3
"""Independent checker: counterexample to the affirmative form of Question 4.8
of Almiron & Moyano-Fernandez (arXiv:2012.01358v3).

Statement tested: "every numerical semigroup Gamma with mu_Gamma <= 4 has a
gap g with W(g) >= 0".  A certificate refutes it by exhibiting ONE numerical
semigroup Gamma with mu_Gamma <= 4, at least one gap, and W(g) < 0 for EVERY gap.

Definitions (statement.md, cross-checked with the arXiv HTML of v3):
  c(Gamma)     = F(Gamma)+1, F = largest gap
  delta(Gamma) = #{x in Gamma : x < c(Gamma)}
  W_Gamma(k)   = k*delta(Gamma) - c(Gamma);  mu = min{k in N : W_Gamma(k) >= 0}
  Delta_g      = Gamma u (g+Gamma)  (semimodule minimally generated by [0,g])
  c(Delta)     = (largest element of N \\ Delta) + 1,
  delta(Delta) = #{x in Delta : x < c(Delta)}
  W(g)         = 2*delta(Delta_g) - c(Delta_g)
All arithmetic is on Python ints.  Standard library only.
"""
import json
import sys

MAX_FROB = 20000  # size guard so the quadratic closure test stays fast


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


def is_int(x):
    return isinstance(x, int) and not isinstance(x, bool)


def main():
    if len(sys.argv) != 2:
        fail("usage: python3 checker.py certificate.json")
    try:
        with open(sys.argv[1], "r") as fh:
            cert = json.load(fh)
    except Exception as e:  # malformed file
        fail("cannot read/parse certificate: %r" % (e,))
    if not isinstance(cert, dict) or "semigroup_gaps" not in cert:
        fail("certificate is not a JSON object with field 'semigroup_gaps'")
    gaps = cert["semigroup_gaps"]
    if not isinstance(gaps, list) or not all(is_int(x) for x in gaps):
        fail("'semigroup_gaps' must be a list of integers")
    if len(gaps) == 0:
        fail("no gaps: Gamma = N is a degenerate case, not accepted as a counterexample")
    if any(x <= 0 for x in gaps):
        fail("gaps must be positive (0 must belong to Gamma)")
    if len(set(gaps)) != len(gaps):
        fail("gaps are not distinct")
    G = set(gaps)
    F = max(G)
    if F > MAX_FROB:
        fail("largest gap exceeds the size guard %d" % MAX_FROB)

    # ---- Gamma = N \ G.  Membership test valid for every natural number.
    def in_gamma(x):
        return x >= 0 and x not in G

    c = F + 1
    small = [x for x in range(c) if x not in G]  # elements of Gamma below c
    # (1) submonoid: 0 in Gamma (gaps are positive), finite complement (G finite),
    # closed under addition.  A sum a+b can fail to lie in Gamma only if it is a
    # gap, hence <= F, hence a,b <= F; so testing pairs from `small` is complete.
    assert in_gamma(0)
    for i, a in enumerate(small):
        if a == 0:
            continue
        for b in small[i:]:
            s = a + b
            if s > F:
                break
            if s in G:
                fail("not closed under addition: %d + %d = %d is a gap" % (a, b, s))

    # (2) conductor, delta, mu
    # c is the least c with c+N in Gamma: F = c-1 is a gap, everything >= c is in Gamma.
    delta = len(small)
    if delta != c - len(G):
        fail("internal inconsistency in delta(Gamma)")
    if delta < 1:
        fail("internal inconsistency: delta < 1")
    mu = 0
    while mu * delta - c < 0:
        mu += 1
    print("Gamma: gaps=%s  c=%d  delta=%d  mu=%d" % (sorted(G), c, delta, mu))
    if mu > 4:
        fail("mu_Gamma = %d > 4, hypothesis of the statement not met" % mu)

    # (3) every gap
    W4 = 4 * delta - c
    for g in sorted(G):
        # Delta_g = Gamma u (g + Gamma).  Every x >= c lies in Gamma, so
        # N \ Delta_g is contained in [0, c-1]; scan that range exhaustively.
        def in_delta(x):
            return in_gamma(x) or in_gamma(x - g)

        # Delta_g must be a Gamma-semimodule (automatic for a monoid Gamma, but
        # re-verified): x in Delta_g, s in Gamma => x+s in Delta_g.  Only sums
        # < c can fail.
        dl_small = [x for x in range(c) if in_delta(x)]
        dl_gaps = [x for x in range(c) if not in_delta(x)]
        for x in dl_small:
            for s in small:
                if x + s >= c:
                    break
                if not in_delta(x + s):
                    fail("Delta_%d is not a Gamma-semimodule" % g)
        # independent brute-force rebuild of Delta_g on [0, c+g] as a set union
        lim = c + g
        gam = set(x for x in range(lim + 1) if x not in G)
        union = gam | set(x + g for x in gam if x + g <= lim)
        if set(x for x in range(lim + 1) if x not in union) != set(dl_gaps):
            fail("two constructions of Delta_%d disagree" % g)

        cD = (max(dl_gaps) + 1) if dl_gaps else 0
        dD = sum(1 for x in range(cD) if in_delta(x))
        Wg = 2 * dD - cD
        print("g=%d: c(Delta)=%d delta(Delta)=%d W(g)=%d" % (g, cD, dD, Wg))
        # sanity: paper's Theorem 4.2 (W(g) <= W_Gamma(4)) pins the sign convention
        if Wg > W4:
            fail("W(%d)=%d exceeds W_Gamma(4)=%d, contradicting Theorem 4.2; "
                 "definitions misapplied" % (g, Wg, W4))
        if Wg >= 0:
            fail("gap g=%d has W(g)=%d >= 0; not a counterexample" % (g, Wg))

    print("Numerical semigroup with mu=%d <= 4 and W(g) < 0 for all %d gaps: "
          "the statement is refuted." % (mu, len(G)))
    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    main()
