import os, json

def get_file_type(filepath):
    if filepath.endswith('.jpg') or filepath.endswith('.png'):
        return 'image'
    elif filepath.endswith('.mp4'):
        return 'video'
    else:
        return None

def get_files(directory):
    files = []
    for root, dirs, filenames in os.walk(directory):
        for filename in filenames:
            files.append(os.path.join(root, filename))
    return files

files = get_files('STORAGE/')
os.makedirs('images', exist_ok=True)
os.makedirs('videos', exist_ok=True)

for filepath in files:
    if not os.path.exists(filepath):
        print(f"File {filepath} does not exist, skipping.")
        continue
    
    # Extract the username from the filepath assuming the structure STORAGE/{username}/{filename}
    filepath = filepath.replace('\\', '/')  # Replace backslashes with forward slashes
    parts = filepath.split('/')  # Split the path by the system's separator
    if len(parts) < 3 or parts[0] != 'STORAGE':  # Check if the structure is valid
        print(f"Unexpected filepath format: {filepath}")
        continue
    
    username = parts[1]  # Extract the username from the second part
    fileType = get_file_type(filepath)  # Determine the type of the file
    if not fileType:
        print(f"Unknown file type for {filepath}")
        continue
    
    if fileType == 'image':
        newpath = os.path.join('images', username, os.path.basename(filepath))
    elif fileType == 'video':
        newpath = os.path.join('videos', username, os.path.basename(filepath))
    else:
        print(f"Unknown media type {fileType} for {filepath}")
        continue
    
    os.makedirs(os.path.dirname(newpath), exist_ok=True)  # Create directory structure if it doesn't exist
    os.rename(filepath, newpath)  # Move the file to the new location