// Meta Marketing API Type Definitions

// ============================================================
// Core API Types
// ============================================================

export interface MetaApiConfig {
  accessToken: string;
  appId?: string;
  appSecret?: string;
  apiVersion: string; // e.g., "v21.0"
  baseUrl: string;
}

export interface MetaPaginatedResponse<T> {
  data: T[];
  paging?: {
    cursors?: { before: string; after: string };
    next?: string;
    previous?: string;
  };
  summary?: Record<string, unknown>;
}

export interface MetaApiError {
  error: {
    message: string;
    type: string;
    code: number;
    error_subcode?: number;
    fbtrace_id: string;
  };
}

// ============================================================
// Ad Account
// ============================================================

export interface AdAccount {
  id: string; // act_XXXXXXXXX
  name: string;
  account_id: string;
  account_status: number; // 1=ACTIVE, 2=DISABLED, 3=UNSETTLED, etc.
  currency: string;
  timezone_name: string;
  timezone_offset_hours_utc: number;
  business?: { id: string; name: string };
  balance: string;
  amount_spent: string;
  spend_cap: string;
  age: number;
  created_time: string;
  owner: string;
  funding_source?: string;
  capabilities?: string[];
}

// ============================================================
// Campaign
// ============================================================

export type CampaignObjective =
  | "OUTCOME_APP_PROMOTION"
  | "OUTCOME_AWARENESS"
  | "OUTCOME_ENGAGEMENT"
  | "OUTCOME_LEADS"
  | "OUTCOME_SALES"
  | "OUTCOME_TRAFFIC";

export type CampaignStatus = "ACTIVE" | "PAUSED" | "DELETED" | "ARCHIVED";

export type BuyingType = "AUCTION" | "RESERVED";

export type BidStrategy =
  | "LOWEST_COST_WITHOUT_CAP"
  | "LOWEST_COST_WITH_BID_CAP"
  | "COST_CAP"
  | "LOWEST_COST_WITH_MIN_ROAS";

export interface Campaign {
  id: string;
  name: string;
  account_id: string;
  objective: CampaignObjective;
  status: CampaignStatus;
  effective_status: string;
  buying_type: BuyingType;
  bid_strategy?: BidStrategy;
  budget_remaining: string;
  daily_budget?: string;
  lifetime_budget?: string;
  start_time?: string;
  stop_time?: string;
  created_time: string;
  updated_time: string;
  special_ad_categories: string[];
  spend_cap?: string;
}

export interface CreateCampaignParams {
  name: string;
  objective: CampaignObjective;
  status?: CampaignStatus;
  buying_type?: BuyingType;
  bid_strategy?: BidStrategy;
  daily_budget?: string;
  lifetime_budget?: string;
  start_time?: string;
  stop_time?: string;
  special_ad_categories?: string[];
  spend_cap?: string;
}

export interface UpdateCampaignParams {
  name?: string;
  status?: CampaignStatus;
  bid_strategy?: BidStrategy;
  daily_budget?: string;
  lifetime_budget?: string;
  start_time?: string;
  stop_time?: string;
  spend_cap?: string;
}

// ============================================================
// Ad Set
// ============================================================

export type AdSetStatus = "ACTIVE" | "PAUSED" | "DELETED" | "ARCHIVED";

export type OptimizationGoal =
  | "NONE"
  | "APP_INSTALLS"
  | "AD_RECALL_LIFT"
  | "ENGAGED_USERS"
  | "EVENT_RESPONSES"
  | "IMPRESSIONS"
  | "LEAD_GENERATION"
  | "LINK_CLICKS"
  | "OFFSITE_CONVERSIONS"
  | "PAGE_LIKES"
  | "POST_ENGAGEMENT"
  | "QUALITY_CALL"
  | "QUALITY_LEAD"
  | "REACH"
  | "LANDING_PAGE_VIEWS"
  | "VALUE"
  | "THRUPLAY"
  | "CONVERSATIONS"
  | "DERIVED_EVENTS";

