#!/usr/bin/env python3
"""Convert DB-IP country-lite CSV to MaxMind legacy GeoIP CSV format.

Splits the DB-IP CSV (ip_start,ip_end,CC) into two legacy 6-column CSVs
(one for IPv4, one for IPv6), using GeoNames countryInfo.txt for names.

Legacy row format:
  "start_ip","end_ip","start_int","end_int","CC","Country Name"
"""
import argparse
import csv
import ipaddress
import sys

# Codes that DB-IP emits but libGeoIP (legacy) does not accept.
# ZZ = unknown/unassigned in DB-IP data.
SKIP_CODES = {'ZZ', ''}


def load_country_names(path):
    # countryInfo.txt: col 0 = ISO alpha-2, col 4 = country name
    names = {}
    with open(path, encoding='utf-8') as f:
        for line in f:
            if line.startswith('#') or not line.strip():
                continue
            fields = line.rstrip('\n').split('\t')
            if len(fields) >= 5 and fields[0]:
                names[fields[0]] = fields[4]
    # Legacy MaxMind pseudo-codes
    names.setdefault('A1', 'Anonymous Proxy')
    names.setdefault('A2', 'Satellite Provider')
    names.setdefault('EU', 'Europe')
    names.setdefault('AP', 'Asia/Pacific Region')
    return names


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--input', required=True)
    p.add_argument('--country-info', required=True)
    p.add_argument('--out-v4', required=True)
    p.add_argument('--out-v6', required=True)
    args = p.parse_args()

    names = load_country_names(args.country_info)
    v4_count = v6_count = skipped = 0

    with open(args.input, newline='', encoding='utf-8') as fin, \
         open(args.out_v4, 'w', encoding='utf-8') as v4, \
         open(args.out_v6, 'w', encoding='utf-8') as v6:
        for row in csv.reader(fin):
            if len(row) < 3:
                skipped += 1
                continue
            ip_start = row[0].strip()
            ip_end = row[1].strip()
            cc = row[2].strip().upper()
            if cc in SKIP_CODES or len(cc) != 2 or not cc.isalpha():
                skipped += 1
                continue
            try:
                a = ipaddress.ip_address(ip_start)
                b = ipaddress.ip_address(ip_end)
            except ValueError:
                skipped += 1
                continue
            if a.version != b.version:
                skipped += 1
                continue
            name = names.get(cc, cc)
            out = '"{}","{}","{}","{}","{}","{}"\n'.format(
                a, b, int(a), int(b), cc, name)
            if a.version == 4:
                v4.write(out)
                v4_count += 1
            else:
                v6.write(out)
                v6_count += 1

    print('dbip-to-legacy: v4={} v6={} skipped={}'.format(
        v4_count, v6_count, skipped), file=sys.stderr)


if __name__ == '__main__':
    main()
