import json
import uuid

from fastapi.responses import JSONResponse
from starlette.responses import StreamingResponse

from Log import logger
from app.api import Response, token_required

from app.config.const import IMAGE_TO_TEXT, DOCUMENT_TO_CLEANING, DOCUMENT_TO_REPORT, DIFY, BISHENG, RAGFLOW, \
    DOCUMENT_IA_QUESTIONS, DOCUMENT_TO_REPORT_TITLE, DOCUMENT_TO_TITLE, DOCUMENT_TO_PAPER, \
    DOCUMENT_IA_QUESTIONS_EQUIPMENT, dialog_chat, workflow_chat, advanced_chat, agent_chat, base_chat
from app.models.public_api_model import DfToken
from app.service.v2.api_token import DfTokenDao
from app.service.v2.initialize_data import dialog_menu_sync, create_menu_sync, user_update_app
# from app.task.sync_resources import sync_knowledge, sync_dialog, sync_agent, sync_llm, sync_resource
from fastapi import Depends, APIRouter, File, UploadFile
from sqlalchemy.orm import Session
from app.config.const import smart_message_error, http_400, http_500, http_200, complex_dialog_chat
from app.models import UserModel
from app.models.base_model import get_db
from app.models.v2.session_model import ChatData
from app.service.v2.chat import service_chat_dialog, get_chat_info, service_chat_sessions, service_chat_workflow

public_api = APIRouter()


@public_api.post("/sync/df_token", response_model=Response)
async def sync_df_token(df: DfToken, db=Depends(get_db)):
    token_dict = {IMAGE_TO_TEXT: df.image, DOCUMENT_TO_CLEANING: df.clean,DOCUMENT_IA_QUESTIONS_EQUIPMENT: df.equipment,
                  DOCUMENT_IA_QUESTIONS: df.doc, DOCUMENT_TO_REPORT_TITLE: df.report,DOCUMENT_TO_TITLE: df.title,DOCUMENT_TO_PAPER: df.paper}

    try:
        for api_id, token in token_dict.items():
            if not token:
                continue
            DfTokenDao(db).update_and_insert_token(api_id, token)
    except Exception as e:
        logger.error(e)
        return Response(code=500, msg="failed", data={})

    return Response(code=200, msg="successfully", data={})


# @public_api.post("/sync/app_register", response_model=Response)
# async def sync_app_register(apr: AppRegister, db=Depends(get_db)):
#     app_dict = {RAGFLOW: apr.rg, BISHENG: apr.bs, DIFY: apr.df}
#
#     try:
#         for app_id, status in app_dict.items():
#             AppRegisterDao(db).update_and_insert_app(app_id, status)
#     except Exception as e:
#         logger.error(e)
#         return Response(code=500, msg="failed", data={})
#
#     return Response(code=200, msg="successfully", data={})


@public_api.get("/sync/resource", response_model=Response)
async def sync_resource_data(resource_type: int, db=Depends(get_db)):
    if resource_type == 1:
        await sync_knowledge()
    elif resource_type == 2:
        await sync_dialog()
    elif resource_type == 3:
        await sync_agent()
    elif resource_type == 4:
        await sync_llm()
    else:
        await sync_resource()

    return Response(code=200, msg="", data={})


@public_api.get("/sync/dialog_menu", response_model=Response)
async def sync_dialog_menu(db=Depends(get_db)):
    try:
        await dialog_menu_sync(db)
    except Exception as e:
        logger.error(e)
        return Response(code=500, msg="failed", data={})

    return Response(code=200, msg="success", data={})


@public_api.get("/sync/create/dialog_menu", response_model=Response)
async def get_dialog_menu(db=Depends(get_db)):
    try:
        result = await create_menu_sync(db)
        return JSONResponse(content={"code": 200, "msg": "", "data": result})
    except Exception as e:
        return JSONResponse(content={"code": 500, "msg": str(e), "data": {"error": "Failed to create menu"}})


@public_api.post("/sync/update_app", response_model=Response)
async def sync_update_app(userid, db=Depends(get_db)):
    try:
        await user_update_app(userid, db)
    except Exception as e:
        logger.error(e)
        return Response(code=500, msg=str(e), data={})

    return Response(code=200, msg="success", data={})


@public_api.post("/chat/{chatId}/completions")
async def api_chat_dialog(chatId:str, dialog: ChatData, current_user: UserModel = Depends(token_required),db: Session = Depends(get_db)): #  current_user: UserModel = Depends(get_current_user)
    chat_info = await get_chat_info(db, chatId)
    if not chat_info:
        error_msg = json.dumps(
            {"message": smart_message_error, "error": "\n**ERROR**: parameter exception", "status": http_400})
        return StreamingResponse(f"data: {error_msg}\n\n",
                                 media_type="text/event-stream")
    if chat_info.mode == dialog_chat:

        session_id = dialog.sessionId
        if not dialog.query:
            error_msg = json.dumps(
                {"message": smart_message_error, "error": "\n**ERROR**: question cannot be empty.", "status": http_400})
            return StreamingResponse(f"data: {error_msg}\n\n",
                                     media_type="text/event-stream")
        if not session_id:
            session = await service_chat_sessions(db, chatId, dialog.query)
            # print(session)
            if not session or session.get("code") != 0:
                error_msg = json.dumps(
                    {"message": smart_message_error, "error": "\n**ERROR**: chat agent error", "status": http_500})
                return StreamingResponse(f"data: {error_msg}\n\n",
                                         media_type="text/event-stream")
            session_id = session.get("data", {}).get("id")
        return StreamingResponse(service_chat_dialog(db, chatId, dialog.query, session_id, current_user.id, chat_info.mode),
                                 media_type="text/event-stream")
    elif chat_info.mode == workflow_chat:
        chat_info = await get_chat_info(db, chatId)
        if not chat_info:
            error_msg = json.dumps(
                {"message": smart_message_error, "error": "\n**ERROR**: parameter exception", "status": http_400})
            return StreamingResponse(f"data: {error_msg}\n\n",
                                     media_type="text/event-stream")
        session_id = dialog.sessionId
        if not session_id:
            session_id = str(uuid.uuid4()).replace("-", "")
        return StreamingResponse(service_chat_workflow(db, chatId, dialog, session_id, current_user.id, chat_info.mode),
                                 media_type="text/event-stream")

    elif chat_info.mode == advanced_chat or chat_info.mode == agent_chat or chat_info.mode == base_chat:
        chat_info = await get_chat_info(db, chatId)
        if not chat_info:
            error_msg = json.dumps(
                {"message": smart_message_error, "error": "\n**ERROR**: parameter exception", "status": http_400})
            return StreamingResponse(f"data: {error_msg}\n\n",
                                     media_type="text/event-stream")
        session_id = dialog.sessionId
        if not session_id:
            session_id = str(uuid.uuid4()).replace("-", "")
        return StreamingResponse(service_chat_workflow(db, chatId, dialog, session_id, current_user.id, chat_info.mode),
                                 media_type="text/event-stream")
    else:
        error_msg = json.dumps(
            {"message": smart_message_error, "error": "\n**ERROR**: unknown chat", "status": http_400})
        return StreamingResponse(f"data: {error_msg}\n\n",
                                 media_type="text/event-stream")
