"""Utilidades para ejecutar módulos del paquete ``agix`` como scripts autónomos."""

from __future__ import annotations

import sys
from pathlib import Path
from typing import Iterable

_PROJECT_MARKERS = ("pyproject.toml", ".git")


def _find_project_root(start: Path) -> Path:
    """Devuelve la raíz del proyecto buscando archivos marcadores."""
    for parent in (start.parent, *start.parents):
        if any((parent / marker).exists() for marker in _PROJECT_MARKERS):
            return parent
    # En última instancia asumimos estructura ``<root>/src/...``
    return start.parents[2]


def _ensure_paths(paths: Iterable[Path]) -> None:
    """Inserta rutas en ``sys.path`` si no existen todavía."""
    for path in paths:
        path = path.resolve()
        if not path.exists():
            continue
        path_str = str(path)
        if path_str not in sys.path:
            sys.path.insert(0, path_str)


def _derive_package(module_file: Path, src_root: Path) -> str | None:
    """Calcula el paquete asociado a un módulo dentro de ``src``."""
    try:
        relative_path = module_file.relative_to(src_root)
    except ValueError:
        return None

    parts = relative_path.with_suffix("").parts
    if len(parts) < 2:
        return None
    return ".".join(parts[:-1])


def bootstrap_script_environment(module_name: str, module_file: str) -> None:
    """Prepara ``sys.path`` y ``__package__`` para módulos ejecutados como script."""
    module = sys.modules.get(module_name)
    if module is None:
        return
    if getattr(module, "__package__", None):
        return

    module_path = Path(module_file).resolve()
    project_root = _find_project_root(module_path)
    src_root = project_root / "src"

    _ensure_paths((project_root, src_root))

    package = _derive_package(module_path, src_root)
    if package:
        module.__package__ = package


def bootstrap_current_script() -> None:
    """Conveniencia para ajustar el entorno del módulo ``__main__``."""

    main_module = sys.modules.get("__main__")
    if not main_module:
        return

    module_file = getattr(main_module, "__file__", None)
    if not module_file:
        return

    bootstrap_script_environment("__main__", module_file)
