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> {
  // Fire multiple requests in parallel for speed
  const [summary, connectivity, shifts, events, activity] = await Promise.allSettled([
    api.request('GET', '/api/dashboard/summary'),
    api.request('GET', '/api/dashboard/connectivity'),
    api.request('GET', '/api/dashboard/upcoming-shifts'),
    api.request('GET', '/api/ticketed-events/admin', { status: 'PUBLISHED', limit: 5 }),
    api.request('GET', '/api/dashboard/activity', { limit: 10 }),
  ]);

  const sections: string[] = [];

  // Platform summary
  if (summary.status === 'fulfilled') {
    sections.push('## Platform Summary\n' + JSON.stringify(summary.value, null, 2));
  } else {
    sections.push('## Platform Summary\n(Failed to fetch)');
  }

  // Service health
  if (connectivity.status === 'fulfilled') {
    sections.push('## Service Health\n' + JSON.stringify(connectivity.value, null, 2));
  } else {
    sections.push('## Service Health\n(Failed to fetch)');
  }

  // Upcoming shifts
  if (shifts.status === 'fulfilled') {
    sections.push('## Upcoming Shifts\n' + JSON.stringify(shifts.value, null, 2));
  } else {
    sections.push('## Upcoming Shifts\n(Failed to fetch)');
  }

  // Upcoming ticketed events
  if (events.status === 'fulfilled') {
    sections.push('## Upcoming Ticketed Events\n' + JSON.stringify(events.value, null, 2));
  } else {
    sections.push('## Upcoming Ticketed Events\n(Failed to fetch)');
  }

  // Recent activity
  if (activity.status === 'fulfilled') {
    sections.push('## Recent Activity\n' + JSON.stringify(activity.value, null, 2));
  } else {
    sections.push('## Recent Activity\n(Failed to fetch)');
  }

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

export const dailyBriefing: CompositeToolDef = {
  name: 'daily_briefing',
  description:
    'Get a comprehensive daily briefing: platform summary (campaign/user/location counts), ' +
    'service health checks, upcoming volunteer shifts, upcoming ticketed events, and recent activity feed. ' +
    'Use this as the first call to understand the current state of everything.',
  inputSchema: {},
  handler,
  tier: 3,
};
