"""
Shared type definitions for BuzzTrail monorepo.

These types mirror the TypeScript definitions in libs/shared/types/src/lib/
and must be kept in sync manually. See TYPES.md for synchronization process.

Version: 1.0.0
Last synced: 2025-10-14
"""

from typing import TypedDict, Literal, Optional, List, Dict, Any
from datetime import datetime


# =============================================================================
# Database Schema Types (from supabase.ts)
# =============================================================================

ConversationSessionStatus = Literal[
    'generating_deck',
    'deck_ready',
    'bot_active',
    'completed',
    'error'
]


class ConversationSession(TypedDict):
    """
    Conversation session record.

    Represents an active Tavus conversation session with associated deck generation
    and bot lifecycle.
    """
    id: str  # Unique session identifier
    tavus_conversation_id: str  # Tavus conversation ID for video interaction
    daily_room_url: str  # Daily.co room URL for video conferencing
    status: ConversationSessionStatus  # Current session status
    created_at: str  # Timestamp when session was created
    updated_at: str  # Timestamp when session was last updated


SlideControlCommandType = Literal['next', 'prev', 'goto', 'sync', 'reload']


class SlidevDeck(TypedDict, total=False):
    """
    Slidev deck record.

    Represents a generated Slidev presentation deck.
    """
    id: str  # Unique database record identifier (required)
    deck_id: str  # Human-readable deck identifier (required)
    github_url: str  # GitHub Pages URL where deck is published (required)
    template_id: str  # Template ID used for deck generation (required)
    created_at: str  # Timestamp when deck was created (required)
    updated_at: str  # Timestamp when deck was last updated (required)
    session_id: str  # Associated session ID (optional, for session-linked decks)
    generation_data: Dict[str, Any]  # Additional generation data (flexible JSON field)


class SlideControlCommand(TypedDict, total=False):
    """
    Slide control command record.

    Commands sent to control slide navigation during presentations.
    """
    id: str  # Unique command identifier (required)
    session_id: str  # Associated session ID (required)
    command: SlideControlCommandType  # Command type (required)
    created_at: str  # Timestamp when command was created (required)
    slide_number: int  # Target slide number (for 'goto' command) (optional)


BotTypeValue = Literal['screenshare', 'screenshare_livekit', 'tool-forwarder', 'voice-agent']
ActiveBotStatus = Literal['spawning', 'running', 'stopping', 'stopped', 'error']


class ActiveBotRow(TypedDict, total=False):
    """
    Active bot database record.

    Tracks active bot processes for presentation sessions.
    This is the database schema - for application-level types, use types from bot section.
    """
    bot_id: str  # Unique bot identifier (required)
    bot_type: BotTypeValue  # Bot type (screenshare, screenshare_livekit, tool-forwarder, or voice-agent) (required)
    pid: int  # Operating system process ID (required)
    session_id: str  # Associated session ID (required)
    room_url: str  # Daily.co room URL (required)
    status: ActiveBotStatus  # Current bot status (required)
    spawned_at: str  # Timestamp when bot was spawned (required)
    created_at: str  # Timestamp when record was created (required)
    updated_at: str  # Timestamp when record was last updated (required)
    deck_url: str  # Slidev deck URL (for screenshare bots) (optional)
    stopped_at: str  # Timestamp when bot was stopped (optional)
    error_message: str  # Error message if bot failed (optional)
    log_file_path: str  # Path to bot log file (optional)


# Database Schema Structure
class DatabaseTablesConversationSessions(TypedDict):
    """Type structure for conversation_sessions table operations."""
    Row: ConversationSession
    # Note: Insert and Update types use Omit/Partial which aren't directly translatable to Python
    # These would need custom TypedDict definitions if needed


class DatabaseTablesSlidevDecks(TypedDict):
    """Type structure for slidev_decks table operations."""
    Row: SlidevDeck
    # Note: Insert and Update types use Omit/Partial which aren't directly translatable to Python


class DatabaseTablesSlideControlCommands(TypedDict):
    """Type structure for slide_control_commands table operations."""
    Row: SlideControlCommand
    # Note: Insert and Update types use Omit/Partial which aren't directly translatable to Python


class DatabaseTablesActiveBots(TypedDict):
    """Type structure for active_bots table operations."""
    Row: ActiveBotRow
    # Note: Insert and Update types use Omit/Partial which aren't directly translatable to Python


class DatabaseTables(TypedDict):
    """All database tables."""
    conversation_sessions: DatabaseTablesConversationSessions
    slidev_decks: DatabaseTablesSlidevDecks
    slide_control_commands: DatabaseTablesSlideControlCommands
    active_bots: DatabaseTablesActiveBots


class DatabasePublic(TypedDict):
    """Public schema structure."""
    Tables: DatabaseTables


class Database(TypedDict):
    """
    Supabase Database Schema.

    Type-safe database interface for all tables.
    """
    public: DatabasePublic


