import { apiRequest } from "./client";

export type Pagination = {
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
};

export type CapabilityData = {
  discover_ready: boolean;
  ai_ready: boolean;
  publish_ready: boolean;
  discover_hint?: string;
  ai_hint?: string;
  publish_hint?: string;
  active_threads_account_id?: string;
};

export type ThreadsAccount = {
  id: string;
  display_name?: string;
  username?: string;
  threads_user_id?: string;
  persona_id?: string;
  browser_connected: boolean;
  api_connected: boolean;
  api_token_expires_at?: number;
  status: string;
};

export type ThreadsAccountList = {
  list: ThreadsAccount[];
  active_account_id?: string;
};

export type DeleteThreadsAccountResult = {
  deleted_id: string;
  active_account_id?: string;
  message: string;
};

export type ThreadsConnection = {
  account_id: string;
  account_name: string;
  username?: string;
  browser_connected: boolean;
  api_connected: boolean;
  prefs: Record<string, unknown>;
};

export type ThreadsAiSettings = {
  account_id: string;
  provider: string;
  model: string;
  research_provider?: string;
  research_model?: string;
  api_keys?: Record<string, string>;
  api_keys_configured?: Record<string, unknown>;
};

export type ThreadsAccountAiProviderModels = {
  id: string;
  label: string;
  models: string[];
  streams: boolean;
  error?: string;
};

export type PublishQueueItem = {
  id: string;
  account_id: string;
  persona_id?: string;
  copy_mission_id?: string;
  copy_draft_id?: string;
  text: string;
  topic_tag?: string;
  scheduled_at: number;
  status: string;
  media_id?: string;
  permalink?: string;
  published_at?: number;
  error_message?: string;
  retry_count?: number;
  last_attempt_at?: number;
  next_attempt_at?: number;
  missed_at?: number;
  paused_reason?: string;
  create_at: number;
  update_at: number;
};

export type PublishQueueList = {
  pagination: Pagination;
  list: PublishQueueItem[];
};

export type PublishHealth = {
  summary: {
    pending_scheduled: number;
    failed_count: number;
    published_7d: number;
    total_likes_7d: number;
    total_replies_7d: number;
  };
  pagination: Pagination;
  list: Array<{
    media_id: string;
    permalink?: string;
    text?: string;
    published_at: number;
    like_count: number;
    reply_count: number;
    repost_count?: number;
    quote_count?: number;
    views?: number;
    shares?: number;
    checkpoints?: Array<{ checkpoint: string; like_count: number; reply_count: number; checked_at: number }>;
  }>;
};

export type OwnPostPerformanceItem = {
  media_id: string;
  text?: string;
  permalink?: string;
  timestamp?: string;
  media_type?: string;
  media_url?: string;
  thumbnail_url?: string;
  topic_tag?: string;
  shortcode?: string;
  like_count: number;
  reply_count: number;
  repost_count?: number;
  quote_count?: number;
  views?: number;
  shares?: number;
  insights_status?: string;
  insights_message?: string;
};

export type PostPerformance = {
  account_id: string;
  username?: string;
  threads_user_id?: string;
  fetched_at: number;
  account_insights?: {
    status?: string;
    message?: string;
    metrics?: Array<{ name: string; value: number }>;
  };
  posts: OwnPostPerformanceItem[];
};

export type OwnPostFormulaReview = {
  media_id?: string;
  reviewed_at?: number;
  from_cache?: boolean;
  summary: string;
  wins?: string[];
  improvements?: string[];
  formula?: string;
  post_template?: string;
  hook_pattern?: string;
  structure?: string;
  replication_tips?: string[];
  avoid?: string[];
};

export type Persona = {
  id: string;
  display_name?: string;
  persona?: string;
  brief?: string;
  style_profile?: string;
  style_benchmark?: string;
  create_at: number;
  update_at: number;
};

export type CopyDraft = {
  id: string;
  persona_id: string;
  content_plan_id?: string;
  copy_mission_id?: string;
  scan_post_id?: string;
  formula_id?: string;
  draft_type: string;
  text: string;
  topic_tag?: string;
  angle?: string;
  hook?: string;
  rationale?: string;
  ai_score?: number;
  formula_score?: number;
  brand_fit_score?: number;
  risk_score?: number;
  similarity_score?: number;
  engagement_potential?: number;
  freshness_score?: number;
  review_suggestion?: string;
  status?: string;
  publish_queue_id?: string;
  published_at?: number;
  published_permalink?: string;
  create_at?: number;
};

export type CopyMissionInspiration = {
  topic_candidate_id?: string;
  content_plan_id?: string;
  label: string;
  seed_query: string;
  brief: string;
  trend_reason?: string;
  trend_keywords?: string[];
  angles?: string[];
  mission?: string;
  target_audience?: string;
  opening_type?: string;
  body_type?: string;
  emotion?: string;
  cta_type?: string;
  risk_level?: string;
  avoid?: string[];
  sources?: Array<{ query?: string; title?: string; snippet?: string; url?: string }>;
  web_search_used: boolean;
  message: string;
};

export type TopicCandidate = {
  id: string;
  persona_id: string;
  name: string;
  source?: string;
  category?: string;
  seed_query?: string;
  trend_reason?: string;
  trend_keywords?: string[];
  heat_score?: number;
  fit_score?: number;
  interaction_score?: number;
  extend_score?: number;
  risk_score?: number;
  final_score?: number;
  recommended_missions?: string[];
  status?: string;
  create_at: number;
  update_at: number;
};

export type ContentPlan = {
  id: string;
  persona_id: string;
  topic_candidate_id?: string;
  topic: string;
  mission: string;
  target_audience?: string;
  angle?: string;
  opening_type?: string;
  body_type?: string;
  emotion?: string;
  ending_type?: string;
  cta_type?: string;
  risk_level?: string;
  requires_human_review?: boolean;
  avoid?: string[];
  selected_knowledge?: string[];
  status?: string;
  create_at: number;
  update_at: number;
};

export type FeedbackEvent = {
  id: string;
  persona_id: string;
  content_plan_id?: string;
  draft_id?: string;
  decision: string;
  note?: string;
  snapshot?: string;
  create_at: number;
};

