from __future__ import annotations

from collections.abc import AsyncGenerator, Sequence
import types
from typing import TYPE_CHECKING, Protocol

from vibe.core.types import AvailableTool, LLMChunk, LLMMessage, StrToolChoice

if TYPE_CHECKING:
    from vibe.core.config import ModelConfig


class BackendLike(Protocol):
    """Port protocol for dependency-injectable LLM backends.

    Any backend used by AgentLoop should implement this async context manager
    interface with `complete` and `complete_streaming` methods.
    """

    async def __aenter__(self) -> BackendLike: ...
    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: types.TracebackType | None,
    ) -> None: ...

    async def complete(
        self,
        *,
        model: ModelConfig,
        messages: Sequence[LLMMessage],
        temperature: float,
        tools: list[AvailableTool] | None,
        max_tokens: int | None,
        tool_choice: StrToolChoice | AvailableTool | None,
        extra_headers: dict[str, str] | None,
        metadata: dict[str, str] | None = None,
    ) -> LLMChunk:
        """Complete a chat conversation using the specified model and provider.

        Args:
            model: Model configuration
            messages: List of conversation messages
            temperature: Sampling temperature (0.0 to 1.0)
            tools: Optional list of available tools
            max_tokens: Maximum tokens to generate
            tool_choice: How to choose tools (auto, none, or specific tool)
            extra_headers: Additional HTTP headers to include
            metadata: Optional metadata to attach to the request

        Returns:
            LLMChunk containing the response message and usage information

        Raises:
            BackendError: If the API request fails
        """
        ...

    # Note: actual implementation should be an async function,
    # but we can't make this one async, as it would lead to wrong type inference
    # https://stackoverflow.com/a/68911014
    def complete_streaming(
        self,
        *,
        model: ModelConfig,
        messages: Sequence[LLMMessage],
        temperature: float,
        tools: list[AvailableTool] | None,
        max_tokens: int | None,
        tool_choice: StrToolChoice | AvailableTool | None,
        extra_headers: dict[str, str] | None,
        metadata: dict[str, str] | None = None,
    ) -> AsyncGenerator[LLMChunk, None]:
        """Equivalent of the complete method, but yields LLMEvent objects
        instead of a single LLMEvent.

        Args:
            model: Model configuration
            messages: List of conversation messages
            temperature: Sampling temperature (0.0 to 1.0)
            tools: Optional list of available tools
            max_tokens: Maximum tokens to generate
            tool_choice: How to choose tools (auto, none, or specific tool)
            extra_headers: Additional HTTP headers to include
            metadata: Optional metadata to attach to the request

        Returns:
            AsyncGenerator[LLMEvent, None] yielding LLMEvent objects

        Raises:
            BackendError: If the API request fails
        """
        ...
