import { api } from '../api/client'
import type { ExpandStrategy } from '../types/brand'

export type { ExpandStrategy }

export type WebSearchProvider = 'brave' | 'exa'

export type PlacementResearchSettings = {
  web_search_provider: WebSearchProvider
  brave_api_key?: string
  brave_api_key_configured: boolean
  exa_api_key?: string
  exa_api_key_configured: boolean
  brave_country: string
  brave_search_lang: string
  exa_user_location: string
  expand_strategy: ExpandStrategy
}

export const WEB_SEARCH_PROVIDER_OPTIONS: {
  value: WebSearchProvider
  label: string
  hint: string
}[] = [
  {
    value: 'brave',
    label: 'Brave Search',
    hint: '沿用既有 site:threads.net 查詢語法，適合已設定 Brave key 的帳號',
  },
  {
    value: 'exa',
    label: 'Exa Search',
    hint: '神經搜尋 + Threads domain 過濾，適合內容研究與近期貼文發現',
  },
]

export const EXPAND_STRATEGY_OPTIONS: {
  value: ExpandStrategy
  label: string
  hint: string
}[] = [
  {
    value: 'brave',
    label: 'Brave 網路搜尋',
    hint: '優先用手動海巡關鍵字與研究地圖提問，最多約 6 次查詢、每次取 6 筆；夠用會提早停',
  },
  {
    value: 'llm',
    label: 'LLM 推論（省 web search 費用）',
    hint: '不呼叫外部搜尋，由 AI 依研究地圖與產品脈絡直接產生延伸知識；參考連結較少，但可正常海巡',
  },
  {
    value: 'hybrid',
    label: 'Web search + LLM（推薦）',
    hint: '只打約 4 次高價值網路查詢，其餘由 LLM 補廣度；有參考連結又省 API 次數',
  },
]

export function expandStrategyRequiresWebSearch(strategy: ExpandStrategy) {
  return strategy === 'brave' || strategy === 'hybrid'
}

export function expandStrategyRequiresBrave(strategy: ExpandStrategy) {
  return expandStrategyRequiresWebSearch(strategy)
}

export function webSearchKeyReady(settings: PlacementResearchSettings | null | undefined) {
  if (!settings) return false
  if (settings.web_search_provider === 'exa') {
    return !!settings.exa_api_key_configured
  }
  return !!settings.brave_api_key_configured
}

export function expandStrategyLabel(strategy?: string) {
  const found = EXPAND_STRATEGY_OPTIONS.find((item) => item.value === strategy)
  return found?.label ?? (strategy || '未指定')
}

export async function fetchPlacementResearchSettings() {
  return api.get<PlacementResearchSettings>('/api/v1/members/me/placement-settings', { auth: true })
}