#!/usr/bin/env python3
import argparse
import csv
import ipaddress
import json
from pathlib import Path


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(
        description="Convert rpki report.json VRPs into Routinator-compatible CSV"
    )
    p.add_argument("--report", required=True, help="path to rpki report.json")
    p.add_argument("--out", required=True, help="output CSV path")
    p.add_argument(
        "--trust-anchor",
        default="unknown",
        help="Trust Anchor column value (default: unknown)",
    )
    return p.parse_args()


def sort_key(vrp: dict):
    network = ipaddress.ip_network(vrp["prefix"], strict=False)
    return (
        int(vrp["asn"]),
        network.version,
        int(network.network_address),
        network.prefixlen,
        int(vrp["max_length"]),
    )


def main() -> int:
    args = parse_args()
    report = json.loads(Path(args.report).read_text(encoding="utf-8"))
    vrps = list(report.get("vrps") or [])
    vrps.sort(key=sort_key)

    out_path = Path(args.out)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    with out_path.open("w", encoding="utf-8", newline="") as f:
        w = csv.writer(f)
        w.writerow(["ASN", "IP Prefix", "Max Length", "Trust Anchor"])
        for vrp in vrps:
            w.writerow([
                f"AS{vrp['asn']}",
                vrp["prefix"],
                vrp["max_length"],
                args.trust_anchor,
            ])
    print(out_path)
    return 0


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