"""Command for creating a new chat session."""

from dataclasses import dataclass
from uuid import UUID

from alloy_runtime_sdk.api_client.client import ApiClient
from alloy_runtime_types.dtos.sessions import CreateSessionRequest
from alloy_runtime_sdk.logging.config import get_logger

from cli.tui.chat.commands.base import CommandResult
from cli.tui.chat.store import ChatStore
from cli.tui.chat.types import ChatPhase

logger = get_logger(__name__)


@dataclass
class CreateSessionResult:
    """Result data for create session operation.

    Supports both agent mode and direct model mode.

    Attributes:
        session_id: ID of the newly created session.
        session_name: Name of the session.
        agent_id: ID of the agent (agent mode).
        agent_name: Name of the agent (agent mode).
        provider_key: Provider key (model mode).
        provider_model_name: Model name (model mode).
        system_instruction: System instruction (model mode).
    """

    session_id: UUID
    session_name: str | None
    # Agent mode
    agent_id: UUID | None = None
    agent_name: str | None = None
    # Model mode
    provider_key: str | None = None
    provider_model_name: str | None = None
    system_instruction: str | None = None


@dataclass
class CreateSessionCommand:
    """Command to create a new chat session.

    Supports two modes:
    - Agent mode: Uses agent_id/agent_name
    - Model mode: Uses provider_key/provider_model_name/system_instruction

    This command:
    1. Transitions store to CREATING_SESSION phase
    2. Sends create request to the API
    3. Updates store with new session context
    4. Clears any existing messages
    5. Transitions back to IDLE

    Attributes:
        client: Server client for API calls.
        store: Chat store for state management.
        name: Optional name for the session.
        agent_id: ID of the agent to use (agent mode).
        agent_name: Name of the agent (agent mode).
        provider_key: Provider key (model mode).
        provider_model_name: Model name (model mode).
        system_instruction: System instruction (model mode).
    """

    client: ApiClient
    store: ChatStore
    name: str | None
    # Agent mode
    agent_id: UUID | None = None
    agent_name: str | None = None
    # Model mode
    provider_key: str | None = None
    provider_model_name: str | None = None
    system_instruction: str | None = None

    async def execute(self) -> CommandResult[CreateSessionResult]:
        """Execute the create session operation.

        Returns:
            CommandResult with new session data on success.
        """
        logger.info(
            "create_session_starting",
            agent_id=str(self.agent_id) if self.agent_id else None,
            agent_name=self.agent_name,
            model=self.provider_model_name,
        )
        self.store.set_phase(ChatPhase.CREATING_SESSION)

        try:
            # Create session request - agent is optional
            # For model mode, we don't associate an agent with the session
            request = CreateSessionRequest(
                name=self.name,
                agent=str(self.agent_id) if self.agent_id else None,
            )
            session = await self.client.create_session(request)

            # Update store with new session
            self.store.set_session(
                session_id=session.id,
                session_name=self.name,
                agent_id=self.agent_id,
                agent_name=self.agent_name,
                message_count=0,
                provider_key=self.provider_key,
                model_name=self.provider_model_name,
                system_instruction=self.system_instruction,
            )
            self.store.set_messages([])
            self.store.set_phase(ChatPhase.IDLE)

            logger.info("create_session_completed", session_id=str(session.id))
            return CommandResult[CreateSessionResult](
                success=True,
                data=CreateSessionResult(
                    session_id=session.id,
                    session_name=self.name,
                    agent_id=self.agent_id,
                    agent_name=self.agent_name,
                    provider_key=self.provider_key,
                    provider_model_name=self.provider_model_name,
                    system_instruction=self.system_instruction,
                ),
            )

        except Exception as e:
            logger.warning("create_session_failed", error=str(e))
            self.store.set_phase(ChatPhase.IDLE)
            return CommandResult[CreateSessionResult](success=False, error=str(e))
