#!/usr/bin/env python
# coding:utf-8

# 导包
import maxminddb
import os
import sys

# 加载配置文件,将country、province设置为字典
def load_encode_file(filename):
    result = {}
    with open(os.path.abspath(filename),'r', encoding='utf-8') as file:
        for line in file:
            kv = line.strip().split()
            if len(kv) == 2:
                if kv[1].isdigit():
                    result[kv[1]] = kv[0]
                else:
                    result[kv[0]] = kv[1]
    return result

# 加载配置文件，将city设置为字典
def load_city_dict(filename):
    result = {}
    with open(os.path.abspath(filename),'r',encoding='utf-8') as file:
        for line in file:
            fields = line.strip().split()
            if len(fields) >= 3:
                prov, city, num = fields
                result[num] = city
    return result


def cityinfo(prov, x, city_dict):
    if prov in city_dict:
        return city_dict[prov].get(x)


def ipinfo(couns, provs, isps, data):
    # print("couns: {}".format(couns))
    # print("provs: {}".format(provs))
    # print("isps: {}".format(isps))
    # # print("city_dict: {}".format(city_dict))
    # print("data: {}".format(data))

    # print(data['country'])
    coun = couns.get(str(data['country']), 'unknown')
    isp = isps.get(str(data['isp']), 'unknown')

    prov = provs.get(str(data['prov']), 'unknown')
    # city = city_dict.get(str(data['city']), 'unknown')
    return f"{coun} {prov} {isp}"


def main(ip_address):
    provs = load_encode_file('encode/province')
    couns = load_encode_file('encode/country')
    isps = load_encode_file('encode/isp')
    # city_dict = load_city_dict('encode/city')
    reader = maxminddb.Reader('ipdb_pro.mmdb')


    # ip_address = '61.155.182.107'
    try:
        data = reader.get(ip_address)
        # print("data:{}".format(data))
        if data is None:
            print(f"{ip_address}: no ip data")
        else:
            info = ipinfo(couns, provs, isps, data)
            print(f"{ip_address}: {info}")
    except Exception as e:
        print(f"{e}")


if __name__ == '__main__':
    iplist = sys.argv[1]
    with open(iplist, 'r', encoding='utf-8') as f1:
        for ip_addr in  f1:
            main(ip_addr.strip('\n'))
