/** 海巡搜尋來源模式（每帳號設定） */
export type SearchSourceMode =
  | "mixed"
  | "threads"
  | "brave"
  | "crawler"
  | "threads_brave"
  | "threads_crawler"
  | "brave_crawler";

export const DEFAULT_SEARCH_SOURCE_MODE: SearchSourceMode = "mixed";

export const SEARCH_SOURCE_MODE_OPTIONS: Array<{
  value: SearchSourceMode;
  label: string;
  hint: string;
}> = [
  {
    value: "mixed",
    label: "混合模式",
    hint: "Threads API → Brave → 爬蟲（推薦）",
  },
  {
    value: "threads",
    label: "Threads API",
    hint: "僅官方 API 關鍵字搜尋",
  },
  {
    value: "brave",
    label: "Brave Search",
    hint: "僅 Brave 網搜 Threads 貼文",
  },
  {
    value: "crawler",
    label: "瀏覽器爬蟲",
    hint: "僅 Playwright 站內搜尋",
  },
  {
    value: "threads_brave",
    label: "API + Brave",
    hint: "Threads API 不足時用 Brave，不爬蟲",
  },
  {
    value: "threads_crawler",
    label: "API + 爬蟲",
    hint: "Threads API 不足時用瀏覽器，不用 Brave",
  },
  {
    value: "brave_crawler",
    label: "Brave + 爬蟲",
    hint: "Brave 不足時用瀏覽器補漏",
  },
];

export function parseSearchSourceMode(value: string | null | undefined): SearchSourceMode {
  const valid = SEARCH_SOURCE_MODE_OPTIONS.map((o) => o.value);
  if (value && valid.includes(value as SearchSourceMode)) {
    return value as SearchSourceMode;
  }
  return DEFAULT_SEARCH_SOURCE_MODE;
}

export function modeAllowsThreads(mode: SearchSourceMode): boolean {
  return (
    mode === "mixed" ||
    mode === "threads" ||
    mode === "threads_brave" ||
    mode === "threads_crawler"
  );
}

export function modeAllowsBrave(mode: SearchSourceMode): boolean {
  return (
    mode === "mixed" ||
    mode === "brave" ||
    mode === "threads_brave" ||
    mode === "brave_crawler"
  );
}

export function modeAllowsCrawler(mode: SearchSourceMode): boolean {
  return (
    mode === "mixed" ||
    mode === "crawler" ||
    mode === "threads_crawler" ||
    mode === "brave_crawler"
  );
}

export function searchSourceModeLabel(mode: SearchSourceMode): string {
  return SEARCH_SOURCE_MODE_OPTIONS.find((o) => o.value === mode)?.label ?? mode;
}