"""Check the individual necessity of retained routes and optionally rebuild the full reduction."""
import argparse
import csv
import json
from math import gcd
from pathlib import Path
import subprocess
import tempfile
import zipfile

HERE = Path(__file__).resolve().parent
PRIMES = (11, 13, 17, 19, 23, 29, 31, 37)
PAIRS = ((18533, 18593), (26149, 26203), (8047, 8087), (34429, 34441),
         (9451, 9517), (22889, 22943), (22507, 22567), (17959, 17989),
         (17093, 17117), (17177, 17239), (17291, 17317), (39229, 39269))


def rebuild(archive, executable):
    with zipfile.ZipFile(archive) as certificate:
        selected = {}
        for line in certificate.read("familles.txt").decode().splitlines():
            endpoints, *internal = line.split(";")
            key = tuple(map(int, endpoints.split()))
            if key in PAIRS:
                selected[key] = [list(map(int, values.split())) for values in internal]

    with tempfile.TemporaryDirectory() as tmp:
        directory = Path(tmp)
        cases = directory / "cases.txt"
        answers = directory / "answers.csv"
        def solve(key, family):
            parts = [" ".join(map(str, key))] + [" ".join(map(str, path)) for path in family]
            cases.write_text(";".join(parts) + "\n", encoding="ascii")
            subprocess.run([executable, "37", str(cases), str(answers)], check=True)
            with answers.open(newline="") as src:
                row, = csv.DictReader(src)
            assert (int(row["u"]), int(row["v"])) == key
            assignment = dict(term.split("=") for term in row["cover"].split())
            return [int(assignment[str(prime)]) for prime in PRIMES] if assignment else []
        output = []
        for key in PAIRS:
            family = selected[key].copy()
            before = len(family)
            for route in sorted(family, key=len, reverse=True):
                candidate = family.copy()
                candidate.remove(route)
                if not solve(key, candidate):
                    family = candidate
            assert not solve(key, family)
            phases = [solve(key, family[:i] + family[i+1:]) for i in range(len(family))]
            output.append(dict(ends=list(key), before=before, family=family, phases=phases))
        return output


def verify(rows):
    assert [tuple(row["ends"]) for row in rows] == list(PAIRS)
    before = after = empty = 0
    for row in rows:
        u, v = row["ends"]
        family = row["family"]
        assert len(family) == len(row["phases"])
        for i, residues in enumerate(row["phases"]):
            assert len(residues) == len(PRIMES)
            assert all(0 <= a < p for p, a in zip(PRIMES, residues))
            def alive(x):
                return gcd(x, 210) == 1 and all(x % p != a for p, a in zip(PRIMES, residues))
            assert alive(u) and alive(v) and not any(alive(x) for x in range(u+1, v))
            survivors = [j for j, route in enumerate(family) if all(alive(x) for x in route)]
            assert survivors == [i], (u, v, i)
        empty += not family
        before += row["before"]
        after += len(family)
    return dict(pairs=len(rows), before=before, after=after, witness_assignments=after,
                empty_families=empty)


if __name__ == "__main__":
    if not __debug__:
        raise RuntimeError("Enable Python assertions.")
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--build", nargs=2, metavar=("CERTIFICATE37_ZIP", "COVER_EXECUTABLE"))
    parser.add_argument("--export", type=Path)
    args = parser.parse_args()
    if args.export and not args.build:
        parser.error("--export requires --build")
    source = HERE / "reduction-37.json"
    rows = rebuild(args.build[0], str(Path(args.build[1]).resolve())) if args.build else json.loads(source.read_text())
    summary = verify(rows)
    if args.export:
        args.export.write_text(json.dumps(rows, indent=2) + "\n", encoding="utf8")
    elif args.build:
        assert rows == json.loads(source.read_text())
    print(json.dumps(summary, indent=2))
