'use strict';

// Gateway-internal tools that should not be listed as available to Claude.
// These are OC infrastructure tools, not user-facing.
const GATEWAY_BLOCKED = new Set(['sessions_send', 'sessions_spawn', 'gateway']);

/**
 * Render a single OpenAI function-calling parameter schema into a compact,
 * human/Claude-readable signature plus per-arg notes.
 *
 * PATCHED for alvin-bot (2026-06-16): the upstream bridge only passed each
 * tool's name + description to Claude, dropping the JSON-Schema entirely. That
 * forced Claude to GUESS argument keys/types — unreliable for anything beyond
 * the obvious (path/command). We now surface the full parameter contract
 * (names, types, required-ness, descriptions, enums) so Claude emits
 * arguments that match what alvin-bot's tool-executor actually expects.
 */
function renderParams(fn) {
    const schema = fn.parameters || {};
    const props = schema.properties || {};
    const required = Array.isArray(schema.required) ? schema.required : [];
    const keys = Object.keys(props);
    if (keys.length === 0) {
        return { signature: '', notes: [] };
    }
    const sigParts = [];
    const notes = [];
    for (const k of keys) {
        const p = props[k] || {};
        const opt = required.includes(k) ? '' : '?';
        const type = p.type || 'any';
        sigParts.push(`${k}${opt}: ${type}`);
        const bits = [];
        if (p.description) bits.push(p.description);
        if (Array.isArray(p.enum)) bits.push(`one of: ${p.enum.join(', ')}`);
        if (bits.length > 0) notes.push(`    - ${k}: ${bits.join(' — ')}`);
    }
    return { signature: sigParts.join(', '), notes };
}

/**
 * Build tool instructions for the system prompt.
 *
 * In the new architecture, Claude does NOT execute tools.
 * Instead, it outputs <tool_call> blocks which we parse and return
 * to OpenClaw as standard OpenAI tool_calls.
 * OpenClaw executes the tools and sends results back.
 */
function buildToolInstructions(tools) {
    if (!tools || tools.length === 0) return '';

    const lines = [
        '',
        '---',
        '',
        '## Tool Calling Protocol',
        '',
        'You HAVE access to the tools listed below. They are live, real, and fully',
        'functional in this environment. An external orchestrator executes them for',
        'you and returns the real output. This is how you read files, run commands,',
        'search the web, etc.',
        '',
        'To use a tool, output EXACTLY this format and then STOP immediately:',
        '',
        '<tool_call>',
        '{"name": "tool_name", "arguments": {"key": "value"}}',
        '</tool_call>',
        '',
        'You may request multiple tools at once:',
        '',
        '<tool_call>',
        '{"name": "web_search", "arguments": {"query": "bitcoin price"}}',
        '</tool_call>',
        '<tool_call>',
        '{"name": "read_file", "arguments": {"path": "/etc/hosts"}}',
        '</tool_call>',
        '',
        'CRITICAL RULES — follow these exactly:',
        '- NEVER say a tool is "not available", that you "cannot access" a file/URL/',
        '  command, or ask the user to paste content. If a listed tool can get it,',
        '  CALL the tool instead. Claiming unavailability is always wrong here.',
        '- Do NOT execute tools yourself and do NOT use any native Claude Code tools',
        '  (Bash, Read, Write, Edit, WebSearch, WebFetch, Glob, Grep, Task). Use ONLY',
        '  the <tool_call> protocol above.',
        '- After emitting your <tool_call> block(s), STOP your response immediately.',
        '  Do NOT write "Here are the results", do NOT guess, invent, or fabricate the',
        '  tool output. The orchestrator runs the tool and gives you the REAL result',
        '  in the next turn — only then do you continue.',
        '- Put ALL arguments INSIDE the "arguments" object — never as top-level',
        '  keys. Correct: {"name":"python_execute","arguments":{"code":"..."}}.',
        '  Wrong: {"name":"python_execute","code":"..."}.',
        '- Use the EXACT argument names shown in each tool signature below. Include',
        '  every required argument (those without a "?").',
        '- "arguments" must be valid JSON: escape newlines in string values as \\n,',
        '  tabs as \\t and double-quotes as \\". Never put a raw line break inside a',
        '  JSON string.',
        '- If you genuinely need no tools, just answer directly.',
        '- The conversation may already contain tool results from previous turns —',
        '  use them, do not re-request the same call.',
        '',
        'Available tools:',
    ];

    for (const tool of tools) {
        const fn = tool.function || tool;
        const name = fn.name;
        if (!name) continue;
        if (GATEWAY_BLOCKED.has(name)) continue;
        const desc = fn.description || '';
        const { signature, notes } = renderParams(fn);
        lines.push(`- **${name}**(${signature}): ${desc}`);
        for (const note of notes) lines.push(note);
    }

    return lines.join('\n');
}

module.exports = { buildToolInstructions };