export type KnowledgeSource = { id: string; persona_id: string; source_type: string; title?: string; filename?: string; parsed_status?: string; chunk_count?: number; create_at: number };
export type KnowledgeChunk = { id: string; persona_id: string; source_id: string; content: string; topics?: string[]; style_tags?: string[]; risk_level?: string; create_at: number };
export type FormulaPool = { id: string; persona_id: string; type: string; name: string; pattern?: string; use_cases?: string[]; avoid?: string[]; weight?: number; create_at: number; update_at: number };

export type ContentInboxItem = CopyDraft & {
  scheduled_at?: number;
  lifecycle: "draft" | "scheduled" | "published" | string;
  group_date: number;
  formula_label?: string;
};

export type ContentFormula = {
  id: string;
  account_id: string;
  label: string;
  source_type: string;
  source_ref?: string;
  source_post_text?: string;
  source_author?: string;
  source_permalink?: string;
  summary?: string;
  wins?: string[];
  improvements?: string[];
  formula: string;
  post_template?: string;
  hook_pattern?: string;
  structure?: string;
  replication_tips?: string[];
  avoid?: string[];
  tags?: string[];
  create_at: number;
  update_at: number;
};

export type ViralScanPost = {
  id: string;
  search_tag: string;
  permalink: string;
  author: string;
  text: string;
  like_count: number;
  reply_count: number;
  engagement_score: number;
  source: string;
  create_at: number;
};

export type ContentFormulaSearchPost = {
  text: string;
  author: string;
  permalink?: string;
  media_id?: string;
  like_count: number;
  reply_count: number;
  engagement_score: number;
};

export type PublishSlot = {
  weekday: number;
  time: string;
};

export type PublishSourceRef = {
  type: string;
  persona_id?: string;
  copy_mission_id?: string;
  scan_post_id?: string;
  manual_seed?: string;
};

export type PublishInventoryPolicy = {
  account_id: string;
  enabled: boolean;
  target_daily_count: number;
  low_stock_threshold: number;
  lookahead_days: number;
  timezone: string;
  slots: PublishSlot[];
  source_refs: PublishSourceRef[];
  update_at: number;
};

export type PublishGuardPolicy = {
  account_id: string;
  enabled: boolean;
  max_daily_posts: number;
  min_interval_minutes: number;
  consecutive_failure_pause_limit: number;
  paused: boolean;
  paused_reason?: string;
  update_at: number;
};

export type PublishSlotInsights = {
  account_id: string;
  timezone: string;
  slots: Array<PublishSlot & {
    avg_likes_1h: number;
    avg_replies_1h: number;
    avg_likes_24h: number;
    avg_replies_24h: number;
    avg_likes_7d: number;
    avg_replies_7d: number;
    sample_size: number;
    recommendation: string;
  }>;
};

export type PublishQueueEvent = {
  id: string;
  queue_id: string;
  event_type: string;
  from_status?: string;
  to_status?: string;
  message?: string;
  create_at: number;
};

export type PublishAlert = {
  type: string;
  severity: string;
  message: string;
  queue_id?: string;
  account_id: string;
  create_at: number;
};

export type PublishDashboardSummary = {
  list: Array<{
    account_id: string;
    account_name: string;
    pending_scheduled: number;
    failed_count: number;
    published_7d: number;
    total_likes_7d: number;
    total_replies_7d: number;
    paused: boolean;
    best_slot?: string;
    low_slot?: string;
  }>;
  total_pending: number;
  total_failed: number;
  total_published_7d: number;
  total_likes_7d: number;
  total_replies_7d: number;
};

export type ThreadsDiagnostics = {
  account_id: string;
  checked_at: number;
  api_connected: boolean;
  token_expires_at?: number;
  scopes: string[];
  items: Array<{ scope: string; name: string; status: string; message: string; count: number }>;
  message: string;
};

export type ThreadsPlaygroundResult = {
  action: string;
  ok: boolean;
  message: string;
  data: string;
};

export type MentionInboxItem = {
  media_id: string;
  author_username?: string;
  text?: string;
  permalink?: string;
  shortcode?: string;
  timestamp?: string;
  media_type?: string;
  is_reply: boolean;
  is_quote_post: boolean;
  has_replies: boolean;
  root_post_id?: string;
  parent_id?: string;
  thread_post_text?: string;
  parent_reply_text?: string;
  reply_ready: boolean;
  reply_ready_msg?: string;
  synced_at: number;
};

export type SyncMentionInboxResult = {
  synced: number;
  ready: number;
  total: number;
};

export type MentionInboxList = {
  list: MentionInboxItem[];
  pagination: Pagination;
  ready_total?: number;
  newest_synced_at?: number;
};

export type ThreadsReply = {
  id: string;
  text?: string;
  username?: string;
  permalink?: string;
  timestamp?: string;
  like_count?: number;
  parent_id?: string;
  replied_to_id?: string;
  root_post_id?: string;
  is_reply?: boolean;
  is_reply_owned_by_me?: boolean;
  has_replies?: boolean;
  media_type?: string;
  media_url?: string;
  thumbnail_url?: string;
  gif_url?: string;
  media_children?: Array<{
    id?: string;
    media_type?: string;
    media_url?: string;
    thumbnail_url?: string;
  }>;
};

export type ThreadsInspirationPost = {
  id: string;
  text?: string;
  username?: string;
  permalink?: string;
  timestamp?: string;
  like_count?: number;
  reply_count?: number;
};

export type StylePreset = {
  id: string;
  persona_id: string;
  name: string;
  tone?: string;
  cta?: string[];
  banned_words?: string[];
  notes?: string;
  create_at: number;
  update_at: number;
};

// ==================== Brand (full contract per backend) ====================
export type ResearchItemData = {
  title?: string;
  url?: string;
  snippet?: string;
  query?: string;
};

export type ResearchMapData = {
  audience_summary?: string;
  content_goal?: string;
  questions?: string[];
  pillars?: string[];
  exclusions?: string[];
  research_items?: ResearchItemData[];
  expand_strategy?: string;
  patrol_keywords?: string[];
};

export type BrandProductData = {
  id: string;
  label: string;
  product_context: string;
  match_tags?: string[];
  placement_url?: string;   // 置入網址
  create_at: number;
  update_at: number;
};

