import os
import sys
import importlib
import pkgutil
import subprocess

def main():
    """Command-line interface handler for multiple commands."""
    if len(sys.argv) < 2:
        print("Usage:")
        print("  skeltymlops <method_name>              # Call a method in any class")
        print("  skeltymlops new <folder_name>          # Create a folder and clone a repo")
        print("  skeltymlops run <pipeline_name>        # Run a pipeline file (data_ingestion, data_prep, etc.)")
        sys.exit(1)

    command = sys.argv[1]

    # 1) CREATE NEW FOLDER & CLONE REPO
    if command == "new":
        if len(sys.argv) < 3:
            print("Error: Please specify a folder name.")
            sys.exit(1)

        folder_name = sys.argv[2]
        github_repo = "https://github.com/jeanpierrenashef/UI_skeleton"

        try:
            os.makedirs(folder_name, exist_ok=True)
            print(f"✅ Folder '{folder_name}' created successfully.")

            # Clone the repo inside the folder
            subprocess.run(["git", "clone", github_repo, folder_name], check=True)
            print(f"✅ Repository cloned into '{folder_name}'.")
        except Exception as e:
            print(f"❌ Error: {e}")
            sys.exit(1)

    # 2) RUN A PIPELINE
    elif command == "run":
        if len(sys.argv) < 3:
            print("Error: Please specify a pipeline name, e.g. data_ingestion, data_prep, training, etc.")
            sys.exit(1)

        pipeline_name = sys.argv[2]
        pipeline_file = os.path.join(pipeline_name, "pipeline.py")

        if not os.path.isfile(pipeline_file):
            print(f"Error: No pipeline found at {pipeline_file}")
            sys.exit(1)

        try:
            subprocess.run(["python", pipeline_file], check=True)
            print(f"✅ Ran pipeline: {pipeline_name}")
        except Exception as e:
            print(f"❌ Error running pipeline {pipeline_name}: {e}")
            sys.exit(1)

    # 3) CALL A METHOD IN ANY CLASS (the original logic)
    else:
        method_name = command
        package_name = __name__

        for _, module_name, _ in pkgutil.iter_modules(__path__):
            module = importlib.import_module(f"{package_name}.{module_name}")
            for attr_name in dir(module):
                attr = getattr(module, attr_name)
                if isinstance(attr, type):  # Check if it's a class
                    obj = attr()  # Instantiate the class
                    if hasattr(obj, method_name):
                        getattr(obj, method_name)()
                        return

        print(f"Error: Method '{method_name}' not found in any module.")
        sys.exit(1)