export type BillingEvent = "APP_INSTALLS" | "CLICKS" | "IMPRESSIONS" | "LINK_CLICKS" | "NONE" | "OFFER_CLAIMS" | "PAGE_LIKES" | "POST_ENGAGEMENT" | "THRUPLAY";

export interface TargetingSpec {
  age_min?: number;
  age_max?: number;
  genders?: number[]; // 1=male, 2=female
  geo_locations?: {
    countries?: string[];
    regions?: Array<{ key: string }>;
    cities?: Array<{ key: string; radius?: number; distance_unit?: string }>;
    zips?: Array<{ key: string }>;
    location_types?: string[];
  };
  interests?: Array<{ id: string; name: string }>;
  behaviors?: Array<{ id: string; name: string }>;
  life_events?: Array<{ id: string; name: string }>;
  custom_audiences?: Array<{ id: string; name?: string }>;
  excluded_custom_audiences?: Array<{ id: string; name?: string }>;
  flexible_spec?: Array<Record<string, Array<{ id: string; name: string }>>>;
  exclusions?: Record<string, Array<{ id: string; name: string }>>;
  locales?: number[];
  publisher_platforms?: string[];
  facebook_positions?: string[];
  instagram_positions?: string[];
  device_platforms?: string[];
  targeting_optimization?: string;
}

export interface AdSet {
  id: string;
  name: string;
  account_id: string;
  campaign_id: string;
  status: AdSetStatus;
  effective_status: string;
  optimization_goal: OptimizationGoal;
  billing_event: BillingEvent;
  bid_amount?: number;
  bid_strategy?: BidStrategy;
  daily_budget?: string;
  lifetime_budget?: string;
  budget_remaining: string;
  targeting: TargetingSpec;
  start_time?: string;
  end_time?: string;
  created_time: string;
  updated_time: string;
  promoted_object?: Record<string, string>;
  destination_type?: string;
}

export interface CreateAdSetParams {
  name: string;
  campaign_id: string;
  optimization_goal: OptimizationGoal;
  billing_event: BillingEvent;
  targeting: TargetingSpec;
  status?: AdSetStatus;
  bid_amount?: number;
  bid_strategy?: BidStrategy;
  daily_budget?: string;
  lifetime_budget?: string;
  start_time?: string;
  end_time?: string;
  promoted_object?: Record<string, string>;
}

export interface UpdateAdSetParams {
  name?: string;
  status?: AdSetStatus;
  optimization_goal?: OptimizationGoal;
  bid_amount?: number;
  bid_strategy?: BidStrategy;
  daily_budget?: string;
  lifetime_budget?: string;
  targeting?: TargetingSpec;
  start_time?: string;
  end_time?: string;
}

// ============================================================
// Ad
// ============================================================

export type AdStatus = "ACTIVE" | "PAUSED" | "DELETED" | "ARCHIVED";

export interface Ad {
  id: string;
  name: string;
  account_id: string;
  campaign_id: string;
  adset_id: string;
  status: AdStatus;
  effective_status: string;
  creative: { id: string };
  created_time: string;
  updated_time: string;
  tracking_specs?: Record<string, unknown>[];
  conversion_specs?: Record<string, unknown>[];
}

export interface CreateAdParams {
  name: string;
  adset_id: string;
  creative: { creative_id: string } | AdCreativeSpec;
  status?: AdStatus;
  tracking_specs?: Record<string, unknown>[];
}

// ============================================================
// Ad Creative
// ============================================================

export interface AdCreative {
  id: string;
  name: string;
  account_id: string;
  body?: string;
  title?: string;
  call_to_action_type?: string;
  image_hash?: string;
  image_url?: string;
  video_id?: string;
  thumbnail_url?: string;
  link_url?: string;
  object_story_spec?: ObjectStorySpec;
  asset_feed_spec?: AssetFeedSpec;
  status: string;
  effective_status: string;
}

