from datetime import datetime
from models.docchat import ChatMessage, ChatSession


class ChatService:
    @staticmethod
    async def insert_new_record(db, user_id, **kwargs):
        """
        Insert a new record into the financial_information_pages table using MySQLDB's execute_insert.

        :param db: An instance of MySQLDB
        :param kwargs: Dictionary of column values for the new record
        """
        new_record = ChatMessage(
            **kwargs,
            created_at=datetime.now(),
            created_by=user_id,
        )
        new_record.update_modify(user_id)
        record = await db.execute_insert(new_record)
        return record

    @staticmethod
    async def create_chat_session(
        db, current_user, project_id, team_id, selected_files
    ):
        "Create a new chat session"
        new_session = ChatSession(
            created_at=datetime.now(),
            created_by=current_user.user_id,
            project_id=project_id,
            team_id=team_id,
            selected_files=selected_files,
        )
        new_session.update_modify(current_user.user_id)

        record = await db.execute_insert(new_session)
        return record

    @staticmethod
    async def get_latest_session_for_user(db, user, project_id, team_id):
        "Get the last session for a user"
        filters = [
            ChatSession.created_by == user.user_id,
            ChatSession.is_active == True,
            ChatSession.project_id == project_id,
            ChatSession.team_id == team_id,
        ]
        order_by = [ChatSession.modified_at.desc()]
        limit = 1
        return await db.execute_query(
            ChatSession, filters=filters, order_by=order_by, limit=limit
        )

    @staticmethod
    async def get_all_sessions_for_user(db, user, project_id, team_id):
        "Get all sessions for a user"
        filters = [
            ChatSession.created_by == user.user_id,
            ChatSession.project_id == project_id,
            ChatSession.team_id == team_id,
        ]
        order_by = [ChatSession.modified_at.desc()]
        return await db.execute_query(
            ChatSession,
            filters=filters,
            order_by=order_by,
        )

    @staticmethod
    async def get_messages_for_session(db, session_id, offset=0, limit=10):
        "Get all messages for a session"
        filters = [ChatMessage.session_id == session_id]
        order_by = [ChatMessage.created_at.desc()]
        return await db.execute_query(
            ChatMessage, filters=filters, order_by=order_by, limit=limit, offset=offset
        )

    @staticmethod
    async def end_chat_session(db, session_id, current_user):
        "End a chat session"
        filters = [
            ChatSession.session_id == session_id,
            ChatSession.created_by == current_user.user_id,
        ]
        values = {"is_active": False}
        values["modified_at"] = datetime.now()
        values["modified_by"] = current_user.user_id

        return await db.update_record(ChatSession, filters=filters, values=values)

    @staticmethod
    async def update_chat_session(db, session_id, payload, current_user):
        "Update a chat session"
        filters = [ChatSession.session_id == session_id]
        values = {}
        if payload.is_active:
            values["is_active"] = payload.is_active
        if payload.selected_files:
            values["selected_files"] = payload.selected_files

        values["modified_at"] = datetime.now()
        values["modified_by"] = current_user.user_id

        session = await db.update_record(ChatSession, filters=filters, values=values)
        return session
