from pydantic import BaseModel, Field
from typing import Optional, List, Any, Dict
from datetime import datetime


class ChatRequest(BaseModel):
    """Request schema for chat endpoint"""
    chat_session_id: Optional[str] = Field(None, description="Chat session ID for continuous conversation. Send null for new chat.")
    company_id: int = Field(..., description="Company ID to query data for")
    user_id: int = Field(..., description="User ID")
    store_id: int = Field(..., description="Store ID")
    branch_id: int = Field(..., description="Branch ID")
    question: str = Field(..., description="Natural language question about inventory data")


class ChatData(BaseModel):
    """Data structure for chat response"""
    chat_session_id: str = Field(..., description="Chat session ID to use for follow-up questions")
    raw_data: Optional[List[Dict[str, Any]]] = None
    answer: str


class ChatResponse(BaseModel):
    """Response schema for chat endpoint"""
    success: bool
    data: ChatData
    message: str


class ChatErrorResponse(BaseModel):
    """Error response schema for chat endpoint"""
    success: bool = False
    message: str
    error_code: Optional[str] = None
    details: Optional[Dict[str, Any]] = None


# ============== Chat History Schemas ==============

class ChatMessageSchema(BaseModel):
    """Schema for a single chat message"""
    id: int
    role: str
    content: str
    created_at: datetime

    class Config:
        from_attributes = True


class ChatSessionListItem(BaseModel):
    """Schema for chat session in list view"""
    id: int
    chat_session_id: str
    chat_name: Optional[str]
    company_id: int
    user_id: int
    store_id: int
    branch_id: int
    created_at: datetime
    updated_at: datetime
    message_count: int = 0

    class Config:
        from_attributes = True


class ChatSessionDetail(BaseModel):
    """Schema for detailed chat session with messages"""
    id: int
    chat_session_id: str
    chat_name: Optional[str]
    company_id: int
    user_id: int
    store_id: int
    branch_id: int
    created_at: datetime
    updated_at: datetime
    messages: List[ChatMessageSchema]

    class Config:
        from_attributes = True


class ChatHistoryListResponse(BaseModel):
    """Response schema for chat history list"""
    success: bool
    data: List[ChatSessionListItem]
    total: int
    page: int
    page_size: int
    message: str


class ChatHistoryDetailResponse(BaseModel):
    """Response schema for chat history detail"""
    success: bool
    data: Optional[ChatSessionDetail]
    message: str

