# routes.py
from flask import Blueprint, render_template, request, jsonify


from app.services.file_service import parse_file  # 导入 service 中的函数
from app.services.chat_service import clear_chat_history, create_chat
from app.services.embed_service import parse_file_to_embed
from llm_model.get_vector_db import get_vector_db

main_bp = Blueprint('main', __name__)

# 主页


@main_bp.route('/')
def index():
    return render_template('index.html')

# 测试接口


@main_bp.route("/hello")
def hello():
    return "Hello, World!"

# 语音文件上传


@main_bp.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file part in the request"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No file selected for uploading"}), 400

    # 保存文件并解析
    res_obj = parse_file(file)
    return jsonify(res_obj), 200

# 关闭聊天记录


@main_bp.route('/closeMsg', methods=['DELETE'])
def del_msg():
    return jsonify({"msg": "清除成功",
                    "code": 200,
                    "chat_history": clear_chat_history(),
                    })

# 聊天


@main_bp.route('/msg', methods=['POST'])
def input_msg():
    # 从请求中获取JSON数据
    data = request.get_json()

    # 检查是否接收到数据
    if not data:
        return jsonify({"error": "No data received"}), 400

    # 打印接收到的消息
    print(data['msg'])
    msg = data['msg']
    type = data['type']

    json_res = create_chat(msg, type)

    # 返回响应
    return jsonify(json_res)

# 知识问答文件解析


@main_bp.route('/embed', methods=['POST'])
def route_embed():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']

    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    return parse_file_to_embed(file)

# 删除向量库


@main_bp.route('/embed', methods=['DELETE'])
def route_delete():
    db = get_vector_db()
    db.delete_collection()

    return jsonify({"message": "Collection deleted successfully"}), 200
