const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
const DEBUG_GLM_WEB_SEARCH = (process.env.ROUTECODEX_DEBUG_GLM_WEB_SEARCH || '').trim() === '1';
export function applyGlmWebSearchRequestTransform(payload) {
    const root = structuredClone(payload);
    const webSearchRaw = root.web_search;
    if (!isRecord(webSearchRaw)) {
        return root;
    }
    const webSearch = webSearchRaw;
    const queryValue = webSearch.query;
    const recencyValue = webSearch.recency;
    const countValue = webSearch.count;
    const query = typeof queryValue === 'string' ? queryValue.trim() : '';
    const recency = typeof recencyValue === 'string' ? recencyValue.trim() : undefined;
    let count;
    if (typeof countValue === 'number' && Number.isFinite(countValue)) {
        const normalized = Math.floor(countValue);
        if (normalized >= 1 && normalized <= 50) {
            count = normalized;
        }
    }
    if (!query) {
        // No meaningful search query, drop the helper object and passthrough.
        delete root.web_search;
        return root;
    }
    const webSearchConfig = {
        // 按 GLM 文档要求：search_engine 为必填，默认使用 search_std。
        search_engine: 'search_std',
        enable: true,
        search_query: query,
        // 返回搜索结果详情，便于我们在响应中提取摘要或调试。
        search_result: true
    };
    if (recency) {
        webSearchConfig.search_recency_filter = recency;
    }
    if (typeof count === 'number') {
        webSearchConfig.count = count;
    }
    // 根据 OpenAPI：tools.anyOf[*] = WebSearchToolSchema[]，即一次只能选择一种工具类型。
    // 在 web_search 路由下，我们只保留 WebSearchToolSchema，丢弃其它 function/retrieval/MCP 工具，
    // 避免混用导致后端忽略 web_search 配置。
    const baseTool = {
        type: 'web_search',
        web_search: webSearchConfig
    };
    root.tools = [baseTool];
    delete root.web_search;
    if (DEBUG_GLM_WEB_SEARCH) {
        try {
            // eslint-disable-next-line no-console
            console.log('\x1b[38;5;27m[compat][glm_web_search_request] applied web_search transform ' +
                `search_engine=${String(baseTool?.web_search?.search_engine ?? 'search_std')} ` +
                `query=${JSON.stringify(query).slice(0, 200)} ` +
                `count=${String(count ?? '')}\x1b[0m`);
        }
        catch {
            // logging best-effort
        }
    }
    return root;
}
