// ==============================================================================
// 模块: BAI 业务审计子系统 (v1.8 完整功能稳态版)
// ==============================================================================

routerAdd("GET", "/bai-ai-manage", (c) => {
    try {
        const html = $template.loadFiles(__hooks + "/bai_chat_alm_hooks/views/ai-manage-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 (err) {
        return c.json(500, { message: "HTML 模板渲染失败: " + err.message });
    }
});

// 1. 获取用户列表
routerAdd("GET", "/pb-api-v1/audit/users", (c) => {
    try {
        const info = c.requestInfo();
        const days = parseInt(info.query["days"] || "0");
        
        // 保持原有的时间过滤逻辑
        let timeClause = (days > 0) ? `AND c.createdAt > ${new Date().getTime() - (days * 24 * 60 * 1000)}` : "";

        // 【核心修正】SQL 采用 LEFT JOIN 确保 thread_id 为空的 API 对话不被漏掉
        // 注意：这里去掉了可能引起语法错误的注释，使用了探针兼容的 SQL
        const sql = `
            SELECT 
                COALESCE(t.slug, t.name, 'API_USER') as phone, 
                COUNT(c.id) as chat_count, 
                MAX(c.createdAt) as last_active 
            FROM workspace_chats c 
            LEFT JOIN workspace_threads t ON c.thread_id = t.id 
            WHERE 1=1 ${timeClause}
            GROUP BY phone 
            ORDER BY last_active DESC
        `;

        // 保持对 3010 探针的调用
        const res = $http.send({ 
            url: "http://bai-alm-audit-api:3010/api/v1/audit/query", 
            method: "POST", 
            body: JSON.stringify({ "sql": sql, "params": [] }), 
            headers: { "Content-Type": "application/json" } 
        });

        // 保持原有的 PB 用户姓名映射逻辑
        let phoneToNameMap = {};
        const pbRecords = $app.findAllRecords("tbl_auth_users");
        pbRecords.forEach(r => { 
            phoneToNameMap[r.getString("users_phone")] = r.getString("users_name"); 
        });

        const data = (res.json.data || []).map(u => ({ 
            ...u, 
            name: phoneToNameMap[u.phone] || (u.phone === 'API_USER' ? '微信测试用户' : "") 
        }));

        return c.json(200, { code: 200, data });
    } catch (err) { 
        return c.json(500, { message: "Users API Error: " + err.message }); 
    }
});

// 2. 获取流水记录
routerAdd("GET", "/pb-api-v1/audit/chat-list", (c) => {
    try {
        const info = c.requestInfo();
        const phone = info.query["phone"];
        const page = parseInt(info.query["page"] || "1");
        const days = parseInt(info.query["days"] || "0");
        const offset = (page - 1) * 50;

        let timeClause = (days > 0) ? `AND c.createdAt > ${new Date().getTime() - (days * 24 * 60 * 60 * 1000)}` : "";

        // 【核心修正】针对 API_USER 的特殊查询逻辑
        let whereClause = "";
        if (phone === "API_USER") {
            whereClause = `WHERE c.thread_id IS NULL`;
        } else {
            whereClause = `WHERE t.slug = '${phone}' OR t.name = '${phone}'`;
        }

        const sql = `
            SELECT c.id, w.name AS workspace_name, c.prompt, c.response, c.createdAt 
            FROM workspace_chats c 
            LEFT JOIN workspace_threads t ON c.thread_id = t.id 
            LEFT JOIN workspaces w ON c.workspaceId = w.id 
            ${whereClause} ${timeClause} 
            ORDER BY c.createdAt DESC 
            LIMIT 50 OFFSET ${offset}
        `;

        const res = $http.send({ 
            url: "http://bai-alm-audit-api:3010/api/v1/audit/query", 
            method: "POST", 
            body: JSON.stringify({ "sql": sql, "params": [] }), 
            headers: { "Content-Type": "application/json" } 
        });

        return c.json(200, { code: 200, data: res.json.data || [] });
    } catch (err) { 
        return c.json(500, { message: "Chat List Error: " + err.message }); 
    }
});

// 3. 全量导出保持不变
routerAdd("GET", "/pb-api-v1/audit/export-all", (c) => {
    try {
        const info = c.requestInfo();
        const phone = info.query["phone"];
        let whereClause = (phone === "API_USER") ? "WHERE c.thread_id IS NULL" : `WHERE t.slug = '${phone}' OR t.name = '${phone}'`;
        
        const sql = `SELECT c.*, w.name AS workspace_name FROM workspace_chats c LEFT JOIN workspace_threads t ON c.thread_id = t.id LEFT JOIN workspaces w ON c.workspaceId = w.id ${whereClause} ORDER BY c.createdAt DESC;`;
        const res = $http.send({ url: "http://bai-alm-audit-api:3010/api/v1/audit/query", method: "POST", body: JSON.stringify({ "sql": sql, "params": [] }), headers: { "Content-Type": "application/json" } });
        return c.json(200, { code: 200, data: res.json.data || [] });
    } catch (err) { return c.json(500, { message: err.message }); }
});