from datetime import datetime
from configs.ragflow import ragflow
from services.dataset import create_initial_dataset, get_dataset_by_name
from settings import settings
from configs.logger import get_logger
import json

logger = get_logger(__name__)


def create_chat_assistant(user_id: str):
    datasets = get_dataset_by_name(user_id)
    if len(datasets) == 0:
        datasets = [create_initial_dataset(user_id)]
    return ragflow.create_chat(user_id)


def get_chat_assistant(user_id: str):
    chats = []
    try:
        chats = ragflow.list_chats(name=user_id)
    except Exception as e:
        chats = []
    if len(chats) > 0:
        return chats[0]
    else:
        return create_chat_assistant(user_id)


def create_chat_session(user_id: str):
    chat = get_chat_assistant(user_id)
    if not chat:
        return None
    session_name = f"New session {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    return chat.create_session(session_name)


def get_chat_session(user_id: str):
    sessions = []
    try:
        chat = get_chat_assistant(user_id)
        sessions = chat.list_sessions()
    except Exception as e:
        logger.error(f"Error getting chat session: {e}")
        return []
    if len(sessions) > 0:
        return sessions[0]
    else:
        return create_chat_session(user_id)


def ask_ragflow(user_id: str, question: str, stream: bool = False):
    session = create_chat_session(user_id)
    if not session:
        return {
            "data": {
                "reference": [],
                "answer": "Mock response: This is a test response for local testing"
            }
        }

    # Mock response for local testing
    return {
        "data": {
            "reference": [],
            "answer": "Mock response: This is a test response for local testing"
        }
    }