from flask import Flask, request
import os, sys

base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_path)
from ai_chat import parse_utils, sys_content
from ApiResponse import handle_exceptions
from ai_utils import get_bot_with_history, get_ai_chat_history, get_bot_with_history_rag
from parse_utils import get_last_user_value, convert_dialog_format

app = Flask(__name__)


@app.route('/api/chat', methods=['POST'])
@handle_exceptions
def get_chat_with_history():
    data = request.get_json()
    sys_list = [{"role": "system", "content": sys_content.action_content}]
    ai_reply, total_tokens = get_ai_chat_history(sys_list + get_last_user_value(data))
    if ai_reply.get('content') == '1':
        mag = parse_utils.extract_mp4_to_text(get_last_user_value(data)[0].get('content'))
        return mag
    elif ai_reply.get('content') == '2':
        sys_list = [{"role": "system", "content": sys_content.douyin_text_fix}]
        ai_reply, total_tokens = get_ai_chat_history(sys_list + convert_dialog_format(data))
        return ai_reply
    elif ai_reply.get('content') == '3':
        sys_list = [{"role": "system", "content": sys_content.helpful_content_text_rag}]
        ai_reply, total_tokens = get_bot_with_history_rag(sys_list + convert_dialog_format(data))
        return ai_reply
    else:
        sys_list = [{"role": "system", "content": sys_content.helpful_content_text}]
        ai_reply, total_tokens = get_bot_with_history(sys_list + convert_dialog_format(data))
        return ai_reply


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8088, debug=True)

    # print(get_chat_with_history([{'user': '提取文案https://www.douyin.com/video/7525861419037855018'}]))