export interface ObjectStorySpec {
  page_id: string;
  link_data?: {
    link: string;
    message?: string;
    name?: string;
    description?: string;
    caption?: string;
    image_hash?: string;
    video_id?: string;
    call_to_action?: { type: string; value?: Record<string, string> };
    child_attachments?: Array<{
      link: string;
      image_hash?: string;
      video_id?: string;
      name?: string;
      description?: string;
      call_to_action?: { type: string; value?: Record<string, string> };
    }>;
  };
  video_data?: {
    video_id: string;
    title?: string;
    message?: string;
    image_hash?: string;
    call_to_action?: { type: string; value?: Record<string, string> };
  };
}

export interface AssetFeedSpec {
  images?: Array<{ hash: string }>;
  videos?: Array<{ video_id: string; thumbnail_hash?: string }>;
  bodies?: Array<{ text: string }>;
  titles?: Array<{ text: string }>;
  descriptions?: Array<{ text: string }>;
  link_urls?: Array<{ website_url: string }>;
  call_to_action_types?: string[];
}

export interface AdCreativeSpec {
  name?: string;
  object_story_spec?: ObjectStorySpec;
  asset_feed_spec?: AssetFeedSpec;
  url_tags?: string;
}

// ============================================================
// Insights
// ============================================================

export type DatePreset =
  | "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";

export type InsightBreakdown =
  | "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"
  | "body_asset"
  | "call_to_action_asset"
  | "description_asset"
  | "image_asset"
  | "link_url_asset"
  | "title_asset"
  | "video_asset";

export type InsightLevel = "account" | "campaign" | "adset" | "ad";

export interface InsightParams {
  date_preset?: DatePreset;
  time_range?: { since: string; until: string };
  time_increment?: number | "monthly" | "all_days";
  breakdowns?: InsightBreakdown[];
  level?: InsightLevel;
  fields?: string[];
  filtering?: Array<{ field: string; operator: string; value: string | string[] }>;
  limit?: number;
  sort?: string[];
}

export interface InsightRow {
  account_id?: string;
  campaign_id?: string;
  campaign_name?: string;
  adset_id?: string;
  adset_name?: string;
  ad_id?: string;
  ad_name?: string;
  date_start: string;
  date_stop: string;
  impressions?: string;
  clicks?: string;
  spend?: string;
  reach?: string;
  frequency?: string;
  cpc?: string;
  cpm?: string;
  cpp?: string;
  ctr?: string;
  actions?: Array<{ action_type: string; value: string }>;
  action_values?: Array<{ action_type: string; value: string }>;
  cost_per_action_type?: Array<{ action_type: string; value: string }>;
  cost_per_unique_action_type?: Array<{ action_type: string; value: string }>;
  conversions?: Array<{ action_type: string; value: string }>;
  conversion_values?: Array<{ action_type: string; value: string }>;
  purchase_roas?: Array<{ action_type: string; value: string }>;
  website_purchase_roas?: Array<{ action_type: string; value: string }>;
  unique_clicks?: string;
  unique_ctr?: string;
  unique_link_clicks_ctr?: string;
  inline_link_clicks?: string;
  inline_link_click_ctr?: string;
  outbound_clicks?: Array<{ action_type: string; value: string }>;
  video_avg_time_watched_actions?: Array<{ action_type: string; value: string }>;
  video_p25_watched_actions?: Array<{ action_type: string; value: string }>;
  video_p50_watched_actions?: Array<{ action_type: string; value: string }>;
  video_p75_watched_actions?: Array<{ action_type: string; value: string }>;
  video_p100_watched_actions?: Array<{ action_type: string; value: string }>;
  quality_ranking?: string;
  engagement_rate_ranking?: string;
  conversion_rate_ranking?: string;
  [key: string]: unknown;
}

// ============================================================
// Audience
// ============================================================

export type CustomAudienceSubtype =
  | "CUSTOM"
  | "WEBSITE"
  | "APP"
  | "OFFLINE"
  | "CLAIM"
  | "PARTNER"
  | "MANAGED"
  | "VIDEO"
  | "LOOKALIKE"
  | "ENGAGEMENT"
  | "BAG_OF_ACCOUNTS"
  | "STUDY_RULE_AUDIENCE"
  | "FOX";

