import os
import re
import json
from zipfile import ZipFile


def legalize(filename: str, repl: str='') -> str:
    illegal_characters = list('<>:"/\\|?*') + [chr(i) for i in range(32)]
    illegal_names = [
        'CON',
        'PRN',
        'AUX',
        'NUL',
        'COM1',
        'COM2',
        'COM3',
        'COM4',
        'COM5',
        'COM6',
        'COM7',
        'COM8',
        'COM9',
        'LPT1',
        'LPT2',
        'LPT3',
        'LPT4',
        'LPT5',
        'LPT6',
        'LPT7',
        'LPT8',
        'LPT9'
    ]
    if repl and repl in illegal_characters:
        raise NameError(f'repl \'{repl}\' cannot be a illegal character')
    for c in illegal_characters:
        filename = filename.replace(c, repl)
    if filename.split('.')[0].upper() in illegal_names:
        filename = (repl or '_') + filename
    while filename[-1] == '.':
        filename = filename[:-1]
    return filename

def rename(inpath, outpath, count=0):
    outpath_unique = outpath
    if count:
        outpath_unique = outpath.split('.')
        outpath_unique[len(outpath_unique)-2] += f'-{chr(97+count)}'
        outpath_unique = '.'.join(outpath_unique)
    if os.path.isfile(outpath_unique):
        rename(inpath, outpath, count+1)
    else:
        os.rename(inpath, outpath_unique)
        print(inpath, ' --> ', outpath_unique)

os.chdir('G:/Books/Comics/Aku Ankka')
for d in os.listdir():
    for f in os.listdir(d):
        with ZipFile(f'{d}/{f}') as z:
            with z.open('metadata.json') as m:
                j = json.load(m)
                slug = re.search(r'(\d{4}.+)', j['slug']).group(1).upper()
                fn = legalize('{} - {}{}.{}'.format(
                    ' '.join(j['text'].split(' ')[:-1]),
                    (slug[:4]+' #'+slug[5:]+slug[4]).rstrip('-'),
                    '' if j['title'].startswith('#') else f" - {j['title']}",
                    f.split('.')[-1]
                ))
        if os.path.join(d, f) != os.path.join(d, fn):
            rename(os.path.join(d, f), os.path.join(d, fn))
