"""Motor basado en modelos de Hugging Face."""

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))

from typing import Optional

from .base import LogicEngine


class HFEngine(LogicEngine):
    """Utiliza la librería ``transformers`` para generar texto."""

    def __init__(self, model_name: str = "gpt2") -> None:
        self.model_name = model_name
        self._pipe = None  # carga diferida

    def _ensure_pipeline(self) -> None:
        if self._pipe is None:
            try:
                from transformers import pipeline
            except ImportError as exc:
                raise ImportError("Se requiere 'transformers' para HFEngine") from exc
            self._pipe = pipeline("text-generation", model=self.model_name)

    def infer(self, prompt: str) -> str:
        return self.generate(prompt)

    def generate(self, prompt: str) -> str:
        self._ensure_pipeline()
        result = self._pipe(prompt, max_new_tokens=50)
        return result[0]["generated_text"]