export interface CustomAudience {
  id: string;
  name: string;
  account_id: string;
  subtype: CustomAudienceSubtype;
  description?: string;
  approximate_count_lower_bound?: number;
  approximate_count_upper_bound?: number;
  time_created: string;
  time_updated: string;
  retention_days?: number;
  rule?: string;
  delivery_status?: { status: string };
  operation_status?: { status: string };
  data_source?: { type: string; sub_type: string };
  lookalike_spec?: {
    origin: Array<{ id: string; name: string; type: string }>;
    ratio: number;
    country: string;
  };
}

// ============================================================
// Product Catalog
// ============================================================

export interface ProductCatalog {
  id: string;
  name: string;
  product_count: number;
  vertical: string;
  business?: { id: string; name: string };
}

export interface Product {
  id: string;
  name: string;
  description?: string;
  price: string;
  currency: string;
  url: string;
  image_url: string;
  availability: string;
  brand?: string;
  category?: string;
  retailer_id?: string;
}

// ============================================================
// Lead Form
// ============================================================

export interface LeadForm {
  id: string;
  name: string;
  status: string;
  page_id: string;
  locale: string;
  created_time: string;
  questions?: Array<{ key: string; label: string; type: string }>;
  privacy_policy_url?: string;
  thank_you_page?: { title: string; body: string; url?: string };
}

export interface Lead {
  id: string;
  form_id: string;
  created_time: string;
  field_data: Array<{ name: string; values: string[] }>;
}

// ============================================================
// Experiment / A/B Test
// ============================================================

export interface Experiment {
  id: string;
  name: string;
  description?: string;
  type: string;
  status: string;
  start_time: string;
  end_time?: string;
  control_ids: string[];
  treatment_ids: string[];
  winner_declaring_time?: string;
  winner_campaign_id?: string;
  results?: ExperimentResult[];
}

export interface ExperimentResult {
  campaign_id: string;
  objective_metric: string;
  metric_value: number;
  confidence_level: number;
  is_winner: boolean;
  lift_percentage?: number;
}

// ============================================================
// Ad Library (Competitive Intel)
// ============================================================

export interface AdLibraryEntry {
  id: string;
  ad_creation_time: string;
  ad_delivery_start_time: string;
  ad_delivery_stop_time?: string;
  ad_creative_bodies?: string[];
  ad_creative_link_captions?: string[];
  ad_creative_link_descriptions?: string[];
  ad_creative_link_titles?: string[];
  page_id: string;
  page_name: string;
  publisher_platforms?: string[];
  estimated_audience_size?: { lower_bound: number; upper_bound: number };
  spend?: { lower_bound: number; upper_bound: number; currency: string };
  impressions?: { lower_bound: number; upper_bound: number };
  demographic_distribution?: Array<{ percentage: string; age: string; gender: string }>;
  delivery_by_region?: Array<{ percentage: string; region: string }>;
}

// ============================================================
// Pixel
// ============================================================

export interface Pixel {
  id: string;
  name: string;
  code: string;
  creation_time: string;
  last_fired_time?: string;
  is_unavailable: boolean;
  data_use_setting: string;
  owner_ad_account?: { id: string; name: string };
}

// ============================================================
// MCP Tool Annotation Types
// ============================================================

export interface ToolAnnotations {
  title?: string;
  readOnlyHint?: boolean;
  destructiveHint?: boolean;
  idempotentHint?: boolean;
  openWorldHint?: boolean;
}

// ============================================================
// Lazy Loading Module Types
// ============================================================

export type ToolCategory =
  | "account"
  | "campaigns"
  | "adsets"
  | "ads"
  | "analytics"
  | "audiences"
  | "budget"
  | "experiments"
  | "catalog"
  | "leads"
  | "competitive";

export type LoadTier = "core" | "advanced";

export interface ToolModule {
  category: ToolCategory;
  tier: LoadTier;
  loaded: boolean;
  register: (server: unknown, client: unknown) => void;
}
