"""Match an IP against an AWS-format saved JSON file. Python standard library only.
Usage: python3 cidr-match.py ip-ranges.json 203.0.113.7
No match means absent from this file, not absent from a provider's network.
"""
import hashlib
import ipaddress
import json
import sys
from pathlib import Path


def match(document, address):
    ip = ipaddress.ip_address(address)
    matches = []
    for collection, field in [("prefixes", "ip_prefix"), ("ipv6_prefixes", "ipv6_prefix")]:
        rows = document.get(collection)
        if not isinstance(rows, list):
            raise ValueError(f"Missing or invalid {collection} array")
        for row in rows:
            network = ipaddress.ip_network(row[field], strict=True)
            if ip.version == network.version and ip in network:
                matches.append({"cidr": str(network), "service": row.get("service"),
                                "region": row.get("region"),
                                "network_border_group": row.get("network_border_group")})
    return matches


if __name__ == "__main__":
    if len(sys.argv) != 3:
        raise SystemExit("Usage: python3 cidr-match.py SAVED_JSON IP")
    raw = Path(sys.argv[1]).read_bytes()
    document = json.loads(raw)
    results = match(document, sys.argv[2])
    print(json.dumps({"address": sys.argv[2], "sha256": hashlib.sha256(raw).hexdigest(),
                      "createDate": document.get("createDate"),
                      "syncToken": document.get("syncToken"),
                      "result": "matched" if results else "not_in_this_file",
                      "matches": results}, indent=2))