# =============================================================================
# API Request and Response Types (from api.ts)
# =============================================================================

class SlideData(TypedDict, total=False):
    """Slide data for deck generation."""
    title: str  # Slide title (required)
    content: str  # Slide content (supports Markdown) (required)
    layout: str  # Optional slide layout/theme (optional)


class GenerateCustomDeckRequest(TypedDict, total=False):
    """Request to generate a custom Slidev deck."""
    company: str  # Company name for deck customization (required)
    slides: List[SlideData]  # Array of slide data (required)
    template_id: str  # Optional template ID (defaults to 'default' if not provided) (optional)
    session_id: str  # Optional session ID to associate deck with a conversation (optional)


class GenerateCustomDeckResponse(TypedDict, total=False):
    """Response from deck generation."""
    deck_id: str  # Generated deck identifier (required)
    github_url: str  # GitHub Pages URL where deck is published (required)
    created_at: str  # Generation timestamp (required)
    session_id: str  # Associated session ID (if provided in request) (optional)


class SpawnScreenshareBotRequest(TypedDict, total=False):
    """Request to spawn a screenshare bot."""
    room_url: str  # Daily.co room URL (required)
    deck_url: str  # Slidev deck URL to present (required)
    session_id: str  # Session ID to associate bot with (required)
    meeting_token: str  # Optional Daily.co meeting token for authentication (optional)


class SpawnBotResponse(TypedDict, total=False):
    """Response from bot spawn operation."""
    bot_id: str  # Unique bot identifier (required)
    status: str  # Bot status (typically 'spawning' initially) (required)
    estimated_join_time: str  # Estimated time for bot to join room (required)
    message: str  # Success message (required)
    pid: int  # Process ID of spawned bot (optional)
    log_file: str  # Path to bot log file (optional)


class BotStatusRequest(TypedDict, total=False):
    """Request to get bot status."""
    bot_id: str  # Bot ID to query (optional, if not provided returns all bots)
    session_id: str  # Filter by session ID (optional)


class BotStatusDetails(TypedDict, total=False):
    """Bot status details."""
    bot_id: str  # Bot identifier (required)
    session_id: str  # Associated session ID (required)
    room_url: str  # Daily.co room URL (required)
    status: str  # Current bot status (required)
    pid: int  # Process ID (required)
    spawned_at: str  # When bot was spawned (required)
    deck_url: str  # Deck URL (for screenshare bots) (optional)
    stopped_at: str  # When bot was stopped (if applicable) (optional)
    error: str  # Error message (if failed) (optional)
    log_file: str  # Log file path (optional)
    is_process_alive: bool  # Whether the process is still alive (optional)


class BotStatusResponse(TypedDict, total=False):
    """Response from bot status query."""
    bot: BotStatusDetails  # Single bot status (when querying specific bot)
    bots: List[BotStatusDetails]  # Multiple bot statuses (when querying all bots)
    active_count: int  # Count of active bots


class KillBotRequest(TypedDict):
    """Request to kill a bot."""
    bot_id: str  # Bot ID to kill


class KillBotResponse(TypedDict):
    """Response from bot kill operation."""
    message: str  # Success message
    bot_id: str  # Bot ID that was killed
    status: str  # Updated status


class SpawnTavusToolForwarderRequest(TypedDict, total=False):
    """Request to spawn a Tavus tool forwarder bot."""
    room_url: str  # Daily.co room URL (required)
    session_id: str  # Session ID to associate bot with (required)
    meeting_token: str  # Optional Daily.co meeting token (optional)
    webhook_url: str  # Optional webhook URL for tool responses (optional)


SlideControlCommandValue = Literal['next', 'prev', 'goto', 'sync', 'reload']


class SlideControlRequest(TypedDict, total=False):
    """Slide control request."""
    session_id: str  # Session ID (required)
    command: SlideControlCommandValue  # Command type (required)
    slide_number: int  # Target slide number (required for 'goto' command) (optional)


class SlideControlResponse(TypedDict, total=False):
    """Slide control response."""
    success: bool  # Success indicator (required)
    command: str  # Command that was executed (required)
    current_slide: int  # Current slide number after command (optional)
    error: str  # Error message if failed (optional)


class ApiErrorResponse(TypedDict, total=False):
    """Error response structure."""
    error: str  # Error type/category (required)
    details: str  # Detailed error message (optional)
    validation_errors: Dict[str, str]  # Validation errors (field-specific) (optional)
    status: int  # HTTP status code (optional)


# =============================================================================
# Bot Configuration Types (from bot.ts)
# =============================================================================

BotType = Literal['screenshare', 'screenshare_livekit', 'tool-forwarder', 'voice-agent']
BotStatus = Literal['spawning', 'running', 'stopping', 'stopped', 'error']


