import os
import shutil

ROOT_DIR = os.getcwd()

def flatten_structure_deep():
    print("Starting Deep 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 Theme: {item}")
            
            # Walk top-down through the directory
            # We use os.walk but we need to be careful not to process files we just moved.
            # So we list dir first.
            
            subdirs = [d for d in os.listdir(theme_dir) if os.path.isdir(os.path.join(theme_dir, d))]
            
            for subdir in subdirs:
                if subdir == "assets":
                    continue # Skip root assets
                
                subdir_path = os.path.join(theme_dir, subdir)
                print(f"  Flattening subfolder: {subdir}")
                
                # Recursively move everything from this folder to theme_dir
                for root, dirs, files in os.walk(subdir_path, topdown=False):
                    for name in files:
                        src_file = os.path.join(root, name)
                        
                        # Calculate relative path to preserve context in filename if needed
                        # But user wants ROOT.
                        # Collision strategy: If file exists, prepend folder name.
                        
                        dest_file = os.path.join(theme_dir, name)
                        
                        if os.path.exists(dest_file):
                            # Collision! Prepend subdir name to filename
                            # Ex: "manual.md" -> "Asterisk_manual.md"
                            print(f"    Collision for {name}. Renaming...")
                            new_name = f"{subdir}_{name}"
                            dest_file = os.path.join(theme_dir, new_name)
                        
                        shutil.move(src_file, dest_file)
                        print(f"    Moved: {name} -> {os.path.basename(dest_file)}")
                        
                    for name in dirs:
                        # Handle Assets folders
                        if name == "assets":
                            assets_src = os.path.join(root, name)
                            theme_assets = os.path.join(theme_dir, "assets")
                            
                            if not os.path.exists(theme_assets):
                                os.makedirs(theme_assets)
                                
                            for asset_file in os.listdir(assets_src):
                                a_src = os.path.join(assets_src, asset_file)
                                a_dst = os.path.join(theme_assets, asset_file)
                                if not os.path.exists(a_dst):
                                    shutil.move(a_src, a_dst)
                            
                            try:
                                os.rmdir(assets_src)
                            except:
                                pass
                
                # Remove the original subfolder if empty
                try:
                    shutil.rmtree(subdir_path)
                    print(f"  Removed folder: {subdir}")
                except Exception as e:
                    print(f"  Warning: Could not remove {subdir}: {e}")

if __name__ == "__main__":
    flatten_structure_deep()
