"""Runner factory for hybrid SDK/Provider routing.

This module provides factory functions to create the appropriate runner
based on the model type:
- Claude models → SDKAgentRunner (uses Anthropic Agent SDK)
- Other models → AgentRunner (uses OpenAI-compatible API)
"""

from pathlib import Path
from typing import Optional, Union, TYPE_CHECKING

from .sdk_runner import SDKAgentRunner, is_claude_model
from .agent_runner import AgentRunner
from ...utils.logger import log

if TYPE_CHECKING:
    from ..events import AgentEventEmitter


def get_runner(
    model: str,
    cwd: Optional[str] = None,
    emitter: Optional["AgentEventEmitter"] = None,
    system_prompt: Optional[str] = None,
    plan_mode: bool = False,
    prefer_sdk: bool = True,
    **kwargs,
) -> Union[SDKAgentRunner, AgentRunner]:
    """Get the appropriate runner for the model.

    Routes to SDKAgentRunner for Claude models (uses Anthropic Agent SDK),
    or AgentRunner for other models (uses OpenAI-compatible API).

    Args:
        model: Model string (e.g., "claude-sonnet-4", "fireworks:minimax-m2p1")
        cwd: Working directory
        emitter: Event emitter for streaming
        system_prompt: Custom system prompt
        plan_mode: If True, restrict to read-only tools
        prefer_sdk: If True, prefer SDK for Claude models (default True)
        **kwargs: Additional arguments passed to runner

    Returns:
        SDKAgentRunner or AgentRunner instance

    Example:
        # Claude model → uses SDK
        runner = get_runner("claude-sonnet-4")

        # Fireworks model → uses standard provider
        runner = get_runner("fireworks:accounts/fireworks/models/minimax-m2p1")

        # Force standard provider even for Claude
        runner = get_runner("claude-sonnet-4", prefer_sdk=False)
    """
    use_sdk = prefer_sdk and is_claude_model(model)

    if use_sdk:
        log.info(f"Using SDKAgentRunner for Claude model: {model}")
        return SDKAgentRunner(
            model=model,
            cwd=cwd,
            emitter=emitter,
            system_prompt=system_prompt,
            plan_mode=plan_mode,
        )
    else:
        log.info(f"Using AgentRunner for model: {model}")
        # Import toolkit here to avoid circular imports
        from ..toolkit import AgentToolkit

        # Generate plan file path when in plan mode
        plan_file_path = None
        repo_root = Path(cwd) if cwd else Path.cwd()
        if plan_mode:
            plan_file_path = str(repo_root / ".emdash" / "plan.md")
            # Ensure .emdash directory exists
            (repo_root / ".emdash").mkdir(exist_ok=True)

        toolkit = AgentToolkit(
            repo_root=repo_root,
            plan_mode=plan_mode,
            plan_file_path=plan_file_path,
        )

        return AgentRunner(
            toolkit=toolkit,
            model=model,
            emitter=emitter,
            system_prompt=system_prompt,
            **kwargs,
        )


def create_hybrid_runner(
    model: str,
    **kwargs,
) -> Union[SDKAgentRunner, AgentRunner]:
    """Convenience alias for get_runner.

    Args:
        model: Model string
        **kwargs: Passed to get_runner

    Returns:
        Appropriate runner instance
    """
    return get_runner(model, **kwargs)
