#!/usr/bin/env node
'use strict';

// Optional stdio adapter for clients that launch local MCP processes.
// Node.js 20+; no npm packages required. Credentials are read only from environment.
const readline = require('node:readline');

function createAdapter({ endpoint, token, fetchImpl = fetch, write = line => process.stdout.write(line + '\n') }) {
    const url = new URL(endpoint);
    if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname))) throw new Error('SELLIX_MCP_URL must use HTTPS (HTTP is allowed only on loopback).');
    if (!token) throw new Error('SELLIX_API_KEY is required.');
    let protocol = '2025-11-25';
    return async function forward(line) {
        let message;
        try {
            message = JSON.parse(line);
            const modern = message.params?._meta?.['io.modelcontextprotocol/protocolVersion'];
            const headers = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${token}`, 'MCP-Protocol-Version': modern || protocol };
            if (modern) {
                headers['Mcp-Method'] = message.method;
                const name = message.params?.name ?? message.params?.uri;
                if (name !== undefined) headers['Mcp-Name'] = name;
            }
            const response = await fetchImpl(url, { method: 'POST', headers, body: line, redirect: 'error', signal: AbortSignal.timeout(120000) });
            if (response.status === 202) return;
            const reply = await response.json();
            if (reply.jsonrpc !== '2.0') throw new Error(reply.error?.message || `MCP HTTP error ${response.status}.`);
            if (message.method === 'initialize' && reply.result?.protocolVersion) protocol = reply.result.protocolVersion;
            write(JSON.stringify(reply));
        } catch (error) {
            if (message && Object.hasOwn(message, 'id')) write(JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { code: -32000, message: error.message.replaceAll(token, '[redacted]') } }));
            else if (!message) write(JSON.stringify({ jsonrpc: '2.0', error: { code: -32700, message: 'Invalid JSON input.' } }));
        }
    };
}

module.exports = { createAdapter };
if (require.main === module) {
    try {
        const forward = createAdapter({ endpoint: process.env.SELLIX_MCP_URL || 'https://api.sellix.gg/mcp', token: process.env.SELLIX_API_KEY });
        const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
        // Preserve message order without writing anything except JSON-RPC to stdout.
        let pending = Promise.resolve();
        input.on('line', line => { if (line.trim()) pending = pending.then(() => forward(line)); });
    } catch (error) {
        process.stderr.write(error.message + '\n');
        process.exitCode = 1;
    }
}
