# from sys import argv
import argparse
import ipaddress
import random

# script, prefix = argv

def main(ipv6net_list, size_list):
    """
    메인 함수
    """
    if 2 == len(ipv6net_list):
        ipv6net_src =  ipaddress.IPv6Interface(ipv6net_list[0])
        size = ipv6net_list[1]
        print('Input : {}'.format(ipv6net_src))
        print('Size : {}'.format(size))
    elif 2 > len(ipv6net_list):
        ipv6net_src =  ipaddress.IPv6Interface(ipv6net_list[0])
        size = size_list
        print('Input : {}'.format(ipv6net_list))
        print('Size : {}'.format(size))
    else:
        ipv6net_src = []
        size = size_list
        print('Please, Read Help')

    ipv6_rand = 0
    size_rand = int(size)-int(str(ipv6net_src)[str(ipv6net_src).find('/')+1:])
    while size_rand != 0:
        if 16 <= size_rand:
            ipv6_rand = ipv6_rand << 16
            ipv6_rand += random.randint(0, (2**16)-1)
            size_rand -= 16
        else:
            ipv6_rand = ipv6_rand << size_rand
            ipv6_rand += random.randint(0, (2**size_rand)-1)
            size_rand = 0

#    print('{}'.format(ipaddress.IPv6Network((ipv6net_src))))
#    print('{}'.format(str(ipaddress.IPv6Address((ipv6_rand<<(128-int(size)))))+'/'+size))
#    print('{}'.format(int(size)-int(str(ipv6net_src)[str(ipv6net_src).find('/')+1:])))
    print('Output : {}'.format(str(ipaddress.IPv6Address(int(ipv6net_src)+(ipv6_rand <<(128 - int(size)))))+'/'+size))

def get_arguments():
    """
    argument를 파싱해서 가져옴
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('ipv6net', nargs='+', help='Example) 2001:db8::/40 or 2001:db8::/40 64', type=str)
    parser.add_argument('--size', nargs='?', help='Example) 64...0', default='48', type=str)

    ipv6net_list = parser.parse_args().ipv6net
    size_list = parser.parse_args().size

    return ipv6net_list, size_list

if __name__ == '__main__':
    ipv6net_list, size_list = get_arguments()
    main(ipv6net_list, size_list)
