"""Public SDK — developer-facing API. One import. One class. One method."""

from typing import Any, cast

from xyglue.config import EngineConfig
from xyglue.engine import XyglueEngine, RunResult
from xyglue.tools.base import Tool


class Engine:
    """
    The XYGLUE Engine — thinking-first agent framework.

    Usage:
        engine = Engine(api_key="xxx")
        result = await engine.run("Build a REST API for user management")

    Full configuration:
        engine = Engine(
            api_key="xxx",
            mode="semi",
            divergence="high",
            learning="supervised",
            agents={"scout": "Recon", "physicist": "Newton", "architect": "Blueprint"}
        )
    """

    def __init__(
        self,
        api_key: str | None = None,
        mode: str = "semi",
        divergence: str = "medium",
        learning: str = "supervised",
        agents: dict[str, str] | None = None,
        **kwargs: Any,
    ) -> None:
        # Build config
        agent_names = {
            "scout": (agents or {}).get("scout", "Scout"),
            "physicist": (agents or {}).get("physicist", "Physicist"),
            "architect": (agents or {}).get("architect", "Architect"),
        }

        self.config = EngineConfig(
            mode=cast(Any, mode),
            divergence=cast(Any, divergence),
            learning=cast(Any, learning),
            agent_names=agent_names,
            **{k: v for k, v in kwargs.items() if hasattr(EngineConfig, k)},
        )

        # Initialize AI client if API key provided
        ai_client = None
        if api_key:
            try:
                import anthropic  # type: ignore[import-not-found]

                ai_client = anthropic.AsyncAnthropic(api_key=api_key)
            except ImportError:
                pass  # AI features disabled, rule-based fallbacks active

        # Build engine
        self._engine = XyglueEngine(config=self.config, ai_client=ai_client)

    def register_tool(self, tool: Tool) -> None:
        """Register a tool for use in execution."""
        self._engine.register_tool(tool)

    async def run(
        self,
        goal: str,
        tools: list[str] | None = None,
        context: dict[str, Any] | None = None,
        mode: str | None = None,
        divergence: str | None = None,
        path: str | None = None,
    ) -> RunResult:
        """
        Run the XYGLUE pipeline.

        Args:
            goal: What to accomplish
            tools: Override available tools
            context: Additional context
            mode: Override mode ("semi" | "auto")
            divergence: Override divergence ("low" | "medium" | "high")
            path: Skip to specific path ("A" | "B" | "C")

        Returns:
            RunResult with status, output, brief, quality_score, etc.
        """
        return await self._engine.run(
            goal_input=goal,
            tools=tools,
            context=context,
            mode=mode,
            divergence=divergence,
            path=path,
        )

    async def approve(self, pending_result: RunResult, path: str = "A") -> RunResult:
        """Approve and execute a pending semi-autonomous result."""
        return await self._engine.approve_and_execute(pending_result, path=path)

    @property
    def stats(self) -> dict[str, Any]:
        """Get framework statistics."""
        return {
            "ground": self._engine.ground_tracker.get_stats(),
            "templates": self._engine.template_library.get_stats(),
            "patterns": self._engine.pattern_library.get_stats(),
        }
