#!/usr/bin/python3

import argparse
import json
import re

from typing import Dict
from urllib.parse import urlparse
import GeoIP  # type: ignore


def geoip_info(gi, url_prefix):
    """Return GeoIP record for URL_PREFIX"""
    record = gi.record_by_name(urlparse(url_prefix).hostname)
    assert record is not None
    return record


def pretty_geoip_info(gi, url_prefix):
    """Return prettified GeoIP information for URL_PREFIX"""
    record = geoip_info(gi, url_prefix)
    country = record['country_name']
    region = record['region_name']
    city = record['city']
    return f"Country: {country}, Region: {region}, City: {city}"


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--url-prefix",
                        help="URL prefix of the mirror to check")
    args = parser.parse_args()
    gi = GeoIP.open("/usr/share/GeoIP/GeoIPCity.dat", GeoIP.GEOIP_STANDARD)
    if args.url_prefix:
        assert re.compile(r'^https?\:\/\/[\w\-\.]+').match(args.url_prefix)
        print(pretty_geoip_info(gi, args.url_prefix))
    else:
        with open('mirrors.json', 'r', encoding='utf-8') as f:
            mirrors = [
                mirror
                for mirror in json.loads(f.read())['mirrors']
                if mirror['weight'] > 0
            ]
        mirrors_info = [geoip_info(gi, mirror['url_prefix'])
                        for mirror in mirrors]
        countries: Dict[str, int] = {}
        for mirror_info in mirrors_info:
            country = mirror_info['country_name']
            if country in countries:
                countries[country] += 1
            else:
                countries[country] = 1
        for country in sorted(countries.keys(),
                              key=lambda k: countries[k],
                              reverse=True):
            print(f"{country}: {countries['country']}")
