"""Automatic workflow discovery by scanning directories."""

import importlib.util
import sys
from pathlib import Path
from typing import List


def discover_workflows_in_directory(directory: str | Path) -> List[str]:
    """Discover and import Python files in a directory to register workflows.

    Args:
        directory: Path to directory to scan for Python files.

    Returns:
        List of imported module names.
    """
    directory = Path(directory)
    if not directory.exists():
        return []

    imported_modules = []

    # Find all Python files
    python_files = list(directory.glob("**/*.py"))

    # Add directory to sys.path to support local imports
    directory_str = str(directory.absolute())
    path_added = False
    if directory_str not in sys.path:
        sys.path.insert(0, directory_str)
        path_added = True

    try:
        for py_file in python_files:
            # Skip __init__.py and files starting with _
            if py_file.name.startswith("_"):
                continue

            try:
                # Create a unique module name
                module_name = f"ombra_workflow_{py_file.stem}_{id(py_file)}"

                # Load the module
                spec = importlib.util.spec_from_file_location(module_name, py_file)
                if spec and spec.loader:
                    module = importlib.util.module_from_spec(spec)
                    sys.modules[module_name] = module
                    spec.loader.exec_module(module)
                    imported_modules.append(str(py_file))

            except Exception as e:
                # Silently skip files that can't be imported
                print(f"Warning: Could not import {py_file}: {e}")
                continue
    finally:
        # Clean up sys.path if we added it
        if path_added and directory_str in sys.path:
            sys.path.remove(directory_str)

    return imported_modules


def discover_workflows_from_paths(paths: List[str | Path]) -> List[str]:
    """Discover workflows from multiple paths.

    Args:
        paths: List of directories or files to scan.

    Returns:
        List of imported module names.
    """
    all_imported = []

    for path in paths:
        path = Path(path)

        if path.is_file() and path.suffix == ".py":
            # Import single file
            try:
                module_name = f"ombra_workflow_{path.stem}_{id(path)}"
                spec = importlib.util.spec_from_file_location(module_name, path)
                if spec and spec.loader:
                    module = importlib.util.module_from_spec(spec)
                    sys.modules[module_name] = module
                    spec.loader.exec_module(module)
                    all_imported.append(str(path))
            except Exception as e:
                print(f"Warning: Could not import {path}: {e}")

        elif path.is_dir():
            # Import directory
            all_imported.extend(discover_workflows_in_directory(path))

    return all_imported