class BotSpawnConfig(TypedDict, total=False):
    """Configuration for spawning a bot."""
    roomUrl: str  # Daily.co room URL to join (required)
    sessionId: str  # Session ID to associate bot with (required)
    deckUrl: str  # Slidev deck URL to present (for screenshare bots) (optional)
    meetingToken: str  # Optional Daily.co meeting token for authentication (optional)
    botType: BotType  # Bot type (optional)


class RoomProperties(TypedDict, total=False):
    """Daily.co room properties."""
    enable_screenshare: bool  # Enable screenshare
    enable_chat: bool  # Enable chat
    max_participants: int  # Maximum participants
    exp: int  # Room expiration time


class RoomConfig(TypedDict, total=False):
    """Daily.co room configuration."""
    url: str  # Daily.co room URL (required)
    name: str  # Room name/identifier (optional)
    token: str  # Meeting token for authentication (optional)
    properties: RoomProperties  # Room properties (privacy settings, etc.) (optional)


class Resolution(TypedDict):
    """Video resolution."""
    width: int
    height: int


class Viewport(TypedDict):
    """Browser viewport size."""
    width: int
    height: int


class BrowserConfig(TypedDict, total=False):
    """Browser configuration for rendering."""
    headless: bool  # Headless mode (default: true) (optional)
    viewport: Viewport  # Viewport size (optional)


class ScreenshareBotConfig(TypedDict, total=False):
    """Screenshare bot specific configuration."""
    room: RoomConfig  # Daily.co room configuration (required)
    deckUrl: str  # Slidev deck URL to present (required)
    sessionId: str  # Session ID (required)
    fps: int  # Frames per second for screenshare (default: 10) (optional)
    resolution: Resolution  # Video resolution (optional)
    browser: BrowserConfig  # Browser configuration for rendering (optional)


class ToolDefinition(TypedDict, total=False):
    """Tool definition for Tavus conversation."""
    name: str  # Tool name/identifier (required)
    description: str  # Tool description (required)
    inputSchema: Dict[str, Any]  # Input schema (JSON Schema) (optional)
    requiresConfirmation: bool  # Whether tool requires confirmation (optional)


class TavusToolForwarderBotConfig(TypedDict, total=False):
    """Tavus tool forwarder bot configuration."""
    room: RoomConfig  # Daily.co room configuration (required)
    sessionId: str  # Session ID (required)
    webhookUrl: str  # Webhook URL for tool call responses (optional)
    tools: List[ToolDefinition]  # Tool definitions to forward (optional)


class ActiveBot(TypedDict, total=False):
    """
    Active bot instance metadata.

    Note: TypeScript uses Date objects for spawnedAt/stoppedAt,
    but in Python these should be datetime objects when used in code.
    """
    botId: str  # Unique bot identifier (required)
    botType: BotType  # Bot type (required)
    sessionId: str  # Session ID (required)
    roomUrl: str  # Daily.co room URL (required)
    status: BotStatus  # Current status (required)
    spawnedAt: datetime  # When bot was spawned (required)
    deckUrl: str  # Deck URL (for screenshare bots) (optional)
    pid: int  # Process ID (optional)
    stoppedAt: datetime  # When bot was stopped (optional)
    error: str  # Error message if failed (optional)
    logFilePath: str  # Log file path (optional)


class BotSpawnResult(TypedDict, total=False):
    """Bot spawn result."""
    botId: str  # Bot identifier (required)
    status: BotStatus  # Initial status (required)
    estimatedJoinTime: str  # Estimated time to join room (required)
    pid: int  # Process ID (optional)
    logFilePath: str  # Log file path (optional)


BotLifecycleEvent = Literal[
    'bot-spawned',
    'bot-joined',
    'bot-exited',
    'bot-error',
    'bot-killed'
]


class BotLifecycleEventPayload(TypedDict, total=False):
    """Bot lifecycle event payload."""
    event: BotLifecycleEvent  # Event type (required)
    botId: str  # Bot identifier (required)
    sessionId: str  # Session ID (required)
    timestamp: str  # Timestamp (required)
    data: Dict[str, Any]  # Additional event data (optional)


# Note: BotManager is an interface with methods, which doesn't translate to TypedDict.
# In Python, this would be implemented as a Protocol or ABC (Abstract Base Class).
# Example using typing.Protocol:
#
# from typing import Protocol
#
# class BotManager(Protocol):
#     def spawnBot(self, config: BotSpawnConfig) -> BotSpawnResult: ...
#     def killBot(self, botId: str) -> None: ...
#     def getBotStatus(self, botId: str) -> Optional[ActiveBot]: ...
#     def getAllBotsStatus(self) -> Dict[str, Any]: ...  # Returns {"activeCount": int, "bots": List[ActiveBot]}
#     def findBotBySessionId(self, sessionId: str) -> Optional[str]: ...
#     def shutdown(self) -> None: ...
