"""Chat service: send messages, stream responses, manage conversations."""

from __future__ import annotations

from gemini_web_mcp_cli.core.client import GeminiClient
from gemini_web_mcp_cli.core.constants import Model
from gemini_web_mcp_cli.core.models import ConversationMetadata, StreamResponse


class ChatService:
    """Service for chat interactions with Gemini.

    Wraps GeminiClient.send() with conversation state management
    and convenience methods.
    """

    def __init__(self, client: GeminiClient):
        self.client = client
        self._metadata: ConversationMetadata | None = None

    async def send(
        self,
        prompt: str,
        model: str | Model | None = None,
        conversation_id: str | None = None,
        gem_id: str | None = None,
        files: list[str] | None = None,
    ) -> StreamResponse:
        """Send a message and get a complete response.

        For multi-turn conversations, the metadata is automatically
        tracked between calls.

        Args:
            files: Optional list of file paths to upload and attach.
        """
        import mimetypes
        from pathlib import Path

        from gemini_web_mcp_cli.services.file import FileService

        file_data = None
        if files:
            file_data = []
            file_service = FileService(self.client)
            for fpath in files:
                p = Path(fpath)
                file_id = await file_service.upload(p)
                mime_type, _ = mimetypes.guess_type(p)
                mime_type = mime_type or "application/octet-stream"

                # Format discovered via Chrome DevTools MCP live capture
                file_data.append([
                    [file_id, 16, None, mime_type],
                    p.name,
                    None, None, None, None, None, None,
                    [0]
                ])

        # Use stored metadata for multi-turn, or start fresh
        metadata = self._metadata if self._metadata and not conversation_id else None

        response = await self.client.send(
            prompt=prompt,
            model=model,
            metadata=metadata,
            gem_id=gem_id,
            file_data=file_data,
        )

        # Update metadata for next turn
        if response.metadata and response.metadata.cid:
            self._metadata = response.metadata

        return response

    def reset(self) -> None:
        """Reset conversation state (start a new conversation)."""
        self._metadata = None

    @property
    def conversation_id(self) -> str | None:
        """Get the current conversation ID, if in a multi-turn conversation."""
        if self._metadata:
            return self._metadata.cid
        return None
