/**
 * 測試 Brave Search API 是否正常。
 * 用法：npx tsx scripts/test-web-search.ts
 */
import { config } from "dotenv";
import {
  detectLegacySearchEnvKeys,
  isBraveSearchConfigured,
  searchWebThorough,
} from "../lib/services/web-search";

config();

const sampleQuery = 'site:threads.com 狗洗澡 求推薦';

async function main() {
  console.log("=== 網路搜尋 API 健檢 ===\n");

  const legacy = detectLegacySearchEnvKeys();
  if (legacy.length > 0) {
    console.log("⚠ 偵測到已停用的搜尋 API 環境變數（將被忽略）：");
    for (const key of legacy) console.log(`  - ${key}`);
    console.log("  請改為僅使用 BRAVE_SEARCH_API_KEY\n");
  }

  console.log("BRAVE_SEARCH:", isBraveSearchConfigured() ? "已設定" : "未設定");
  console.log("測試查詢:", sampleQuery, "\n");

  if (!isBraveSearchConfigured()) {
    console.log("未設定 BRAVE_SEARCH_API_KEY");
    console.log("  取得方式：https://api-dashboard.search.brave.com/");
    console.log("  海巡仍可用 Threads API／瀏覽器爬蟲，Brave 僅作補充");
    return;
  }

  const t0 = Date.now();
  const thorough = await searchWebThorough(sampleQuery, 3);
  const ms = Date.now() - t0;

  if (thorough.results.length > 0) {
    console.log(`✓ Brave Search 正常（${ms}ms，${thorough.results.length} 筆）`);
    console.log("  範例:", thorough.results[0].title?.slice(0, 50));
  } else {
    console.log(`✗ Brave Search 無結果或失敗（${ms}ms）`);
    console.log("  請確認 API key 與額度：https://api-dashboard.search.brave.com/");
  }

  console.log("\n來源:", thorough.providerLabel);
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});