/**
 * MCP Tool: generate_report
 *
 * Generate analytical reports on European Parliament data
 *
 * **Intelligence Perspective:** Produces structured intelligence products including MEP
 * activity scorecards, committee effectiveness assessments, voting pattern reports, and
 * legislative progress tracking aligned with intelligence analysis best practices.
 *
 * **Business Perspective:** Premium report generation capability enabling consulting
 * deliverables, automated briefings, and white-label reporting for enterprise customers.
 *
 * **Marketing Perspective:** Flagship feature demonstrating automated parliamentary
 * intelligence—key for content marketing, case studies, and product demonstrations.
 *
 * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
 */

import type { z } from 'zod';
import { GenerateReportSchema } from '../../schemas/europeanParliament.js';
import {
  generateMEPActivityReport,
  generateCommitteePerformanceReport,
  generateVotingStatisticsReport,
  generateLegislationProgressReport
} from './reportGenerators.js';
import type { Report, ReportType } from './types.js';
import type { ToolResult } from '../shared/types.js';
import { ToolError } from '../shared/errors.js';

/**
 * Report parameters type inferred from schema
 */
type ReportParams = z.infer<typeof GenerateReportSchema>;

/**
 * Report generator map for O(1) lookup
 */
const reportGenerators: Record<
  ReportType,
  (params: ReportParams) => Promise<Report>
> = {
  MEP_ACTIVITY: generateMEPActivityReport,
  COMMITTEE_PERFORMANCE: generateCommitteePerformanceReport,
  VOTING_STATISTICS: generateVotingStatisticsReport,
  LEGISLATION_PROGRESS: generateLegislationProgressReport
};

/**
 * Handles the generate_report MCP tool request.
 *
 * Generates structured analytical intelligence reports on European Parliament data.
 * Supports four report types: MEP activity scorecards, committee performance
 * assessments, voting statistics summaries, and legislation progress reports.
 * Delegates to a type-keyed generator map for O(1) dispatch.
 *
 * @param args - Raw tool arguments, validated against {@link GenerateReportSchema}
 * @returns MCP tool result containing a structured report with summary, sections,
 *   statistics, and recommendations appropriate to the requested report type
 * @throws {ZodError} If `args` fails schema validation (e.g., missing required fields or invalid format)
 * @throws {ToolError} If the European Parliament API is unreachable or returns an error response
 *
 * @example
 * ```typescript
 * const result = await handleGenerateReport({
 *   reportType: 'MEP_ACTIVITY',
 *   subjectId: 'MEP-124810',
 *   dateFrom: '2024-01-01',
 *   dateTo: '2024-12-31'
 * });
 * // Returns MEP activity scorecard with voting discipline, attendance,
 * // committee contributions, and performance recommendations
 * ```
 *
 * @security Input is validated with Zod before any API call.
 *   Personal data in responses is minimised per GDPR Article 5(1)(c).
 *   All requests are rate-limited and audit-logged per ISMS Policy AU-002.
 * @since 0.8.0
 * @see {@link generateReportToolMetadata} for MCP schema registration
 * @see {@link handleTrackLegislation} for per-procedure legislative progress tracking
 */
export async function handleGenerateReport(
  args: unknown
): Promise<ToolResult> {
  const params = GenerateReportSchema.parse(args);

  try {
    const generator = reportGenerators[params.reportType];
    const report = await generator(params);

    return {
      content: [{
        type: 'text',
        text: JSON.stringify(report, null, 2)
      }]
    };
  } catch (error: unknown) {
    if (error instanceof ToolError) {
      throw error;
    }
    throw new ToolError({
      toolName: 'generate_report',
      operation: 'generateReport',
      message: 'Failed to generate report',
      isRetryable: true,
      cause: error,
    });
  }
}

/**
 * Tool metadata for MCP registration
 */
export const generateReportToolMetadata = {
  name: 'generate_report',
  description: 'Generate comprehensive analytical reports on European Parliament data. Supports MEP activity reports, committee performance reports, voting statistics, and legislation progress reports. Returns structured report with summary, sections, statistics, and recommendations.',
  inputSchema: {
    type: 'object' as const,
    properties: {
      reportType: {
        type: 'string',
        description: 'Type of report to generate',
        enum: ['MEP_ACTIVITY', 'COMMITTEE_PERFORMANCE', 'VOTING_STATISTICS', 'LEGISLATION_PROGRESS']
      },
      subjectId: {
        type: 'string',
        description: 'Subject identifier (MEP ID, Committee ID, etc.) - optional for aggregate reports',
        minLength: 1,
        maxLength: 100
      },
      dateFrom: {
        type: 'string',
        description: 'Report period start date (YYYY-MM-DD format)',
        pattern: '^\\d{4}-\\d{2}-\\d{2}$'
      },
      dateTo: {
        type: 'string',
        description: 'Report period end date (YYYY-MM-DD format)',
        pattern: '^\\d{4}-\\d{2}-\\d{2}$'
      }
    },
    required: ['reportType']
  }
};
