import { z } from 'zod';
import type { CompositeToolDef } from '../../tool-registry.js';
import type { ApiClient } from '../../api-client.js';

async function handler(_args: Record<string, unknown>, api: ApiClient): Promise<string> {
  // Fetch campaign data and effectiveness metrics in parallel
  const [campaigns, effectiveness, emailQueue] = await Promise.allSettled([
    api.request('GET', '/api/campaigns', { limit: 50 }),
    api.request('GET', '/api/influence/effectiveness', {}),
    api.request('GET', '/api/email-queue/status'),
  ]);

  const sections: string[] = [];

  // Campaign overview
  if (campaigns.status === 'fulfilled') {
    const data = campaigns.value as any;
    const list = data.campaigns || data.data || [];
    const statusCounts: Record<string, number> = {};
    for (const c of list) {
      statusCounts[c.status] = (statusCounts[c.status] || 0) + 1;
    }
    sections.push(
      '## Campaign Overview\n' +
        `Total campaigns: ${list.length}\n` +
        `By status: ${JSON.stringify(statusCounts)}\n` +
        `\nCampaigns:\n${JSON.stringify(list.map((c: any) => ({
          id: c.id,
          title: c.title,
          status: c.status,
          emailCount: c._count?.emails || c.emailCount || 0,
          responseCount: c._count?.responses || c.responseCount || 0,
        })), null, 2)}`
    );
  } else {
    sections.push('## Campaign Overview\n(Failed to fetch)');
  }

  // Effectiveness analytics
  if (effectiveness.status === 'fulfilled') {
    sections.push('## Effectiveness Analytics\n' + JSON.stringify(effectiveness.value, null, 2));
  } else {
    sections.push('## Effectiveness Analytics\n(Not available — may need effectiveness module enabled)');
  }

  // Email delivery stats
  if (emailQueue.status === 'fulfilled') {
    sections.push('## Email Queue Status\n' + JSON.stringify(emailQueue.value, null, 2));
  } else {
    sections.push('## Email Queue Status\n(Failed to fetch)');
  }

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

export const outreachReport: CompositeToolDef = {
  name: 'outreach_report',
  description:
    'Generate a comprehensive outreach report: all campaigns with email/response counts, ' +
    'effectiveness analytics (response rates, geographic breakdown), and email queue status. ' +
    'Use this to assess campaign performance across the platform.',
  inputSchema: {},
  handler,
  tier: 3,
};
