/**
 * Analytics & Insights Tools (Tier 1 - Core)
 * All tools are read-only and provide performance metrics from Meta Marketing API
 */

import { z } from "zod";
import type { ToolRegistry } from "../server.js";
import type {
  InsightRow,
  DatePreset,
  InsightBreakdown,
} from "../types/meta-api.js";

// ============================================================
// Shared Schemas
// ============================================================

const datePresetSchema = z
  .enum([
    "today",
    "yesterday",
    "this_month",
    "last_month",
    "this_quarter",
    "maximum",
    "last_3d",
    "last_7d",
    "last_14d",
    "last_28d",
    "last_30d",
    "last_90d",
    "last_week_mon_sun",
    "last_week_sun_sat",
    "last_quarter",
    "last_year",
    "this_week_mon_today",
    "this_week_sun_today",
    "this_year",
  ])
  .describe("Preset date range for insights");

const timeRangeSchema = z
  .object({
    since: z.string().describe("Start date (YYYY-MM-DD format)"),
    until: z.string().describe("End date (YYYY-MM-DD format)"),
  })
  .describe("Custom date range");

const breakdownSchema = z
  .array(
    z.enum([
      "age",
      "gender",
      "country",
      "region",
      "dma",
      "impression_device",
      "platform_position",
      "publisher_platform",
      "device_platform",
      "product_id",
      "frequency_value",
      "hourly_stats_aggregated_by_advertiser_time_zone",
      "hourly_stats_aggregated_by_audience_time_zone",
      "place_page_id",
    ])
  )
  .optional()
  .describe("Breakdown dimensions for insights");

const fieldsSchema = z
  .string()
  .optional()
  .describe(
    "Comma-separated list of insight fields (default: impressions,clicks,spend,reach,ctr,cpm,cpc,actions)"
  );

const objectTypeSchema = z
  .enum(["account", "campaign", "adset", "ad"])
  .describe("Type of ad object");

const attributionWindowSchema = z
  .array(
    z.enum([
      "1d_click",
      "7d_click",
      "28d_click",
      "1d_view",
      "7d_view",
      "28d_view",
      "default",
    ])
  )
  .describe("Attribution window settings to compare");

// ============================================================
// Helper Functions
// ============================================================

/**
 * Build insight parameters for API call
 */
function buildInsightParams(params: {
  date_preset?: DatePreset;
  time_range?: { since: string; until: string };
  fields?: string | string[];
  breakdowns?: InsightBreakdown[];
  level?: string;
}): Record<string, string> {
  const fieldsValue = params.fields 
    ? (Array.isArray(params.fields) ? params.fields.join(',') : params.fields)
    : "impressions,clicks,spend,reach,ctr,cpm,cpc,actions";
  
  const apiParams: Record<string, string> = {
    fields: fieldsValue,
  };

  if (params.date_preset) {
    apiParams.date_preset = params.date_preset;
  } else if (params.time_range) {
    apiParams.time_range = JSON.stringify(params.time_range);
  }

  if (params.breakdowns && params.breakdowns.length > 0) {
    apiParams.breakdowns = params.breakdowns.join(",");
  }

  if (params.level) {
    apiParams.level = params.level;
  }

  return apiParams;
}

/**
 * Calculate derived metrics from insight data
 */
function calculateDerivedMetrics(insight: InsightRow): Record<string, unknown> {
  const derived: Record<string, unknown> = {};

  const spend = parseFloat(insight.spend || "0");
  const clicks = parseInt(insight.clicks || "0", 10);
  const impressions = parseInt(insight.impressions || "0", 10);

  // Calculate CPA for each action type
  if (insight.actions && spend > 0) {
    derived.cost_per_action = insight.actions.map((action) => ({
      action_type: action.action_type,
      value: spend / parseFloat(action.value),
    }));
  }

  // Calculate ROAS from purchase values
  if (insight.action_values && spend > 0) {
    const purchaseValue = insight.action_values.find((av) =>
      av.action_type.includes("purchase")
    );
    if (purchaseValue) {
      derived.roas = parseFloat(purchaseValue.value) / spend;
    }
  }

  // Calculate effective CPM if not provided
  if (!insight.cpm && spend > 0 && impressions > 0) {
    derived.calculated_cpm = (spend / impressions) * 1000;
  }

  // Calculate effective CPC if not provided
  if (!insight.cpc && spend > 0 && clicks > 0) {
    derived.calculated_cpc = spend / clicks;
  }

  // Calculate effective CTR if not provided
  if (!insight.ctr && clicks > 0 && impressions > 0) {
    derived.calculated_ctr = (clicks / impressions) * 100;
  }

  return derived;
}

