// ==============================================================================
// 模块: BAI SQL 实验室 (底层探勘工具) - 拆分独立版
// 路由: /bai-ai-sql-lab
// 注意: 绝不能引入 dynamic_model，防止引擎崩溃
// ==============================================================================

// 1. 页面 UI 挂载 (路径更新为 views 目录)
routerAdd("GET", "/bai-ai-sql-lab", (c) => {
    try {
        const html = $template.loadFiles(__hooks + "/bai_chat_alm_hooks/views/sql-lab-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, { "error": "Template Error: " + err.message });
    }
});

// 2. 全链路体检探针 (保持原样，属于 SQL Lab 的基础能力)
routerAdd("GET", "/pb-api-v1/diagnostics", (c) => {
    let report = { pb_status: "PocketBase OK", py_network: "WAIT", sqlite_storage: "WAIT", sqlite_version: "" };
    try {
        const res1 = $http.send({ url: "http://bai-alm-audit-api:3010/api/v1/audit/py-alive-check", method: "GET", timeout: 5 });
        report.py_network = res1.statusCode === 200 ? "ALIVE" : "ERROR";

        const res2 = $http.send({ url: "http://bai-alm-audit-api:3010/api/v1/audit/sqlite-read-check", method: "GET", timeout: 5 });
        report.sqlite_storage = res2.statusCode === 200 ? "READY" : "ERROR";
        
        if (res2.statusCode === 200 && res2.json.message) {
            const match = res2.json.message.match(/版本:\s*([\d\.]+)/);
            report.sqlite_version = match ? match[1] : "未知";
            report.sqlite_detail = res2.json.message;
        } else {
            report.sqlite_detail = res2.raw;
        }

        return c.json(200, report);
    } catch (err) {
        report.py_network = "ERROR";
        report.sqlite_storage = "ERROR";
        report.sqlite_detail = err.message;
        return c.json(500, report);
    }
});

// 3. 万能 SQL 执行透传通道 (彻底修复 Body 读取方式)
routerAdd("POST", "/pb-api-v1/sql-ops", (c) => {
    try {
        // PB v0.23+ 官方推荐的无依赖 Body 读取方式
        const reqBody = c.requestInfo().body;
        const sqlStatement = reqBody.sql || "";

        if (!sqlStatement) {
            return c.json(400, { "message": "SQL 指令不能为空" });
        }

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

        if (res.statusCode !== 200) {
            return c.json(res.statusCode, { 
                code: res.statusCode, 
                message: res.json?.detail || res.raw || "探针层执行报错" 
            });
        }

        return c.json(200, { code: 200, data: res.json.data || [] });
    } catch (err) {
        return c.json(500, { code: 500, message: "PB穿透异常: " + err.message });
    }
});