#!/usr/bin/env python3
"""Build US IPv4 CIDR list from ARIN delegated stats -> /root/recon/us_ranges.txt"""
import ipaddress

SRC = "/root/recon/delegated-arin-extended-latest"
DST = "/root/recon/us_ranges.txt"

nets = []
total = 0
with open(SRC, encoding="utf-8", errors="replace") as f:
    for line in f:
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        p = line.split("|")
        if len(p) < 7 or p[0] != "arin" or p[1] != "US" or p[2] != "ipv4":
            continue
        if p[6] not in ("allocated", "assigned"):
            continue
        start = ipaddress.IPv4Address(p[3])
        end = ipaddress.IPv4Address(int(start) + int(p[4]) - 1)
        for net in ipaddress.summarize_address_range(start, end):
            if net.is_private or net.is_loopback or net.is_multicast:
                continue
            nets.append(net)
            total += net.num_addresses

with open(DST, "w") as out:
    for n in nets:
        out.write(f"{n}\n")
print(f"{len(nets)} networks, {total} addresses -> {DST}")
