/**
 * Branded Search Demand Estimator
 * ---------------------------------
 * Estimates branded search demand using Wikipedia pageviews as primary signal
 * (when available) or Brave Search result count as a proxy fallback.
 *
 * Internal module -- vendor names permitted in code; forbidden in user-facing output.
 */

import { getWikipediaPageviews } from "./wikipedia-pageviews";

const BRAVE_API_KEY = process.env.BRAVE_SEARCH_API_KEY ?? "";
const TIMEOUT_MS = 8_000;

export type DemandTier = "high" | "moderate" | "low" | "minimal";

export interface BrandedSearchDemandResult {
  demandTier: DemandTier;
  proxyMetric: number;
  source: "pageviews" | "search_volume_proxy";
}

function classifyPageviewTier(avgDaily: number, vertical: string): DemandTier {
  const isHighVolume = ["b2b-saas", "ecommerce"].includes(vertical);
  if (isHighVolume) {
    if (avgDaily > 2000) return "high";
    if (avgDaily > 500)  return "moderate";
    if (avgDaily > 100)  return "low";
    return "minimal";
  }
  // healthcare / local-services / others -- lower absolute volumes expected
  if (avgDaily > 500)  return "high";
  if (avgDaily > 100)  return "moderate";
  if (avgDaily > 20)   return "low";
  return "minimal";
}

function classifyProxyTier(resultCount: number, vertical: string): DemandTier {
  const isHighVolume = ["b2b-saas", "ecommerce"].includes(vertical);
  if (isHighVolume) {
    if (resultCount > 50_000) return "high";
    if (resultCount > 10_000) return "moderate";
    if (resultCount > 2_000)  return "low";
    return "minimal";
  }
  if (resultCount > 10_000) return "high";
  if (resultCount > 2_000)  return "moderate";
  if (resultCount > 500)    return "low";
  return "minimal";
}

export async function estimateBrandedSearchDemand(
  brandName: string,
  hasWikipediaPage: boolean,
  wikipediaPageTitle: string | null,
  vertical: string,
): Promise<BrandedSearchDemandResult> {
  // Primary: Wikipedia pageviews
  if (hasWikipediaPage && wikipediaPageTitle) {
    const pv = await getWikipediaPageviews(wikipediaPageTitle).catch(() => null);
    if (pv) {
      return {
        demandTier: classifyPageviewTier(pv.avgDailyPageviews, vertical),
        proxyMetric: pv.avgDailyPageviews,
        source: "pageviews",
      };
    }
  }

  // Fallback: Brave Search result count
  if (!BRAVE_API_KEY) {
    return { demandTier: "minimal", proxyMetric: 0, source: "search_volume_proxy" };
  }
  try {
    const query = encodeURIComponent(`"${brandName}"`);
    const url = `https://api.search.brave.com/res/v1/web/search?q=${query}&count=1`;
    const res = await Promise.race([
      fetch(url, {
        headers: {
          "Accept": "application/json",
          "X-Subscription-Token": BRAVE_API_KEY,
        },
      }),
      new Promise<Response>((_, reject) => setTimeout(() => reject(new Error("timeout")), TIMEOUT_MS)),
    ]);
    if (!res.ok) return { demandTier: "minimal", proxyMetric: 0, source: "search_volume_proxy" };
    const data = await res.json() as { web?: { totalCount?: number } };
    const total = data?.web?.totalCount ?? 0;
    return {
      demandTier: classifyProxyTier(total, vertical),
      proxyMetric: total,
      source: "search_volume_proxy",
    };
  } catch (err) {
    console.warn("[branded-search-demand] estimation failed:", err instanceof Error ? err.message : err);
    return { demandTier: "minimal", proxyMetric: 0, source: "search_volume_proxy" };
  }
}
