"""Performance tester runner — discovers and runs perf_*.py scripts in this directory."""

import os
import importlib.util
import asyncio


def list_modules():
    """Find all perf_*.py modules in this directory."""
    perf_dir = os.path.dirname(__file__)
    modules = []
    for file in os.listdir(perf_dir):
        if file.startswith("perf_") and file.endswith(".py"):
            modules.append(file[:-3])
    return sorted(modules)


async def load_and_execute_module(module_name):
    module_path = os.path.join(os.path.dirname(__file__), f"{module_name}.py")
    spec = importlib.util.spec_from_file_location(module_name, module_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    if hasattr(module, "main"):
        main_func = module.main
        if asyncio.iscoroutinefunction(main_func):
            await main_func()
        else:
            main_func()
    else:
        print(f"Module {module_name} has no main() function.")


def get_module_description(module_name):
    module_path = os.path.join(os.path.dirname(__file__), f"{module_name}.py")
    spec = importlib.util.spec_from_file_location(module_name, module_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return getattr(module, "description", "No description")


def main():
    modules = list_modules()
    if not modules:
        print("No performance test modules found in test/performance/.")
        return

    print("Available performance tests:")
    for idx, module in enumerate(modules, 1):
        description = get_module_description(module)
        print(f"  {idx}. {module} - {description}")

    try:
        choice = int(input("Select test number: ")) - 1
        if 0 <= choice < len(modules):
            asyncio.run(load_and_execute_module(modules[choice]))
        else:
            print("Invalid selection.")
    except ValueError:
        print("Please enter a valid number.")


if __name__ == "__main__":
    main()
