// ============================================================
// SPARDA ROUTER — Auto-generated. DO NOT EDIT.
// Regenerate: npx sparda-mcp init   •   Remove: npx sparda-mcp remove
// ============================================================
__IMPORT_LINE__

const SPARDA_TOOLS = __TOOLS_JSON__;

const SPARDA_LOCAL_KEY = "__LOCAL_KEY__";
const SPARDA_PORT = __PORT__;

__ROUTER_DECL__

spardaRouter.use((req, res, next) => {
  if (req.headers['x-sparda-key'] !== SPARDA_LOCAL_KEY) {
    return res.status(401).json({ error: 'unauthorized' });
  }
  next();
});

spardaRouter.get('/tools', (_req, res) => res.json(SPARDA_TOOLS));

spardaRouter.post('/invoke', __JSON_MW__, async (req, res) => {
  const { tool, args = {} } = req.body ?? {};
  const spec = SPARDA_TOOLS[tool];
  if (!spec) return res.status(404).json({ error: `unknown tool: ${tool}` });
  if (!spec.enabled) {
    return res.status(403).json({ error: `tool disabled (write-safety): ${tool}`, hint: 'Enable it in sparda.json, then re-run: npx sparda-mcp init' });
  }
  if (spec.path.startsWith('/mcp')) {
    return res.status(400).json({ error: 'self-referential tool blocked (loop protection)' });
  }
  try {
    let url = spec.path.replace(/:(\w+)/g, (_, name) => {
      const v = args[name];
      if (v === undefined) throw Object.assign(new Error(`missing path param: ${name}`), { status: 400 });
      return encodeURIComponent(String(v));
    });
    const query = [];
    for (const [k, v] of Object.entries(args)) {
      if (k === 'body' || spec.pathParams.includes(k) || v === undefined) continue;
      query.push(`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
    }
    if (query.length) url += `?${query.join('&')}`;

    const init = { method: spec.method, headers: {} };
    if (spec.method !== 'GET' && args.body !== undefined) {
      init.headers['content-type'] = 'application/json';
      init.body = JSON.stringify(args.body);
    }
    const upstream = await fetch(`http://127.0.0.1:${SPARDA_PORT}${url}`, { ...init, signal: AbortSignal.timeout(30_000) });
    const text = await upstream.text();
    let data; try { data = JSON.parse(text); } catch { data = text; }
    return res.status(200).json({ upstreamStatus: upstream.status, data });
  } catch (err) {
    return res.status(err.status ?? 502).json({ error: err.message });
  }
});
