import os
import shutil
import re

ROOT_DIR = os.getcwd()

def flatten_structure():
    print("Starting structure flattening...")
    
    # Iterate over all directories in root
    for item in os.listdir(ROOT_DIR):
        theme_dir = os.path.join(ROOT_DIR, item)
        
        # We only care about "documentacao *" folders
        if os.path.isdir(theme_dir) and item.startswith("documentacao "):
            print(f"Processing: {item}")
            
            # Look for Nivel_* folders inside
            for subitem in os.listdir(theme_dir):
                subitem_path = os.path.join(theme_dir, subitem)
                
                if os.path.isdir(subitem_path) and subitem.startswith("Nivel_"):
                    print(f"  Found subfolder: {subitem}")
                    
                    # Move all files from Nivel_X to Root of Theme
                    for file in os.listdir(subitem_path):
                        src_path = os.path.join(subitem_path, file)
                        dst_path = os.path.join(theme_dir, file)
                        
                        # Handle Assets Special Case
                        if file == "assets" and os.path.isdir(src_path):
                            theme_assets = os.path.join(theme_dir, "assets")
                            if not os.path.exists(theme_assets):
                                os.makedirs(theme_assets)
                            
                            # Merge assets
                            for asset in os.listdir(src_path):
                                asset_src = os.path.join(src_path, asset)
                                asset_dst = os.path.join(theme_assets, asset)
                                if not os.path.exists(asset_dst):
                                    shutil.move(asset_src, asset_dst)
                                else:
                                    print(f"    Warning: Asset {asset} already exists in target. Skipping.")
                            
                            # Remove empty assets folder
                            try:
                                os.rmdir(src_path)
                            except OSError:
                                pass # Not empty?
                                
                        elif os.path.isfile(src_path):
                            # Move Main Manual File
                            if os.path.exists(dst_path):
                                print(f"    Warning: File {file} already exists in {item}. Renaming to avoid overwrite.")
                                base, ext = os.path.splitext(file)
                                dst_path = os.path.join(theme_dir, f"{base}_migrated{ext}")
                            
                            shutil.move(src_path, dst_path)
                            print(f"    Moved: {file}")
                    
                    # Remove the now empty Nivel_X folder
                    try:
                        os.rmdir(subitem_path)
                        print(f"  Removed empty folder: {subitem}")
                    except OSError:
                        print(f"  Warning: Could not remove {subitem}, it might not be empty.")

            # Look for other subfolders that are NOT assets (e.g., 'docker', 'pfsense' inside main categories)
            # The user requested flattening. "quero todos os manuais na "raiz" da pasta do assunto"
            # This implies if recursive structures exist like "Conteineres/docker/README.md", they should move to "Conteineres/docker_README.md" OR just stay if they are not "Nivel_X"?
            # The user specifically said "nao quero pastas internas com o nivel".
            # I will focus on flattening "Nivel_*" folders primarily. 
            # If there are other folders (like subject specific subfolders), I should probably check with user or assume "Nivel_*" was the main offender.
            # Start with just Nivel_* as that covers 90% of the structure.

if __name__ == "__main__":
    flatten_structure()