/**
 * Format insight response with calculated metrics
 */
function formatInsightResponse(insights: InsightRow[]): unknown[] {
  return insights.map((insight) => ({
    ...insight,
    derived_metrics: calculateDerivedMetrics(insight),
  }));
}

// ============================================================
// Tool Registration
// ============================================================

export function registerAnalyticsTools(registry: ToolRegistry): void {
  const client = registry.getClient();

  // ============================================================
  // get_account_insights
  // ============================================================
  registry.registerTool({
    name: "get_account_insights",
    description: "Retrieve account-level performance metrics and insights",
    inputSchema: z.object({
      account_id: z
        .string()
        .describe("Ad account ID (with or without act_ prefix)"),
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
      fields: fieldsSchema,
      breakdowns: breakdownSchema,
    }),
    annotations: {
      title: "Get Account Insights",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        account_id: string;
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
        fields?: string[];
        breakdowns?: InsightBreakdown[];
      };
      const accountId = params.account_id.startsWith("act_")
        ? params.account_id
        : `act_${params.account_id}`;

      const insightParams = buildInsightParams({
        date_preset: params.date_preset,
        time_range: params.time_range,
        fields: params.fields,
        breakdowns: params.breakdowns,
        level: "account",
      });

      const response = await client.get<{ data: InsightRow[] }>(
        `${accountId}/insights`,
        insightParams as Record<string, unknown>
      );

      const result = {
        insights: formatInsightResponse(response.data),
        account_id: accountId,
        date_range: (params.date_preset || JSON.stringify(params.time_range)) as string,
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });

  // ============================================================
  // get_campaign_insights
  // ============================================================
  registry.registerTool({
    name: "get_campaign_insights",
    description: "Retrieve campaign-level performance metrics",
    inputSchema: z.object({
      campaign_id: z.string().describe("Campaign ID"),
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
      fields: fieldsSchema,
      breakdowns: breakdownSchema,
    }),
    annotations: {
      title: "Get Campaign Insights",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        campaign_id: string;
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
        fields?: string[];
        breakdowns?: InsightBreakdown[];
      };
      const insightParams = buildInsightParams({
        date_preset: params.date_preset,
        time_range: params.time_range,
        fields: params.fields,
        breakdowns: params.breakdowns,
      });

      const response = await client.get<{ data: InsightRow[] }>(
        `${params.campaign_id}/insights`,
        insightParams as Record<string, unknown>
      );

      const result = {
        insights: formatInsightResponse(response.data),
        campaign_id: params.campaign_id,
        date_range: (params.date_preset || JSON.stringify(params.time_range)) as string,
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });

  // ============================================================
  // get_adset_insights
  // ============================================================
  registry.registerTool({
    name: "get_adset_insights",
    description: "Retrieve ad set-level performance metrics",
    inputSchema: z.object({
      adset_id: z.string().describe("Ad set ID"),
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
      fields: fieldsSchema,
      breakdowns: breakdownSchema,
    }),
    annotations: {
      title: "Get Ad Set Insights",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        adset_id: string;
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
        fields?: string[];
        breakdowns?: InsightBreakdown[];
      };
      const insightParams = buildInsightParams({
        date_preset: params.date_preset,
        time_range: params.time_range,
        fields: params.fields,
        breakdowns: params.breakdowns,
      });

      const response = await client.get<{ data: InsightRow[] }>(
        `${params.adset_id}/insights`,
        insightParams as Record<string, unknown>
      );

      const result = {
        insights: formatInsightResponse(response.data),
        adset_id: params.adset_id,
        date_range: (params.date_preset || JSON.stringify(params.time_range)) as string,
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });

  // ============================================================
  // get_ad_insights
  // ============================================================
  registry.registerTool({
    name: "get_ad_insights",
    description: "Retrieve individual ad-level performance metrics",
    inputSchema: z.object({
      ad_id: z.string().describe("Ad ID"),
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
      fields: fieldsSchema,
      breakdowns: breakdownSchema,
    }),
    annotations: {
      title: "Get Ad Insights",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        ad_id: string;
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
        fields?: string[];
        breakdowns?: InsightBreakdown[];
      };

      const insightParams = buildInsightParams({
        date_preset: params.date_preset,
        time_range: params.time_range,
        fields: params.fields,
        breakdowns: params.breakdowns,
      });

      const response = await client.get<{ data: InsightRow[] }>(
        `${params.ad_id}/insights`,
        insightParams as Record<string, unknown>
      );

      const result = {
        insights: formatInsightResponse(response.data),
        ad_id: params.ad_id,
        date_range: params.date_preset || params.time_range,
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });

  // ============================================================
  // get_breakdown
  // ============================================================
  registry.registerTool({
    name: "get_breakdown",
    description: "Flexible breakdown query for any object type with demographic, placement, or device breakdowns",
    inputSchema: z.object({
      object_id: z.string().describe("ID of the object to analyze"),
      object_type: objectTypeSchema,
      breakdowns: z
        .array(
          z.enum([
            "age",
            "gender",
            "country",
            "region",
            "dma",
            "impression_device",
            "platform_position",
            "publisher_platform",
            "device_platform",
            "hourly_stats_aggregated_by_advertiser_time_zone",
            "place_page_id",
          ])
        )
        .describe("Breakdown dimensions to analyze"),
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
      fields: fieldsSchema,
    }),
    annotations: {
      title: "Get Breakdown Analysis",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        object_id: string;
        object_type: string;
        breakdowns: string[];
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
        fields?: string[];
      };

      const insightParams = buildInsightParams({
        date_preset: params.date_preset,
        time_range: params.time_range,
        fields: params.fields,
        breakdowns: params.breakdowns as InsightBreakdown[],
      });

      const response = await client.get<{ data: InsightRow[] }>(
        `${params.object_id}/insights`,
        insightParams as Record<string, unknown>
      );

      const result = {
        insights: formatInsightResponse(response.data),
        object_id: params.object_id,
        object_type: params.object_type,
        breakdowns: params.breakdowns,
        date_range: params.date_preset || params.time_range,
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });

  // ============================================================
  // get_daily_trend
  // ============================================================
  registry.registerTool({
    name: "get_daily_trend",
    description: "Get day-by-day time series data for any object",
    inputSchema: z.object({
      object_id: z.string().describe("ID of the object to analyze"),
      object_type: objectTypeSchema,
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
      fields: fieldsSchema,
    }),
    annotations: {
      title: "Get Daily Trend",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        object_id: string;
        object_type: string;
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
        fields?: string[];
      };

      const insightParams = buildInsightParams({
        date_preset: params.date_preset,
        time_range: params.time_range,
        fields: params.fields,
      });

      // Add time_increment=1 for daily breakdown
      insightParams.time_increment = "1";

      const response = await client.get<{ data: InsightRow[] }>(
        `${params.object_id}/insights`,
        insightParams as Record<string, unknown>
      );

      // Format as time series
      const timeSeries = response.data.map((row: InsightRow) => ({
        date: row.date_start,
        metrics: {
          impressions: parseInt(row.impressions || "0", 10),
          clicks: parseInt(row.clicks || "0", 10),
          spend: parseFloat(row.spend || "0"),
          reach: parseInt(row.reach || "0", 10),
          ctr: parseFloat(row.ctr || "0"),
          cpm: parseFloat(row.cpm || "0"),
          cpc: parseFloat(row.cpc || "0"),
        },
        derived_metrics: calculateDerivedMetrics(row),
      }));

      const result = {
        time_series: timeSeries,
        object_id: params.object_id,
        object_type: params.object_type,
        date_range: params.date_preset || params.time_range,
        total_days: timeSeries.length,
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });

  // ============================================================
  // compare_objects
  // ============================================================
  registry.registerTool({
    name: "compare_objects",
    description: "Side-by-side comparison of multiple campaigns, ad sets, or ads",
    inputSchema: z.object({
      object_ids: z
        .array(z.string())
        .describe("Array of object IDs to compare"),
      object_type: objectTypeSchema,
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
      fields: fieldsSchema,
    }),
    annotations: {
      title: "Compare Objects",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        object_ids: string[];
        object_type: string;
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
        fields?: string[];
      };

      const insightParams = buildInsightParams({
        date_preset: params.date_preset,
        time_range: params.time_range,
        fields: params.fields,
      });

      // Fetch insights for all objects in parallel
      const insightPromises = params.object_ids.map((objectId: string) =>
        client
          .get<{ data: InsightRow[] }>(`${objectId}/insights`, insightParams as Record<string, unknown>)
          .then((response) => ({
            object_id: objectId,
            insights: response.data,
          }))
      );

      const results = await Promise.all(insightPromises);

      // Format comparison table
      const comparison = results.map((result: { object_id: string; insights: InsightRow[] }) => {
        const insight = result.insights[0] || ({} as InsightRow);
        return {
          object_id: result.object_id,
          name:
            insight.campaign_name ||
            insight.adset_name ||
            insight.ad_name ||
            "Unknown",
          metrics: {
            impressions: parseInt(insight.impressions || "0", 10),
            clicks: parseInt(insight.clicks || "0", 10),
            spend: parseFloat(insight.spend || "0"),
            reach: parseInt(insight.reach || "0", 10),
            ctr: parseFloat(insight.ctr || "0"),
            cpm: parseFloat(insight.cpm || "0"),
            cpc: parseFloat(insight.cpc || "0"),
          },
          derived_metrics: calculateDerivedMetrics(insight),
        };
      });

      // Calculate best performers
      const bestCtr = [...comparison].sort(
        (a, b) => b.metrics.ctr - a.metrics.ctr
      )[0];
      const bestCpc = [...comparison].sort(
        (a, b) => a.metrics.cpc - b.metrics.cpc
      )[0];
      const lowestCost = [...comparison].sort(
        (a, b) => a.metrics.spend - b.metrics.spend
      )[0];

      const result = {
        comparison,
        object_type: params.object_type,
        date_range: params.date_preset || params.time_range,
        summary: {
          best_ctr: bestCtr?.object_id,
          best_cpc: bestCpc?.object_id,
          lowest_spend: lowestCost?.object_id,
        },
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });

  // ============================================================
  // get_conversion_data
  // ============================================================
  registry.registerTool({
    name: "get_conversion_data",
    description: "Get detailed conversion events breakdown with ROAS and cost per action",
    inputSchema: z.object({
      object_id: z.string().describe("ID of the object to analyze"),
      object_type: objectTypeSchema,
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
    }),
    annotations: {
      title: "Get Conversion Data",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        object_id: string;
        object_type: string;
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
      };

      const insightParams = buildInsightParams({
        date_preset: params.date_preset,
        time_range: params.time_range,
        fields:
          "actions,action_values,cost_per_action_type,conversions,conversion_values,purchase_roas,website_purchase_roas,spend",
      });

      const response = await client.get<{ data: InsightRow[] }>(
        `${params.object_id}/insights`,
        insightParams as Record<string, unknown>
      );

      const insight = response.data[0] || ({} as InsightRow);

      // Format conversion data
      const conversions = (insight.actions || []).map((action: { action_type: string; value: string }) => {
        const actionValue = (insight.action_values || []).find(
          (av: { action_type: string; value: string }) => av.action_type === action.action_type
        );
        const costPerAction = (insight.cost_per_action_type || []).find(
          (cpa: { action_type: string; value: string }) => cpa.action_type === action.action_type
        );

        return {
          action_type: action.action_type,
          count: parseInt(action.value, 10),
          value: actionValue ? parseFloat(actionValue.value) : null,
          cost_per_action: costPerAction
            ? parseFloat(costPerAction.value)
            : null,
        };
      });

      // Calculate overall ROAS
      const totalSpend = parseFloat(insight.spend || "0");
      const totalValue = conversions.reduce(
        (sum: number, conv: { value: number | null }) => sum + (conv.value || 0),
        0
      );
      const overallRoas = totalSpend > 0 ? totalValue / totalSpend : 0;

      const result = {
        conversions,
        object_id: params.object_id,
        object_type: params.object_type,
        date_range: params.date_preset || params.time_range,
        summary: {
          total_conversions: conversions.reduce(
            (sum: number, conv: { count: number }) => sum + conv.count,
            0
          ),
          total_value: totalValue,
          total_spend: totalSpend,
          overall_roas: overallRoas,
        },
        purchase_roas: insight.purchase_roas,
        website_purchase_roas: insight.website_purchase_roas,
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });

  // ============================================================
  // get_frequency_data
  // ============================================================
  registry.registerTool({
    name: "get_frequency_data",
    description: "Analyze reach vs frequency to understand ad saturation and audience overlap",
    inputSchema: z.object({
      object_id: z.string().describe("ID of the object to analyze"),
      object_type: objectTypeSchema,
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
    }),
    annotations: {
      title: "Get Frequency Data",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        object_id: string;
        object_type: string;
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
      };

      const insightParams = buildInsightParams({
        date_preset: params.date_preset,
        time_range: params.time_range,
        fields: "reach,frequency,impressions,spend",
        breakdowns: ["frequency_value" as InsightBreakdown],
      });

      const response = await client.get<{ data: InsightRow[] }>(
        `${params.object_id}/insights`,
        insightParams as Record<string, unknown>
      );

      // Format frequency breakdown
      const frequencyBreakdown = response.data.map((row: InsightRow) => ({
        frequency: row.frequency_value || row.frequency,
        reach: parseInt(row.reach || "0", 10),
        impressions: parseInt(row.impressions || "0", 10),
        spend: parseFloat(row.spend || "0"),
      }));

      // Calculate summary metrics
      const totalReach = frequencyBreakdown.reduce(
        (sum: number, fb: { reach: number }) => sum + fb.reach,
        0
      );
      const totalImpressions = frequencyBreakdown.reduce(
        (sum: number, fb: { impressions: number }) => sum + fb.impressions,
        0
      );
      const avgFrequency =
        totalReach > 0 ? totalImpressions / totalReach : 0;

      const result = {
        frequency_breakdown: frequencyBreakdown,
        object_id: params.object_id,
        object_type: params.object_type,
        date_range: params.date_preset || params.time_range,
        summary: {
          total_reach: totalReach,
          total_impressions: totalImpressions,
          average_frequency: avgFrequency,
          unique_frequency_values: frequencyBreakdown.length,
        },
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });

  // ============================================================
  // get_attribution_data
  // ============================================================
  registry.registerTool({
    name: "get_attribution_data",
    description: "Compare metrics across different attribution windows (1d/7d/28d click/view)",
    inputSchema: z.object({
      object_id: z.string().describe("ID of the object to analyze"),
      object_type: objectTypeSchema,
      date_preset: datePresetSchema.optional(),
      time_range: timeRangeSchema.optional(),
      attribution_windows: attributionWindowSchema.optional(),
    }),
    annotations: {
      title: "Get Attribution Data",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "analytics",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      const params = args as {
        object_id: string;
        object_type: string;
        date_preset?: DatePreset;
        time_range?: { since: string; until: string };
        attribution_windows?: string[];
      };

      const windows =
        params.attribution_windows || [
          "1d_click",
          "7d_click",
          "28d_click",
          "1d_view",
          "7d_view",
        ];

      // Fetch insights for each attribution window
      const attributionPromises = windows.map((window: string) => {
        const insightParams = buildInsightParams({
          date_preset: params.date_preset,
          time_range: params.time_range,
          fields:
            "actions,conversions,cost_per_action_type,purchase_roas,spend",
        });
        insightParams.action_attribution_windows = `[${window}]`;

        return client
          .get<{ data: InsightRow[] }>(
            `${params.object_id}/insights`,
            insightParams as Record<string, unknown>
          )
          .then((response) => ({
            window,
            data: response.data[0] || ({} as InsightRow),
          }))
          .catch((error: Error) => ({
            window,
            error: error.message,
            data: {} as InsightRow,
          }));
      });

      const results = await Promise.all(attributionPromises);

      // Format attribution comparison
      const comparison = results.map((result: { window: string; data: InsightRow; error?: string }) => {
        const insight = result.data;
        const totalConversions = (insight.actions || []).reduce(
          (sum: number, action: { action_type: string; value: string }) =>
            action.action_type.includes("offsite_conversion")
              ? sum + parseInt(action.value, 10)
              : sum,
          0
        );

        return {
          attribution_window: result.window,
          conversions: totalConversions,
          actions: insight.actions || [],
          cost_per_action_type: insight.cost_per_action_type || [],
          purchase_roas: insight.purchase_roas,
          spend: parseFloat(insight.spend || "0"),
          error: result.error,
        };
      });

      const result = {
        attribution_comparison: comparison,
        object_id: params.object_id,
        object_type: params.object_type,
        date_range: params.date_preset || params.time_range,
        note: "Differences in metrics across attribution windows show how timing of conversions affects reported performance",
      };

      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2),
        }],
      };
    },
  });
}
