import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { ApiClient } from './api-client.js';
import { ToolRegistry } from './tool-registry.js';

// Tier 1 core tools
import { dashboardTools } from './tools/dashboard.js';
import { campaignTools } from './tools/campaigns.js';
import { peopleTools } from './tools/people.js';
import { shiftTools } from './tools/shifts.js';
import { locationTools } from './tools/locations.js';
import { settingsTools } from './tools/settings.js';
import { registerMetaTools } from './tools/meta.js';

// Tier 2 packs
import { emailPack } from './tools/packs/email.js';
import { smsPack } from './tools/packs/sms.js';
import { paymentsPack } from './tools/packs/payments.js';
import { mediaPack } from './tools/packs/media.js';
import { adminPack } from './tools/packs/admin.js';
import { eventsPack } from './tools/packs/events.js';

// Tier 3 composite workflows
import { dailyBriefing } from './tools/composite/daily-briefing.js';
import { outreachReport } from './tools/composite/outreach-report.js';
import { volunteerSummary } from './tools/composite/volunteer-summary.js';

export interface ServerConfig {
  apiUrl: string;
  mediaApiUrl?: string;
  serviceEmail: string;
  servicePassword: string;
}

export async function createServer(config: ServerConfig) {
  // Initialize MCP server
  const server = new McpServer({
    name: 'changemaker-lite',
    version: '1.0.0',
  });

  // Initialize API client with JWT auth
  const apiClient = new ApiClient({
    baseUrl: config.apiUrl,
    email: config.serviceEmail,
    password: config.servicePassword,
  });

  // Login to get initial tokens
  try {
    await apiClient.login();
    console.error('[MCP] Authenticated with API successfully');
  } catch (err: any) {
    console.error(`[MCP] Failed to authenticate: ${err.message}`);
    console.error('[MCP] Server will start but API calls will fail until auth succeeds');
  }

  // Initialize tool registry
  const registry = new ToolRegistry(server, apiClient);

  // Register Tier 1 core tools (~25 tools, always available)
  registry.registerTools(dashboardTools);
  registry.registerTools(campaignTools);
  registry.registerTools(peopleTools);
  registry.registerTools(shiftTools);
  registry.registerTools(locationTools);
  registry.registerTools(settingsTools);

  // Register Tier 3 composite workflows (always available)
  registry.registerTools([dailyBriefing, outreachReport, volunteerSummary]);

  // Register meta tools (list_tool_packs, enable_tool_pack)
  registerMetaTools(server, registry);

  // Register Tier 2 packs (available on demand via enable_tool_pack)
  registry.registerPack(emailPack);
  registry.registerPack(smsPack);
  registry.registerPack(paymentsPack);
  registry.registerPack(mediaPack);
  registry.registerPack(adminPack);
  registry.registerPack(eventsPack);

  console.error('[MCP] Server initialized with core tools + 6 on-demand packs');

  return server;
}
