"""HeuristicQualiaSpirit: version heurística del espíritu."""

from __future__ import annotations


if __package__ in {None, ""}:  # pragma: no cover - permite ejecución como script
    import sys
    from pathlib import Path

    _current_file = Path(__file__).resolve()
    for _parent in (_current_file.parent, *_current_file.parents):
        if (_parent / "pyproject.toml").exists() or (_parent / ".git").exists():
            _project_root = _parent
            break
    else:
        _project_root = _current_file.parents[2]
    _src_root = _project_root / "src"
    for _path in (_project_root, _src_root):
        _path_str = str(_path)
        if _path_str not in sys.path:
            sys.path.insert(0, _path_str)
    from agix._script_utils import bootstrap_script_environment

    bootstrap_script_environment("__main__", str(_current_file))

if __package__ in {None, ""}:  # pragma: no cover - preparación para ejecución directa
    import importlib.util
    import sys
    from pathlib import Path

    current_file = Path(__file__).resolve()
    project_root = None
    for candidate in current_file.parents:
        if (candidate / "pyproject.toml").exists():
            project_root = candidate
            break
    if project_root is None:
        project_root = current_file.parents[3]

    helper_path = project_root / "src" / "agix" / "_script_utils.py"
    spec = importlib.util.spec_from_file_location("agix._script_utils", helper_path)
    if spec and spec.loader:
        module = sys.modules.get(spec.name)
        if module is None:
            module = importlib.util.module_from_spec(spec)
            sys.modules[spec.name] = module
            spec.loader.exec_module(module)
    else:  # pragma: no cover - solo si falta el helper
        raise ImportError(f"No se pudo cargar el helper de scripts desde {helper_path}")

    sys.modules[spec.name].bootstrap_script_environment(__name__, __file__)

from typing import Callable, List, Tuple

from .spirit import QualiaSpirit
from .heuristic_creator import HeuristicConceptCreator


class HeuristicQualiaSpirit(QualiaSpirit):
    """Extiende ``QualiaSpirit`` aplicando reglas heurísticas."""

    def __init__(self, nombre: str = "Qualia", edad_aparente: int = 7, plasticidad: bool = False) -> None:
        super().__init__(nombre=nombre, edad_aparente=edad_aparente, plasticidad=plasticidad)
        self.rules: List[Callable[[str, float], Tuple[str, float]]] = []

    # ------------------------------------------------------------------
    def add_rule(self, rule: Callable[[str, float], Tuple[str, float]]) -> None:
        """Registra una regla heurística para ajustar emoción e intensidad."""
        self.rules.append(rule)

    # ------------------------------------------------------------------
    def experimentar(self, evento: str, carga: float, tipo_emocion: str = "sorpresa") -> None:
        """Genera un concepto heurístico y aplica reglas antes de registrar."""
        concepto = self.creator.create([tipo_emocion, evento.replace(" ", "_")])
        emocion = concepto.name
        for rule in self.rules:
            emocion, carga = rule(emocion, carga)
        super().experimentar(evento, carga, emocion)