export type BrandData = {
  id: string;
  display_name?: string;
  topic_name?: string;
  seed_query?: string;
  brief?: string;
  product_brief?: string;
  product_context?: string;
  product_id?: string;
  products?: BrandProductData[];
  target_audience?: string;
  goals?: string;
  research_map?: ResearchMapData;
  create_at: number;
  update_at: number;
};

export type ListBrandsData = { list: BrandData[] };

export type PlacementTopicData = {
  id: string;
  brand_id: string;
  brand_display_name?: string;
  topic_name?: string;
  seed_query?: string;
  brief?: string;
  product_id?: string;
  research_map?: ResearchMapData;
  create_at: number;
  update_at: number;
};

export type ListPlacementTopicsData = { list: PlacementTopicData[] };

export type KnowledgeGraphEvidenceData = {
  url?: string;
  snippet?: string;
  query?: string;
};

export type BraveSourceData = {
  query?: string;
  title?: string;
  url?: string;
  snippet?: string;
};

export type KnowledgeGraphNodeData = {
  id: string;
  label: string;
  node_kind: string;
  type: string;
  layer: number;
  relation?: string;
  placement_value?: string;
  product_fit_score: number;
  selected_for_scan: boolean;
  relevance_tags: string[];
  recency_tags: string[];
  evidence?: KnowledgeGraphEvidenceData[];
};

export type KnowledgeGraphEdgeData = {
  from: string;
  to: string;
  relation: string;
};

export type KnowledgeGraphData = {
  id: string;
  brand_id: string;
  seed: string;
  nodes: KnowledgeGraphNodeData[];
  edges: KnowledgeGraphEdgeData[];
  brave_sources?: BraveSourceData[];
  expand_strategy?: string;
  pain_tag_count: number;
  generated_at: number;
  create_at: number;
  update_at: number;
};

export type ExpandKnowledgeGraphData = {
  job_id: string;
  status: string;
  message: string;
};

export type ScanReplyData = {
  external_id?: string;
  author?: string;
  text: string;
  permalink?: string;
  like_count?: number;
  posted_at?: string;
};

export type GenerateOutreachDraftsData = {
  id: string;
  scan_post_id: string;
  relevance: number;
  reason: string;
  drafts: Array<{ text: string; angle: string; rationale: string }>;
  create_at: number;
};

export type PublishOutreachDraftData = {
  scan_post_id: string;
  reply_id?: string;
  permalink?: string;
  outreach_status: string;
  published_permalink?: string;
  message: string;
};

export type ScanPostData = {
  id: string;
  graph_node_id: string;
  search_tag: string;
  query_dimension: string;
  recency_days?: number;
  external_id: string;
  permalink?: string;
  author: string;
  text: string;
  priority: string;
  placement_score: number;
  product_fit_score: number;
  solved_by_product: boolean;
  source: string;
  scan_job_id: string;
  outreach_status?: string;
  published_reply_id?: string;
  published_permalink?: string;
  outreach_update_at?: number;
  posted_at?: string;
  replies?: ScanReplyData[];
  latest_draft?: GenerateOutreachDraftsData;
  create_at: number;
};

export type ListBrandScanPostsData = {
  list: ScanPostData[];
  total: number;
};

export type ContentMatrixRowData = {
  sort_order: number;
  search_tag: string;
  angle: string;
  hook: string;
  text: string;
  reference_notes: string;
  source_permalinks: string[];
  rationale: string;
};

export type ContentMatrixData = {
  id?: string;
  brand_id: string;
  rows: ContentMatrixRowData[];
  generated_at: number;
  create_at?: number;
  update_at?: number;
};

export type BrandScanScheduleData = {
  id?: string;
  brand_id: string;
  cron: string;
  timezone: string;
  enabled: boolean;
  next_run_at?: number;
  last_run_at?: number;
};

// Legacy aliases for existing PatrolPage usage (keep minimal surface)
export type Brand = {
  id: string;
  display_name?: string;
  topic_name?: string;
  seed_query?: string;
  brief?: string;
  product_context?: string;
  target_audience?: string;
  goals?: string;
};

export type ScanPost = {
  id: string;
  author: string;
  text: string;
  permalink?: string;
  priority?: string;
  placement_score?: number;
  product_fit_score?: number;
  outreach_status?: string;
};

export type JobStepProgress = {
  id: string;
  status: string;
  message?: string;
  started_at?: number;
  ended_at?: number;
};

export type JobRun = {
  id: string;
  template_type: string;
  status: string;
  phase?: string;
  worker_type?: string;
  progress?: { percentage?: number; summary?: string; steps?: JobStepProgress[] };
  error?: string;
  attempt?: number;
  max_attempts?: number;
  create_at: number;
  update_at: number;
};

export type JobEvent = {
  id: string;
  job_id: string;
  type: string;
  from?: string;
  to?: string;
  message: string;
  metadata?: Record<string, unknown>;
  create_at: number;
};

export type JobList = {
  pagination: Pagination;
  list: JobRun[];
};

export type JobSchedule = {
  id: string;
  template_type: string;
  cron: string;
  timezone: string;
  enabled: boolean;
  next_run_at?: number;
  last_run_at?: number;
};

export type SettingValue = {
  scope: string;
  scope_id: string;
  key: string;
  value: unknown;
  version?: number;
};

