#!/usr/bin/env python3
"""Side check of the four-point witness of iis:2611.00029 (the audit of iis:2611.00008).

The audit states: A = {0000001, 0000010, 0000100, 2112222} is outside the cap C, and 20
deletions give a cap (C - D) union A with 220 points.  The audit does not list D.
This script builds the cap from the tables of the paper, computes the exact cost of A,
lists D, and tests the set (C - D) union A.  It reads no other file, and it imports the
construction and the tests from verify_q0002.py in the same directory.
usage: python3 -I check_four_witness.py
The script ends with the line "ALL CHECKS PASSED" or it stops with an error.
"""
import importlib.util
import itertools
import os
from collections import Counter

HERE = os.path.dirname(os.path.abspath(__file__))


def load_verifier():
    """Import verify_q0002.py from the directory of this script (the option -I does not add it)."""
    spec = importlib.util.spec_from_file_location("verify_q0002", os.path.join(HERE, "verify_q0002.py"))
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def main():
    V = load_verifier()
    cap = V.build_cap()
    V.check(V.coordinate_hash(cap) == V.PUBLISHED_HASH, "the cap has the published hash")
    pts = sorted(cap)
    A = [tuple(int(c) for c in s) for s in "0000001 0000010 0000100 2112222".split()]
    V.check(len(set(A)) == 4 and not (set(A) & cap), "A has 4 different points, and none is in the cap")
    thirds = [V.add(V.neg(a), V.neg(b)) for a, b in itertools.combinations(A, 2)]
    V.check(all(t not in A for t in thirds), "A has no line")

    def pairs(z):
        """The pairs {x,y} of cap points with x + y + z = 0."""
        nz = V.neg(z)
        out = []
        for x in pts:
            y = V.add(nz, V.neg(x))
            if x < y and y in cap:
                out.append((x, y))
        return sorted(out)

    E = {z: pairs(z) for z in A}
    print("secant counts of the points of A: " + ", ".join("%s: %d" % (V.digits(z), len(E[z])) for z in A))
    V.check([len(E[z]) for z in A] == [10, 10, 10, 11], "the three points of O have 10 secants; 2112222 has 11 secants")
    forced = {t for t in thirds if t in cap}
    edges = sorted(set().union(*E.values()))
    rest = [(a, b) for a, b in edges if a not in forced and b not in forced]
    verts = {v for e in rest for v in e}
    size, cov = V.min_cover(verts, rest)
    D = sorted(forced | cov)
    dset = set(D)
    print("forced deletions: %d; different pairs: %d; pairs without a forced endpoint: %d; points of these pairs: %d"
          % (len(forced), len(edges), len(rest), len(verts)))
    comps = V.components(verts, rest)
    kinds = Counter((len(c), V.tau([(a, b) for a, b in rest if a in set(c)])) for c in comps)
    print("connected parts (points, smallest cover): number of parts = "
          + ", ".join("(%d, %d): %d" % (n, s, m) for (n, s), m in sorted(kinds.items())))
    cost = len(D)
    V.check(cost == len(forced) + size == 20, "the exact cost of A is 20 (forced %d + smallest cover %d)" % (len(forced), size))
    S = (cap - dset) | set(A)
    V.check(cost == 20 and len(S) == 220, "(C - D) union A has 220 points")
    V.check(not V.lines_inside(S), "(C - D) union A has no line")
    V.check(all(a in dset or b in dset for z in A for a, b in E[z]), "D meets each secant of each point of A")

    def unlocked(z):
        """True if no secant of z has both endpoints outside D."""
        nz = V.neg(z)
        for x in pts:
            y = V.add(nz, V.neg(x))
            if x not in dset and y in cap and y not in dset:
                return False
        return True

    outside = [z for z in V.ALL_POINTS if z not in cap]
    free = sorted(z for z in outside if unlocked(z))
    V.check(free == sorted(A), "the %d outside points that D unlocks are exactly the 4 points of A" % len(free))
    print("D = " + " ".join(V.digits(x) for x in D))
    print("\nALL CHECKS PASSED")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
