// ==============================================================================
// 模块: BAI 微信风聊天测试页 (v1.4 修复版)
// ==============================================================================

// 1. 渲染页面路由
routerAdd("GET", "/bai-chat", (c) => {
    try {
        // 确保 views/bai-chat-index.html 路径存在
        const html = $template.loadFiles(__hooks + "/bai_chat_alm_hooks/views/bai-chat-index.html").render({});
        const safeHtml = String(html || "")
        const guardScript = '<script>(function(){var token=localStorage.getItem("pb_manage_token")||"";var isLoggedIn=localStorage.getItem("pb_manage_logged_in")==="1";if(!token||!isLoggedIn){window.location.replace("/pb/manage/login");}})()</script>'
        const guardedHtml = safeHtml.indexOf("</head>") !== -1
            ? safeHtml.replace("</head>", guardScript + "</head>")
            : guardScript + safeHtml
        return c.html(200, guardedHtml);
    } catch (e) {
        return c.json(500, { "message": "HTML 模板渲染失败: " + e.message });
    }
});

// 2. 聊天转发路由
routerAdd("POST", "/pb-api-v1/chat/send", (c) => {
    try {
        const info = c.requestInfo();
        // 增加安全取值逻辑
        const body = info.body || {};
        const userMsg = body.message || "";

        if (!userMsg) {
            return c.json(400, { "message": "消息内容不能为空" });
        }

        // 使用 3001 端口直连 AnythingLLM
        // 如果 8888 还没创建成功，API 会自动回落到默认线程，保证不报错
        const res = $http.send({
            url: "http://bai-anythingllm:3001/api/v1/workspace/ai/chat",
            method: "POST",
            body: JSON.stringify({
                "message": userMsg,
                "mode": "chat", // chat: 对话模式，query: 问答模式， agent: 代理模式
                "sessionId": "8888" 
            }),
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer SEC082V-99D48HT-GB96EZ5-BS34AMS"
            },
            timeout: 120
        });

        // 解析返回结果
        const resData = res.json || {};
        const replyText = resData.textResponse || resData.content || resData.text || "AI 未能返回有效内容";

        return c.json(200, {
            "code": 200,
            "reply": replyText
        });

    } catch (err) {
        return c.json(500, { "message": "转发请求失败: " + err.message });
    }
});