import os, json, funcs

STORAGE_IMPORTED = 'STORAGE_IMPORTED'
pins = json.load(open('db_pins.json', 'r'))

for pin in pins:
    filename = pin['url'].split('/')[-1]
    filepath = os.path.join(STORAGE_IMPORTED, filename)
    pin['filename'] = filename
    if not pin['hash']:
        pin['hash'] = funcs.calculate_file_hash(filepath)

json.dump(pins, open('db_pins.json', 'w'), indent=4)

files = os.listdir(STORAGE_IMPORTED)

for file in files:
    filepath = os.path.join(STORAGE_IMPORTED, file)
    fileHash = funcs.calculate_file_hash(filepath)
    if fileHash not in file:
        print(f'Renaming {file} to {fileHash}')
        os.rename(filepath, os.path.join(STORAGE_IMPORTED, fileHash))

pins_by_username = {}
for pin in pins:
    username = pin['title']
    if username not in pins_by_username:
        pins_by_username[username] = []
    pins_by_username[username].append(pin)

for username, username_pins in pins_by_username.items():
    username_folder = os.path.join(STORAGE_IMPORTED, username)
    os.makedirs(username_folder, exist_ok=True)
    for pin in username_pins:
        photo_id = pin['photo_id']
        photo_url = pin['url']
        fileHash = pin['hash']

        if not fileHash:
            continue
        
        extension = photo_url.split('.')[-1]
        filename = f'{fileHash}.{extension}'
        
        filePath = os.path.join(STORAGE_IMPORTED, filename)
        outputPath = os.path.join(STORAGE_IMPORTED, username, filename)
                
        if os.path.exists(outputPath):
            print(f'File {outputPath} already exists. Skipping...')
            continue
        
        print(f'Moving {photo_url} to {outputPath}')
        os.rename(filePath, outputPath)