export const api = {
  capabilities: () => apiRequest<CapabilityData>("/api/v1/members/me/capabilities", { auth: true }),
  memberMe: () => apiRequest<unknown>("/api/v1/members/me", { auth: true }),
  placementSettings: () => apiRequest<unknown>("/api/v1/members/me/placement-settings", { auth: true }),
  updatePlacementSettings: (body: Record<string, unknown>) =>
    apiRequest<unknown>("/api/v1/members/me/placement-settings", { method: "PATCH", body, auth: true }),

  threadsAccounts: () => apiRequest<ThreadsAccountList>("/api/v1/threads-accounts/", { auth: true }),
  createThreadsAccount: (body: { display_name?: string; activate?: boolean }) =>
    apiRequest<ThreadsAccount>("/api/v1/threads-accounts/", { method: "POST", body, auth: true }),
  deleteThreadsAccount: (id: string) => apiRequest<DeleteThreadsAccountResult>(`/api/v1/threads-accounts/${id}`, { method: "DELETE", auth: true }),
  activateThreadsAccount: (id: string) => apiRequest<null>(`/api/v1/threads-accounts/${id}/activate`, { method: "POST", auth: true }),
  getThreadsConnection: (id: string) => apiRequest<ThreadsConnection>(`/api/v1/threads-accounts/${id}/connection`, { auth: true }),
  updateThreadsConnection: (id: string, body: Record<string, unknown>) =>
    apiRequest<ThreadsConnection>(`/api/v1/threads-accounts/${id}/connection`, { method: "PATCH", body, auth: true }),
  importThreadsAccountSession: (id: string, storageState: string) =>
    apiRequest<{ success: boolean; valid: boolean; synced: boolean; message: string; account_id: string; username?: string }>(
      `/api/v1/threads-accounts/${id}/session/import`,
      { method: "POST", body: { storageState }, auth: true }
    ),
  threadsAiSettings: (id: string) => apiRequest<ThreadsAiSettings>(`/api/v1/threads-accounts/${id}/ai-settings`, { auth: true }),
  updateThreadsAiSettings: (id: string, body: Record<string, unknown>) =>
    apiRequest<ThreadsAiSettings>(`/api/v1/threads-accounts/${id}/ai-settings`, { method: "PUT", body, auth: true }),
  threadsAccountProviderModels: (id: string, provider: string, apiKey?: string) =>
    apiRequest<ThreadsAccountAiProviderModels>(`/api/v1/threads-accounts/${id}/ai-settings/providers/${provider}/models`, {
      method: "POST",
      body: apiKey ? { api_key: apiKey } : {},
      auth: true
    }),
  oauthConfig: () => apiRequest<{ enabled: boolean; redirect_uri: string; success_redirect: string; requires_https: boolean }>("/api/v1/threads-accounts/oauth/config", { auth: true }),
  oauthLogs: () => apiRequest<{ list: Array<{ at: number; level: string; stage: string; message: string }> }>("/api/v1/threads-accounts/oauth/logs", { auth: true }),
  startOauth: (accountId?: string) =>
    apiRequest<{ authorize_url: string; account_id?: string; state?: string }>(
      `/api/v1/threads-accounts/oauth/start${accountId ? `?account_id=${encodeURIComponent(accountId)}` : ""}`,
      { auth: true }
    ),
  smokeTest: (id: string) => apiRequest<unknown>(`/api/v1/threads-accounts/${id}/api/smoke-test`, { method: "POST", auth: true }),
  threadsDiagnostics: (id: string) => apiRequest<ThreadsDiagnostics>(`/api/v1/threads-accounts/${id}/diagnostics`, { auth: true }),
  publishDashboardSummary: () => apiRequest<PublishDashboardSummary>("/api/v1/threads-accounts/publish-dashboard-summary", { auth: true }),
  threadsPlayground: (id: string, body: Record<string, unknown>) =>
    apiRequest<ThreadsPlaygroundResult>(`/api/v1/threads-accounts/${id}/api/playground`, { method: "POST", body, auth: true }),
  syncMentionInbox: (accountId: string, limit = 25, maxPages = 4) =>
    apiRequest<SyncMentionInboxResult>(`/api/v1/threads-accounts/${accountId}/mention-inbox/sync`, {
      method: "POST",
      body: { limit, max_pages: maxPages },
      auth: true
    }),
  listMentionInbox: (accountId: string, page = 1, pageSize = 8) =>
    apiRequest<MentionInboxList>(
      `/api/v1/threads-accounts/${accountId}/mention-inbox?page=${page}&pageSize=${pageSize}`,
      { auth: true }
    ),
  publishMentionReply: (accountId: string, mediaId: string, text: string) =>
    apiRequest<{ media_id?: string; permalink?: string }>(
      `/api/v1/threads-accounts/${accountId}/mention-inbox/${encodeURIComponent(mediaId)}/reply`,
      { method: "POST", body: { text }, auth: true }
    ),

  publishQueue: (accountId: string, status = "", page = 1) =>
    apiRequest<PublishQueueList>(`/api/v1/threads-accounts/${accountId}/publish-queue?page=${page}&pageSize=20${status ? `&status=${status}` : ""}`, { auth: true }),
  createPublishQueue: (accountId: string, body: { text: string; topic_tag?: string; scheduled_at?: number }) =>
    apiRequest<PublishQueueItem>(`/api/v1/threads-accounts/${accountId}/publish-queue`, { method: "POST", body, auth: true }),
  patchPublishQueue: (accountId: string, qid: string, body: { text?: string; topic_tag?: string; scheduled_at?: number }) =>
    apiRequest<PublishQueueItem>(`/api/v1/threads-accounts/${accountId}/publish-queue/${qid}`, { method: "PATCH", body, auth: true }),
  cancelPublishQueue: (accountId: string, qid: string) =>
    apiRequest<PublishQueueItem>(`/api/v1/threads-accounts/${accountId}/publish-queue/${qid}/cancel`, { method: "POST", auth: true }),
  deletePublishQueue: (accountId: string, qid: string) =>
    apiRequest<null>(`/api/v1/threads-accounts/${accountId}/publish-queue/${qid}`, { method: "DELETE", auth: true }),
  retryPublishQueue: (accountId: string, qid: string) =>
    apiRequest<PublishQueueItem>(`/api/v1/threads-accounts/${accountId}/publish-queue/${qid}/retry`, { method: "POST", auth: true }),
  publishQueueEvents: (accountId: string, qid: string) =>
    apiRequest<{ list: PublishQueueEvent[] }>(`/api/v1/threads-accounts/${accountId}/publish-queue/${qid}/events`, { auth: true }),
  publishAlerts: (accountId: string) => apiRequest<{ list: PublishAlert[] }>(`/api/v1/threads-accounts/${accountId}/publish-alerts`, { auth: true }),
  publishCalendar: (accountId: string, startAt: number, endAt: number, status = "") =>
    apiRequest<PublishQueueList>(
      `/api/v1/threads-accounts/${accountId}/publish-calendar?startAt=${startAt}&endAt=${endAt}${status ? `&status=${status}` : ""}`,
      { auth: true }
    ),
  publishInventoryPolicy: (accountId: string) => apiRequest<PublishInventoryPolicy>(`/api/v1/threads-accounts/${accountId}/publish-inventory-policy`, { auth: true }),
  updatePublishInventoryPolicy: (accountId: string, body: Partial<PublishInventoryPolicy>) =>
    apiRequest<PublishInventoryPolicy>(`/api/v1/threads-accounts/${accountId}/publish-inventory-policy`, { method: "PUT", body, auth: true }),
  startPublishInventoryRefill: (accountId: string, count?: number) =>
    apiRequest<{ job_id: string; status: string; message: string }>(`/api/v1/threads-accounts/${accountId}/publish-inventory/refill-jobs`, { method: "POST", body: { count }, auth: true }),
  publishSlotInsights: (accountId: string) => apiRequest<PublishSlotInsights>(`/api/v1/threads-accounts/${accountId}/publish-slot-insights`, { auth: true }),
  publishGuardPolicy: (accountId: string) => apiRequest<PublishGuardPolicy>(`/api/v1/threads-accounts/${accountId}/publish-guard-policy`, { auth: true }),
  updatePublishGuardPolicy: (accountId: string, body: Partial<PublishGuardPolicy>) =>
    apiRequest<PublishGuardPolicy>(`/api/v1/threads-accounts/${accountId}/publish-guard-policy`, { method: "PUT", body, auth: true }),
  resumePublishGuard: (accountId: string) =>
    apiRequest<PublishGuardPolicy>(`/api/v1/threads-accounts/${accountId}/publish-guard/resume`, { method: "POST", auth: true }),
  publishHealth: (accountId: string) => apiRequest<PublishHealth>(`/api/v1/threads-accounts/${accountId}/publish-health?page=1&pageSize=10`, { auth: true }),
  postPerformance: (accountId: string, limit = 30) =>
    apiRequest<PostPerformance>(`/api/v1/threads-accounts/${accountId}/post-performance?limit=${limit}`, { auth: true }),
  generateOwnPostReplyDraft: (
    accountId: string,
    body: {
      media_id: string;
      persona_id?: string;
      reply_to_id?: string;
      post_text?: string;
      reply_text?: string;
      thread_post_text?: string;
      parent_reply_text?: string;
    }
  ) =>
    apiRequest<{ text: string }>(`/api/v1/threads-accounts/${accountId}/own-post-reply-draft`, {
      method: "POST",
      body,
      auth: true
    }),
  generateOwnPostFormula: (
    accountId: string,
    body: {
      media_id: string;
      persona_id?: string;
      post_text?: string;
      topic_tag?: string;
      media_type?: string;
      timestamp?: string;
      like_count?: number;
      reply_count?: number;
      views?: number;
      repost_count?: number;
      quote_count?: number;
      shares?: number;
      force?: boolean;
    }
  ) =>
    apiRequest<OwnPostFormulaReview>(`/api/v1/threads-accounts/${accountId}/own-post-formula`, {
      method: "POST",
      body,
      auth: true
    }),
  listOwnPostFormulas: (accountId: string) =>
    apiRequest<{ list: OwnPostFormulaReview[] }>(`/api/v1/threads-accounts/${accountId}/own-post-formulas`, { auth: true }),

  personas: () => apiRequest<{ list: Persona[] }>("/api/v1/personas/", { auth: true }),
  createPersona: (body: { display_name?: string }) => apiRequest<Persona>("/api/v1/personas/", { method: "POST", body, auth: true }),
  updatePersona: (id: string, body: Record<string, unknown>) => apiRequest<Persona>(`/api/v1/personas/${id}`, { method: "PATCH", body, auth: true }),
  deletePersona: (id: string) => apiRequest<null>(`/api/v1/personas/${id}`, { method: "DELETE", auth: true }),
  startStyleAnalysis: (id: string, benchmark_username: string) =>
    apiRequest<{ job_id: string; status: string }>(`/api/v1/personas/${id}/style-analysis`, { method: "POST", body: { benchmark_username }, auth: true }),
  startStyleAnalysisFromText: (
    id: string,
    body: { reference_texts?: string[]; raw_text?: string; source_label?: string }
  ) =>
    apiRequest<{ persona: Persona; post_count: number; message: string }>(
      `/api/v1/personas/${id}/style-analysis-from-text`,
      { method: "POST", body, auth: true }
    ),
  viralScanPosts: (personaId: string, limit = 30) =>
    apiRequest<{ list: ViralScanPost[]; total: number }>(`/api/v1/personas/${personaId}/viral-scan-posts?limit=${limit}`, { auth: true }),
  personaDrafts: (id: string) => apiRequest<{ list: CopyDraft[]; total: number }>(`/api/v1/personas/${id}/copy-drafts`, { auth: true }),
  updateDraft: (personaId: string, draftId: string, body: Record<string, unknown>) =>
    apiRequest<CopyDraft>(`/api/v1/personas/${personaId}/copy-drafts/${draftId}`, { method: "PATCH", body, auth: true }),
  pruneCopyDrafts: (personaId: string, body?: { keep?: number }) =>
    apiRequest<{ deleted: number; kept: number; message: string }>(`/api/v1/personas/${personaId}/copy-drafts/prune`, { method: "POST", body: body ?? {}, auth: true }),
  deleteDraft: (personaId: string, draftId: string) =>
    apiRequest<{ draft_id: string; message: string }>(`/api/v1/personas/${personaId}/copy-drafts/${draftId}`, { method: "DELETE", auth: true }),
  schedulePersonaDrafts: (personaId: string, body: { account_id: string; draft_ids: string[]; start_at?: number; timezone?: string; slots?: PublishSlot[]; mode?: string }) =>
    apiRequest<{ scheduled: number; list: PublishQueueItem[]; message: string }>(`/api/v1/personas/${personaId}/copy-drafts/schedule`, { method: "POST", body, auth: true }),
  contentInbox: (personaId: string, params?: { page?: number; pageSize?: number; status?: string; rangeStart?: number; rangeEnd?: number }) => {
    const q = new URLSearchParams();
    if (params?.page) q.set("page", String(params.page));
    if (params?.pageSize) q.set("pageSize", String(params.pageSize));
    if (params?.status) q.set("status", params.status);
    if (params?.rangeStart) q.set("rangeStart", String(params.rangeStart));
    if (params?.rangeEnd) q.set("rangeEnd", String(params.rangeEnd));
    const suffix = q.toString() ? `?${q.toString()}` : "";
    return apiRequest<{ pagination: Pagination; list: ContentInboxItem[] }>(`/api/v1/personas/${personaId}/content-inbox${suffix}`, { auth: true });
  },
  scheduleCopyDraft: (personaId: string, draftId: string, body: { account_id: string; topic_tag?: string; scheduled_at?: number }) =>
    apiRequest<{ scheduled: number; list: PublishQueueItem[]; message: string }>(`/api/v1/personas/${personaId}/copy-drafts/${draftId}/schedule`, { method: "POST", body, auth: true }),
  generateFromFormula: (personaId: string, formulaId: string, body: { account_id: string; topic: string; brief?: string; use_web_search?: boolean; draft_count?: number }) =>
    apiRequest<{ list: CopyDraft[]; message: string }>(`/api/v1/personas/${personaId}/content-formulas/${formulaId}/generate`, { method: "POST", body, auth: true }),
  contentFormulas: (accountId: string, params?: { page?: number; pageSize?: number; source_type?: string; tag?: string }) => {
    const q = new URLSearchParams();
    if (params?.page) q.set("page", String(params.page));
    if (params?.pageSize) q.set("pageSize", String(params.pageSize));
    if (params?.source_type) q.set("source_type", params.source_type);
    if (params?.tag) q.set("tag", params.tag);
    const suffix = q.toString() ? `?${q.toString()}` : "";
    return apiRequest<{ pagination: Pagination; list: ContentFormula[] }>(`/api/v1/threads-accounts/${accountId}/content-formulas${suffix}`, { auth: true });
  },
  analyzeContentFormula: (accountId: string, body: Record<string, unknown>) =>
    apiRequest<{ formula: ContentFormula; message: string }>(`/api/v1/threads-accounts/${accountId}/content-formulas/analyze`, { method: "POST", body, auth: true }),
  searchContentFormulaPosts: (accountId: string, body: { keyword: string; search_type?: string; limit?: number }) =>
    apiRequest<{ list: ContentFormulaSearchPost[]; message: string }>(`/api/v1/threads-accounts/${accountId}/content-formulas/search-posts`, { method: "POST", body, auth: true }),
  importOwnPostToFormula: (accountId: string, body: { media_id: string; label?: string }) =>
    apiRequest<{ formula: ContentFormula; message: string }>(`/api/v1/threads-accounts/${accountId}/content-formulas/import-own-post`, { method: "POST", body, auth: true }),
  deleteContentFormula: (accountId: string, formulaId: string) =>
    apiRequest<{ formula_id: string; message: string }>(`/api/v1/threads-accounts/${accountId}/content-formulas/${formulaId}`, { method: "DELETE", auth: true }),
  stylePresets: (personaId: string) => apiRequest<{ list: StylePreset[] }>(`/api/v1/personas/${personaId}/style-presets`, { auth: true }),
  upsertStylePreset: (personaId: string, presetId: string, body: { name: string; tone?: string; cta?: string[]; banned_words?: string[]; notes?: string; apply?: boolean }) =>
    apiRequest<StylePreset>(`/api/v1/personas/${personaId}/style-presets/${presetId}`, { method: "PUT", body, auth: true }),
  deleteStylePreset: (personaId: string, presetId: string) =>
    apiRequest<null>(`/api/v1/personas/${personaId}/style-presets/${presetId}`, { method: "DELETE", auth: true }),

  generateTopicMatrix: (personaId: string, body: { topic: string; brief?: string; use_web_search?: boolean; draft_count?: number }) =>
    apiRequest<{ list: CopyDraft[]; message: string }>(`/api/v1/personas/${personaId}/topic-matrix/generate`, { method: "POST", body, auth: true }),
  startTopicMatrixJob: (personaId: string, body: { topic: string; content_plan_id?: string; brief?: string; use_web_search?: boolean; draft_count?: number }) =>
    apiRequest<{ job_id: string; status: string; ai_provider: string; ai_model: string; message: string }>(`/api/v1/personas/${personaId}/topic-matrix/jobs`, { method: "POST", body, auth: true }),
  startFormulaDraftJob: (personaId: string, body: { account_id: string; formula_id: string; topic: string; brief?: string; use_web_search?: boolean; draft_count?: number }) =>
    apiRequest<{ job_id: string; status: string; ai_provider: string; ai_model: string; message: string }>(`/api/v1/personas/${personaId}/formula-draft/jobs`, { method: "POST", body, auth: true }),
  startRewriteDraftJob: (personaId: string, body: { account_id: string; reference_text: string; topic: string; brief?: string; save_label?: string; use_web_search?: boolean; draft_count?: number }) =>
    apiRequest<{ job_id: string; status: string; ai_provider: string; ai_model: string; message: string }>(`/api/v1/personas/${personaId}/rewrite-draft/jobs`, { method: "POST", body, auth: true }),
  inspireCopyMission: (personaId: string, body: { keyword?: string; content_direction?: string; use_web_search?: boolean; avoid_topics?: string[] }) =>
    apiRequest<CopyMissionInspiration>(`/api/v1/personas/${personaId}/copy-mission-inspiration`, { method: "POST", body, auth: true }),
  topicCandidates: (personaId: string) =>
    apiRequest<{ list: TopicCandidate[] }>(`/api/v1/personas/${personaId}/topic-candidates`, { auth: true }),
  contentPlans: (personaId: string) =>
    apiRequest<{ list: ContentPlan[] }>(`/api/v1/personas/${personaId}/content-plans`, { auth: true }),
  updateContentPlan: (personaId: string, contentPlanId: string, body: Record<string, unknown>) =>
    apiRequest<ContentPlan>(`/api/v1/personas/${personaId}/content-plans/${contentPlanId}`, { method: "PATCH", body, auth: true }),
  createFeedbackEvent: (personaId: string, body: { content_plan_id?: string; draft_id?: string; decision: string; note?: string; snapshot?: string }) =>
    apiRequest<FeedbackEvent>(`/api/v1/personas/${personaId}/feedback-events`, { method: "POST", body, auth: true }),
  createKnowledgeSource: (personaId: string, body: { source_type: string; title?: string; filename?: string; content?: string; content_base64?: string }) =>
    apiRequest<KnowledgeSource>(`/api/v1/personas/${personaId}/knowledge-sources`, { method: "POST", body, auth: true }),
  knowledgeSources: (personaId: string) =>
    apiRequest<{ list: KnowledgeSource[] }>(`/api/v1/personas/${personaId}/knowledge-sources`, { auth: true }),
  knowledgeChunks: (personaId: string) =>
    apiRequest<{ list: KnowledgeChunk[] }>(`/api/v1/personas/${personaId}/knowledge-chunks`, { auth: true }),
  formulaPools: (personaId: string) =>
    apiRequest<{ list: FormulaPool[] }>(`/api/v1/personas/${personaId}/formula-pools`, { auth: true }),
  createFormulaPool: (personaId: string, body: { type: string; name: string; pattern?: string; use_cases?: string[]; avoid?: string[]; weight?: number }) =>
    apiRequest<FormulaPool>(`/api/v1/personas/${personaId}/formula-pools`, { method: "POST", body, auth: true }),

  // Brand core
  brands: () => apiRequest<ListBrandsData>("/api/v1/brands/", { auth: true }),
  createBrand: (body: { display_name?: string }) => apiRequest<BrandData>("/api/v1/brands/", { method: "POST", body, auth: true }),
  getBrand: (id: string) => apiRequest<BrandData>(`/api/v1/brands/${id}`, { auth: true }),
  updateBrand: (id: string, body: Record<string, unknown>) => apiRequest<BrandData>(`/api/v1/brands/${id}`, { method: "PATCH", body, auth: true }),
  deleteBrand: (id: string) => apiRequest<null>(`/api/v1/brands/${id}`, { method: "DELETE", auth: true }),

  // Brand Products
  listBrandProducts: (id: string) => apiRequest<{ list: BrandProductData[] }>(`/api/v1/brands/${id}/products`, { auth: true }),
  createBrandProduct: (id: string, body: { label: string; product_context: string; match_tags?: string[]; placement_url?: string }) =>
    apiRequest<BrandProductData>(`/api/v1/brands/${id}/products`, { method: "POST", body, auth: true }),
  updateBrandProduct: (id: string, productId: string, body: Record<string, unknown>) =>
    apiRequest<BrandProductData>(`/api/v1/brands/${id}/products/${productId}`, { method: "PATCH", body, auth: true }),
  deleteBrandProduct: (id: string, productId: string) =>
    apiRequest<null>(`/api/v1/brands/${id}/products/${productId}`, { method: "DELETE", auth: true }),

  // Knowledge Graph
  expandKnowledgeGraph: (id: string, body: { seed_query: string; supplemental?: boolean; regenerate_map?: boolean; expand_strategy?: string }) =>
    apiRequest<ExpandKnowledgeGraphData>(`/api/v1/brands/${id}/knowledge-graph/expand`, { method: "POST", body, auth: true }),
  getKnowledgeGraph: (id: string) => apiRequest<KnowledgeGraphData>(`/api/v1/brands/${id}/knowledge-graph`, { auth: true }),
  patchKnowledgeGraphNodes: (id: string, body: { updates: Array<{ node_id: string; selected_for_scan?: boolean; relevance_tags?: string[]; recency_tags?: string[] }> }) =>
    apiRequest<KnowledgeGraphData>(`/api/v1/brands/${id}/knowledge-graph/nodes`, { method: "PATCH", body, auth: true }),

  // Scan jobs & posts
  startBrandScan: (id: string, body: Record<string, unknown>) =>
    apiRequest<{ job_id: string; status: string; message?: string }>(`/api/v1/brands/${id}/scan-jobs`, { method: "POST", body, auth: true }),
  listBrandScanPosts: (id: string, params?: { priority?: string; recent_7d?: boolean; product_fit_min?: number; limit?: number }) => {
    const qs = new URLSearchParams();
    if (params?.priority) qs.set("priority", params.priority);
    if (params?.recent_7d) qs.set("recent_7d", "true");
    if (params?.product_fit_min != null) qs.set("product_fit_min", String(params.product_fit_min));
    if (params?.limit) qs.set("limit", String(params.limit));
    const q = qs.toString() ? `?${qs.toString()}` : "";
    return apiRequest<ListBrandScanPostsData>(`/api/v1/brands/${id}/scan-posts${q}`, { auth: true });
  },

  // Outreach
  generateOutreachDrafts: (id: string, body: { scan_post_id: string; topic_id?: string; count?: number; voice_persona_id?: string; product_id?: string }) =>
    apiRequest<GenerateOutreachDraftsData>(`/api/v1/brands/${id}/outreach-drafts/generate`, { method: "POST", body, auth: true }),
  // keep old simple name for PatrolPage (returns any for now)
  generateOutreachDraftsLegacy: (id: string, body: Record<string, unknown>) =>
    apiRequest<Record<string, unknown>>(`/api/v1/brands/${id}/outreach-drafts/generate`, { method: "POST", body, auth: true }),
  publishOutreachDraft: (id: string, body: { scan_post_id: string; text: string; confirm: boolean }) =>
    apiRequest<PublishOutreachDraftData>(`/api/v1/brands/${id}/outreach-drafts/publish`, { method: "POST", body, auth: true }),
  patchScanPostOutreach: (id: string, postId: string, body: { outreach_status?: string }) =>
    apiRequest<ScanPostData>(`/api/v1/brands/${id}/scan-posts/${postId}`, { method: "PATCH", body, auth: true }),

  // Content Matrix
  getBrandContentMatrix: (id: string) => apiRequest<ContentMatrixData>(`/api/v1/brands/${id}/content-matrix`, { auth: true }),
  generateBrandContentMatrix: (id: string, body?: { count?: number }) =>
    apiRequest<ContentMatrixData>(`/api/v1/brands/${id}/content-matrix/generate`, { method: "POST", body: body || {}, auth: true }),

  // Scan Schedule
  getBrandScanSchedule: (id: string) => apiRequest<BrandScanScheduleData>(`/api/v1/brands/${id}/scan-schedule`, { auth: true }),
  upsertBrandScanSchedule: (id: string, body: { cron?: string; timezone?: string; enabled: boolean }) =>
    apiRequest<BrandScanScheduleData>(`/api/v1/brands/${id}/scan-schedule`, { method: "PUT", body, auth: true }),

  // Legacy simple (PatrolPage still uses these names)
  brandScanPosts: (id: string) => apiRequest<{ list: ScanPost[]; total: number }>(`/api/v1/brands/${id}/scan-posts?limit=20`, { auth: true }),

  // Placement Topics (海巡主題) - 主要用於海巡頁：新增主題、爬文、知識圖譜
  placementTopics: () => apiRequest<ListPlacementTopicsData>("/api/v1/placement/topics", { auth: true }),
  createPlacementTopic: (body: { brand_id: string; topic_name: string; seed_query: string; brief: string; product_id?: string }) =>
    apiRequest<PlacementTopicData>("/api/v1/placement/topics", { method: "POST", body, auth: true }),
  getPlacementTopic: (id: string) => apiRequest<PlacementTopicData>(`/api/v1/placement/topics/${id}`, { auth: true }),
  updatePlacementTopic: (id: string, body: Record<string, unknown>) =>
    apiRequest<PlacementTopicData>(`/api/v1/placement/topics/${id}`, { method: "PATCH", body, auth: true }),
  deletePlacementTopic: (id: string) => apiRequest<null>(`/api/v1/placement/topics/${id}`, { method: "DELETE", auth: true }),

  // Placement Topic Knowledge Graph & Scan & Outreach
  expandPlacementTopicGraph: (id: string, body: { seed_query: string; supplemental?: boolean; regenerate_map?: boolean; expand_strategy?: string }) =>
    apiRequest<ExpandKnowledgeGraphData>(`/api/v1/placement/topics/${id}/knowledge-graph/expand`, { method: "POST", body, auth: true }),
  getPlacementTopicGraph: (id: string) => apiRequest<KnowledgeGraphData>(`/api/v1/placement/topics/${id}/knowledge-graph`, { auth: true }),
  patchPlacementTopicGraphNodes: (id: string, body: { updates: Array<{ node_id: string; selected_for_scan?: boolean; relevance_tags?: string[]; recency_tags?: string[] }> }) =>
    apiRequest<KnowledgeGraphData>(`/api/v1/placement/topics/${id}/knowledge-graph/nodes`, { method: "PATCH", body, auth: true }),

  startPlacementTopicScan: (
    id: string,
    body: {
      graph_id?: string;
      node_ids?: string[];
      dual_track?: boolean;
      patrol_mode?: boolean;
      test_patrol?: boolean;
      patrol_keywords?: string[];
    }
  ) =>
    apiRequest<{ job_id: string; status: string; message?: string }>(`/api/v1/placement/topics/${id}/scan-jobs`, { method: "POST", body, auth: true }),
  listPlacementTopicScanPosts: (id: string, params?: { priority?: string; recent_7d?: boolean; product_fit_min?: number; limit?: number }) => {
    const qs = new URLSearchParams();
    if (params?.priority) qs.set("priority", params.priority);
    if (params?.recent_7d) qs.set("recent_7d", "true");
    if (params?.product_fit_min != null) qs.set("product_fit_min", String(params.product_fit_min));
    if (params?.limit) qs.set("limit", String(params.limit));
    const q = qs.toString() ? `?${qs.toString()}` : "";
    return apiRequest<ListBrandScanPostsData>(`/api/v1/placement/topics/${id}/scan-posts${q}`, { auth: true });
  },

  generatePlacementTopicOutreachDrafts: (id: string, body: { scan_post_id: string; count?: number; voice_persona_id?: string; product_id?: string }) =>
    apiRequest<GenerateOutreachDraftsData>(`/api/v1/placement/topics/${id}/outreach-drafts/generate`, { method: "POST", body, auth: true }),
  startPlacementTopicOutreachDraftJobs: (
    id: string,
    body: {
      scan_post_id?: string;
      scan_post_ids?: string[];
      count?: number;
      voice_persona_id: string;
      product_id?: string;
      regenerate?: boolean;
    },
  ) =>
    apiRequest<{ jobs: Array<{ job_id: string; status: string; message: string }>; message: string }>(
      `/api/v1/placement/topics/${id}/outreach-draft-jobs`,
      { method: "POST", body, auth: true },
    ),
  publishPlacementTopicOutreachDraft: (id: string, body: { scan_post_id: string; text: string; confirm: boolean }) =>
    apiRequest<PublishOutreachDraftData>(`/api/v1/placement/topics/${id}/outreach-drafts/publish`, { method: "POST", body, auth: true }),
  updatePlacementTopicOutreachDraft: (topicId: string, draftId: string, body: { draft_index: number; text: string }) =>
    apiRequest<GenerateOutreachDraftsData>(`/api/v1/placement/topics/${topicId}/outreach-drafts/${draftId}`, { method: "PATCH", body, auth: true }),
  deletePlacementTopicScanPost: (topicId: string, postId: string) =>
    apiRequest<null>(`/api/v1/placement/topics/${topicId}/scan-posts/${postId}`, { method: "DELETE", auth: true }),
  batchDeletePlacementTopicScanPosts: (topicId: string, postIds: string[]) =>
    apiRequest<{ deleted_count: number }>(`/api/v1/placement/topics/${topicId}/scan-posts/batch-delete`, { method: "POST", body: { post_ids: postIds }, auth: true }),

  jobs: (page = 1, pageSize = 30) => apiRequest<JobList>(`/api/v1/jobs?page=${page}&pageSize=${pageSize}`, { auth: true }),
  getJob: (id: string) => apiRequest<JobRun>(`/api/v1/jobs/${id}`, { auth: true }),
  jobEvents: (jobId: string, limit = 40) =>
    apiRequest<{ list: JobEvent[] }>(`/api/v1/jobs/${jobId}/events?limit=${limit}`, { auth: true }),
  cancelJob: (id: string) => apiRequest<JobRun>(`/api/v1/jobs/${id}/cancel`, { method: "POST", auth: true }),
  retryJob: (id: string) => apiRequest<JobRun>(`/api/v1/jobs/${id}/retry`, { method: "POST", auth: true }),
  jobSchedules: () => apiRequest<{ list: JobSchedule[]; pagination: Pagination }>("/api/v1/job/schedules?page=1&pageSize=50", { auth: true }),
  settings: (scope: string, scopeId: string) => apiRequest<{ list: SettingValue[]; pagination: Pagination }>(`/api/v1/settings/${scope}/${scopeId}`, { auth: true }),
  permissions: () => apiRequest<unknown>("/api/v1/permissions/me?include_tree=true", { auth: true })
};
