"""Check integer rays for an equal-sphere kissing configuration, exactly.

Usage: python3 verify.py candidate.json [--count 41]
Normalize each ray and multiply by 2 to obtain the center of a unit ball
touching the central unit ball.  Pair separation must be at least 60 degrees.
Exit 0 on a valid configuration, 1 on overlap, 2 on malformed input.
"""
import argparse
import itertools
import json
import sys


def check(document, expected=None):
    rays = document.get("directions")
    if document.get("dimension") != 5 or not isinstance(rays, list) or len(rays) < 2:
        raise ValueError("Expected at least two five-dimensional directions.")
    if expected is not None and len(rays) != expected:
        raise ValueError(f"Expected {expected} directions, received {len(rays)}.")
    for ray in rays:
        if not isinstance(ray, list) or len(ray) != 5 or any(type(x) is not int for x in ray) or not any(ray):
            raise ValueError("Each ray must contain exactly five integers and be nonzero.")
    norms = [sum(x*x for x in ray) for ray in rays]
    bad = []
    for i, j in itertools.combinations(range(len(rays)), 2):
        dot = sum(x*y for x, y in zip(rays[i], rays[j]))
        if dot > 0 and 4*dot*dot > norms[i]*norms[j]:
            bad.append((i+1, j+1))
    return {"centers":len(rays), "pairs":len(rays)*(len(rays)-1)//2,
            "overlaps":len(bad), "valid":not bad, "overlapping_pairs":bad}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("file")
    parser.add_argument("--count", type=int)
    args = parser.parse_args()
    try:
        with open(args.file, encoding="utf-8") as stream:
            result = check(json.load(stream), args.count)
    except (OSError, ValueError, AttributeError) as error:
        print(error, file=sys.stderr)
        sys.exit(2)
    print(json.dumps(result))
    sys.exit(0 if result["valid"] else 1)
