/** Marketplace tools — search and install Forge extensions: connectors (tool
 *  bundles for GitLab/Jenkins/…), skills, and workflow templates. All in-process
 *  lib calls; each follows sync → list → install. Listing auto-syncs once if the
 *  local cache is empty. */

import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { listMarketplace as listConnectorMarket, syncRegistry, installFromRegistry } from '@/lib/connectors/sync';
import { listSkills, syncSkills, installGlobal } from '@/lib/skills';
import { listMarketplace as listWorkflowMarket, syncMarketplace, installFromMarketplace } from '@/lib/workflow-marketplace';
import { text, fail, guard, skillInstalled } from './_shared';

const KIND = ['connector', 'skill', 'workflow'] as const;

function filterBy(query: string | undefined, hay: string): boolean {
  return !query || hay.toLowerCase().includes(query.toLowerCase());
}

export function registerMarketplaceTools(server: McpServer): void {
  server.tool(
    'forge_marketplace_search',
    'Search the Forge marketplace for extensions to install. kind="connector" (external-system tool bundles), "skill" (agent skills), or "workflow" (pipeline templates). Auto-syncs the catalog once if needed.',
    {
      kind: z.enum(KIND).describe('What to search for'),
      query: z.string().optional().describe('Filter by name/description substring'),
    },
    (params) => guard(async () => {
      if (params.kind === 'connector') {
        let m = listConnectorMarket();
        if (!m.entries?.length) { await syncRegistry(); m = listConnectorMarket(); }
        const items = m.entries.filter((e) => filterBy(params.query, `${e.id} ${e.name} ${e.description || ''}`)).slice(0, 40);
        if (!items.length) return text('No matching connectors (catalog may need a sync, or none match).');
        return text(`Connectors:\n${items.map((e) => `• ${e.id} v${e.version}${e.installed_version ? ' (installed)' : ''} — ${e.description || e.name}`).join('\n')}\n\nInstall with forge_marketplace_install kind="connector" name="<id>".`);
      }
      if (params.kind === 'skill') {
        let s = listSkills();
        if (!s?.length) { await syncSkills(); s = listSkills(); }
        const items = s.filter((e) => filterBy(params.query, `${e.name} ${e.description || ''}`)).slice(0, 40);
        if (!items.length) return text('No matching skills.');
        return text(`Skills:\n${items.map((e) => `• ${e.name}${skillInstalled(e) ? ' (installed)' : ''} — ${e.description || ''}`).join('\n')}\n\nInstall with forge_marketplace_install kind="skill" name="<name>".`);
      }
      // workflow
      let w = listWorkflowMarket();
      if (!w.recipes?.length && !w.pipelines?.length) { await syncMarketplace(); w = listWorkflowMarket(); }
      const all = [
        ...(w.pipelines || []).map((e) => ({ ...e, _kind: 'pipeline' })),
        ...(w.recipes || []).map((e) => ({ ...e, _kind: 'recipe' })),
      ].filter((e) => filterBy(params.query, `${e.name} ${e.description || ''}`)).slice(0, 40);
      if (!all.length) return text('No matching workflow templates.');
      return text(`Workflow templates:\n${all.map((e) => `• [${e._kind}] ${e.name} — ${e.description || ''}`).join('\n')}\n\nInstall with forge_marketplace_install kind="workflow" name="<name>" workflow_kind="<pipeline|recipe>".`);
    }),
  );

  server.tool(
    'forge_marketplace_install',
    'Install a marketplace extension by kind and name (see forge_marketplace_search). For workflows, pass workflow_kind ("pipeline" or "recipe").',
    {
      kind: z.enum(KIND).describe('connector | skill | workflow'),
      name: z.string().describe('The id/name from forge_marketplace_search'),
      workflow_kind: z.enum(['pipeline', 'recipe']).optional().describe('For kind="workflow": which list it came from (default pipeline)'),
    },
    (params) => guard(async () => {
      if (params.kind === 'connector') {
        const r = await installFromRegistry(params.name);
        return r.ok ? text(`Installed connector ${params.name}${r.version ? ` v${r.version}` : ''}. Configure it in Settings → Connectors.`) : fail(`Install failed: ${r.error || 'unknown error'}`);
      }
      if (params.kind === 'skill') {
        await installGlobal(params.name); // throws on failure
        return text(`Installed skill "${params.name}" globally.`);
      }
      const r = await installFromMarketplace(params.workflow_kind || 'pipeline', params.name);
      return r.ok ? text(`Installed workflow "${params.name}". List it with forge_list_workflows.`) : fail(`Install failed: ${r.error || 'unknown error'}`);
    }),
  );
}
