import logging
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

try:
    from src.utils.db import get_db
except ImportError:
    from utils.db import get_db

from . import controller
from .schemas import (
    ChatRequest, ChatResponse, ChatData, ChatErrorResponse,
    ChatHistoryListResponse, ChatHistoryDetailResponse,
    ChatSessionListItem, ChatSessionDetail
)
from .services import chat_history_service

logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/chat", response_model=ChatResponse, tags=["Smart Inventory - Frontend"])
def inventory_chat(
    request: ChatRequest,
    db: Session = Depends(get_db)
):
    """
    AI-powered chat endpoint for querying inventory data using natural language.
    Supports continuous conversation with context memory.
    All conversations are persisted to the database.
    
    **Session Management:**
    - **First message**: Send `chat_session_id: null` to start a new conversation
    - **Response**: You'll receive a `chat_session_id` in the response
    - **Follow-up**: Send the same `chat_session_id` to continue the conversation
    - **New chat**: Send `chat_session_id: null` again to start fresh
    - **Context**: Last 5 questions and answers are sent to LLM for context
    
    **Example questions:**
    - "What are the top 10 fast-moving products?"
    - "Tell me more about the first one" (follow-up)
    - "What about location 2?" (follow-up with context)
    - "Show me products that are out of stock"
    
    **Request body:**
    ```json
    {
        "chat_session_id": null,  // or existing session ID
        "company_id": 1,
        "user_id": 1,
        "store_id": 1,
        "branch_id": 1,
        "question": "What are my top selling products?"
    }
    ```
    """
    try:
        result = controller.process_chat_query(
            db=db,
            company_id=request.company_id,
            question=request.question,
            user_id=request.user_id,
            store_id=request.store_id,
            branch_id=request.branch_id,
            chat_session_id=request.chat_session_id
        )
        
        return ChatResponse(
            success=True,
            data=ChatData(**result),
            message="Query processed successfully"
        )
        
    except Exception as e:
        logger.error(f"Error in inventory chat endpoint: {str(e)}")
        
        # Generate a session ID for error response if needed
        from .services import chat_session_service
        session_id = request.chat_session_id
        if session_id is None:
            try:
                session_id = chat_session_service.create_session(request.company_id)
            except Exception:
                session_id = "error-session"
        
        return ChatResponse(
            success=False,
            data=ChatData(
                chat_session_id=session_id,
                raw_data=None,
                answer=f"An error occurred while processing your question: {str(e)}"
            ),
            message="Error processing query"
        )


@router.get("/chat/history", response_model=ChatHistoryListResponse, tags=["Smart Inventory - Frontend"])
def get_chat_history_list(
    user_id: int = Query(..., description="User ID"),
    store_id: int = Query(..., description="Store ID"),
    branch_id: int = Query(..., description="Branch ID"),
    page: int = Query(1, ge=1, description="Page number (1-indexed)"),
    page_size: int = Query(20, ge=1, le=100, description="Number of items per page"),
    db: Session = Depends(get_db)
):
    """
    Get paginated list of chat sessions for a user/store/branch.
    
    Returns chat sessions ordered by most recently updated first.
    Each session includes:
    - `chat_session_id`: Use this to open/continue a chat
    - `chat_name`: Derived from the first question asked
    - `message_count`: Total number of messages in the conversation
    
    **Usage:**
    - Display as a list of previous chats in the sidebar
    - Click on a chat to load its details using the `/chat/history/{chat_session_id}` endpoint
    """
    try:
        sessions, total = chat_history_service.get_chat_history_list(
            db=db,
            user_id=user_id,
            store_id=store_id,
            branch_id=branch_id,
            page=page,
            page_size=page_size
        )
        
        return ChatHistoryListResponse(
            success=True,
            data=[ChatSessionListItem(**s) for s in sessions],
            total=total,
            page=page,
            page_size=page_size,
            message="Chat history retrieved successfully"
        )
        
    except Exception as e:
        logger.error(f"Error getting chat history list: {str(e)}")
        return ChatHistoryListResponse(
            success=False,
            data=[],
            total=0,
            page=page,
            page_size=page_size,
            message=f"Error retrieving chat history: {str(e)}"
        )


@router.get("/chat/history/{chat_session_id}", response_model=ChatHistoryDetailResponse, tags=["Smart Inventory - Frontend"])
def get_chat_history_detail(
    chat_session_id: str,
    db: Session = Depends(get_db)
):
    """
    Get detailed chat session with all messages.
    
    Use this endpoint when user clicks on a chat from the history list.
    Returns all messages in chronological order.
    
    **Usage:**
    - Load all messages to display the full conversation
    - User can continue the chat by sending new messages with the same `chat_session_id`
    """
    try:
        session_detail = chat_history_service.get_chat_session_detail(
            db=db,
            chat_session_id=chat_session_id
        )
        
        if session_detail is None:
            return ChatHistoryDetailResponse(
                success=False,
                data=None,
                message="Chat session not found"
            )
        
        return ChatHistoryDetailResponse(
            success=True,
            data=ChatSessionDetail(**session_detail),
            message="Chat session retrieved successfully"
        )
        
    except Exception as e:
        logger.error(f"Error getting chat history detail: {str(e)}")
        return ChatHistoryDetailResponse(
            success=False,
            data=None,
            message=f"Error retrieving chat session: {str(e)}"
        )
