"""Find the first overlap in a small local CIDR inventory. Python 3.9+."""
import argparse
import ipaddress
from pathlib import Path
import sys

MAX_BYTES = 128 * 1024
MAX_NETWORKS = 1000


def read_networks(path):
    if not path.is_file():
        raise ValueError("input must be a regular file")
    with path.open("rb") as stream:
        raw = stream.read(MAX_BYTES + 1)
    if len(raw) > MAX_BYTES:
        raise ValueError(f"input exceeds {MAX_BYTES} bytes")
    text = raw.decode("utf-8")
    if text.startswith("\ufeff"):
        raise ValueError("remove the UTF-8 BOM first")
    rows = []
    for line_number, line in enumerate(text.splitlines(), 1):
        token = line.split("#", 1)[0].strip()
        if not token:
            continue
        if len(rows) >= MAX_NETWORKS:
            raise ValueError(f"more than {MAX_NETWORKS} networks")
        if token.count("/") != 1 or "%" in token:
            raise ValueError(f"line {line_number}: expected unscoped IP/prefix")
        prefix = token.split("/", 1)[1]
        if not prefix.isascii() or not prefix.isdecimal():
            raise ValueError(f"line {line_number}: prefix must be decimal digits")
        try:
            network = ipaddress.ip_network(token, strict=True)
        except ValueError as exc:
            raise ValueError(f"line {line_number}: {exc}") from exc
        rows.append((line_number, network))
    if not rows:
        raise ValueError("no networks found")
    return rows


def first_overlap(rows):
    for index, (left_line, left) in enumerate(rows):
        for right_line, right in rows[index + 1:]:
            if left.version == right.version and left.overlaps(right):
                return left_line, left, right_line, right
    return None


def main():
    parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
    parser.add_argument("file", type=Path, help="UTF-8 file: one CIDR per line")
    args = parser.parse_args()
    try:
        rows = read_networks(args.file)
        conflict = first_overlap(rows)
    except (OSError, ValueError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 2
    if conflict:
        left_line, left, right_line, right = conflict
        print(f"OVERLAP: line {left_line} {left} <-> line {right_line} {right}")
        return 1
    print(f"OK: {len(rows)} networks; no overlaps within each IP version")
    return 0


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