from rich import print
import os
import shutil


def main():
    debug = True if "y" in input("Debug mode? (y/n): ").lower() else False
    source = os.getcwd()

    print(f"[bold blue]DIRECTORY SCAN:[/bold blue] [bold yellow]{source}[/bold yellow]")

    if not os.path.exists(source):
        print("[bold red]Directory not found![/bold red]")
        return

    items = os.listdir(source)
    print(f"[bold blue]Found:[/bold blue] [bold green]{len(items)}[/bold green] items\n")

    # display
    files = {}

    for item in items:
        full_path = os.path.join(source, item)

        if os.path.isfile(full_path):
            ext = os.path.splitext(item)[1].lstrip(".").lower() or "no_extension"
            files.setdefault(ext, []).append(full_path)

        elif os.path.isdir(full_path):
            files.setdefault("DIRECTORY", []).append(full_path)

    for extension in sorted(files):
        print(f"[bold red].{extension}[/bold red]")
        print("-" * 40)

        for i, path in enumerate(sorted(files[extension]), start=1):
            name = os.path.basename(path)

            if extension == "DIRECTORY":
                try:
                    count = len(os.listdir(path))
                except:
                    count = "?"
                print(f"[cyan]{i}.[/cyan] [green]{name} ({count} items)[/green]")
            else:
                try:
                    size = os.path.getsize(path)
                except:
                    size = "?"
                print(f"[cyan]{i}.[/cyan] [green]{name} ({size} bytes)[/green]")

        print()

    # user confirm
    proceed = input("Proceed with sorting? (y/n): ").lower()
    if "y" not in proceed:
        print("[bold yellow]Sorting cancelled.[/bold yellow]")
        return

    # ask about main folder ONLY if sorting
    use_main_folder = True if "y" in input("Create 'Sorted_Files' folder? \n(this will use the main folder if denied)\n(y/n): ").lower() else False

    # sort init
    if use_main_folder:
        base_folder = os.path.join(source, "Sorted_Files")
        os.makedirs(base_folder, exist_ok=True)
    else:
        base_folder = source

    folders_dir = os.path.join(base_folder, "Folders")
    os.makedirs(folders_dir, exist_ok=True)

    moved_files = 0
    moved_folders = 0

    # sorting
    for item in items:
        full_path = os.path.join(source, item)

        if use_main_folder and full_path == base_folder:
            continue

        # files
        if os.path.isfile(full_path):
            ext = os.path.splitext(item)[1].lstrip(".").lower() or "no_extension"
            ext_folder = os.path.join(base_folder, ext)
            os.makedirs(ext_folder, exist_ok=True)

            destination = os.path.join(ext_folder, item)

            if os.path.exists(destination):
                name, extension = os.path.splitext(item)
                counter = 1
                while True:
                    new_name = f"{name}_{counter}{extension}"
                    new_dest = os.path.join(ext_folder, new_name)
                    if not os.path.exists(new_dest):
                        destination = new_dest
                        break
                    counter += 1

            shutil.move(full_path, destination)
            moved_files += 1

            print(f"[cyan]FILE[/cyan] → [green]{item}[/green] → [yellow]{ext}/[/yellow]")

        # dirs
        elif os.path.isdir(full_path):
            destination = os.path.join(folders_dir, item)

            if os.path.exists(destination):
                counter = 1
                while True:
                    new_name = f"{item}_{counter}"
                    new_dest = os.path.join(folders_dir, new_name)
                    if not os.path.exists(new_dest):
                        destination = new_dest
                        break
                    counter += 1

            shutil.move(full_path, destination)
            moved_folders += 1

            print(f"[magenta]FOLDER[/magenta] → [green]{item}[/green] → [yellow]Folders/[/yellow]")

    # final summary
    print(f"\n[bold green]Sorting complete![/bold green]")
    print(f"[bold blue]Files moved:[/bold blue] [yellow]{moved_files}[/yellow]")
    print(f"[bold blue]Folders moved:[/bold blue] [yellow]{moved_folders}[/yellow]")


if __name__ == "__main__":
    main()