const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
const DEBUG_IFLOW_WEB_SEARCH = (process.env.ROUTECODEX_DEBUG_IFLOW_WEB_SEARCH || '').trim() === '1';
/**
 * IFlow web_search 请求适配（作用于 openai-chat 兼容 payload）：
 *
 * - 仅在 routeId 以 `web_search` 或 `search` 开头时生效（来自 AdapterContext.routeId）；
 * - 读取顶层的 `web_search` helper 对象 `{ query, recency, count, engine }`；
 * - 当 query 为空或无效时：删除 helper，原样透传；
 * - 当 query 有效时：构造一个标准的 OpenAI function tool：
 *   - name 固定为 `web_search`；
 *   - parameters 包含 query/recency/count 三个字段；
 * - 将生成的 function tool 写入 `tools` 数组，并删除顶层 `web_search`。
 *
 * 注意：
 * - 顶层 `web_search` 只在 servertool 的二跳请求中出现，用于驱动后端搜索；
 * - 用户侧的工具调用仍然使用统一的 `web_search` function tool schema。
 */
export function applyIflowWebSearchRequestTransform(payload, adapterContext) {
    const routeId = typeof adapterContext?.routeId === 'string' ? adapterContext.routeId : '';
    const normalizedRoute = routeId.trim().toLowerCase();
    // Some hosts/configs use "search" as the route name for web search engines.
    // Treat both "web_search*" and "search*" as web-search routes.
    if (!normalizedRoute || (!normalizedRoute.startsWith('web_search') && !normalizedRoute.startsWith('search'))) {
        return 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 tool = {
        type: 'function',
        function: {
            name: 'web_search',
            description: 'Perform web search over the public internet and return up-to-date results.',
            parameters: {
                type: 'object',
                properties: {
                    query: {
                        type: 'string',
                        description: 'Search query string.'
                    },
                    recency: {
                        type: 'string',
                        description: 'Optional recency filter such as "day", "week", or "month".'
                    },
                    count: {
                        type: 'integer',
                        minimum: 1,
                        maximum: 50,
                        description: 'Maximum number of search results to retrieve (1-50).'
                    }
                },
                required: ['query']
            }
        }
    };
    root.tools = [tool];
    delete root.web_search;
    if (DEBUG_IFLOW_WEB_SEARCH) {
        try {
            // eslint-disable-next-line no-console
            console.log('\x1b[38;5;27m[compat][iflow_web_search_request] applied web_search transform ' +
                `query=${JSON.stringify(query).slice(0, 200)} ` +
                `recency=${String(recency ?? '')}\x1b[0m`);
        }
        catch {
            // logging best-effort
        }
    }
    return root;
}
