/**
 * Industry Directory Listings Detector
 * ---------------------------------------
 * Checks brand presence across vertical-appropriate industry directories.
 * Uses Brave Search with site: queries. Results use category labels only in
 * customer-facing output; raw domain names stay in rawSignalData.
 *
 * Internal module -- vendor names permitted in code; forbidden in user-facing output.
 */

const BRAVE_API_KEY = process.env.BRAVE_SEARCH_API_KEY ?? "";
const TIMEOUT_MS = 6_000;
const MAX_DIRECTORIES = 8; // cost control

interface DirectoryEntry {
  domain: string;
  category: string; // customer-facing category label, no domain surfaced
}

const DIRECTORY_MAP: Record<string, DirectoryEntry[]> = {
  "healthcare-medical": [
    { domain: "vitals.com",      category: "healthcare review platform" },
    { domain: "healthgrades.com", category: "healthcare review platform" },
    { domain: "zocdoc.com",      category: "healthcare booking platform" },
    { domain: "ratemds.com",     category: "healthcare review platform" },
    { domain: "webmd.com",       category: "medical reference platform" },
  ],
  "healthcare": [
    { domain: "vitals.com",      category: "healthcare review platform" },
    { domain: "healthgrades.com", category: "healthcare review platform" },
    { domain: "zocdoc.com",      category: "healthcare booking platform" },
    { domain: "ratemds.com",     category: "healthcare review platform" },
    { domain: "webmd.com",       category: "medical reference platform" },
  ],
  "local-services": [
    { domain: "yelp.com",        category: "consumer review platform" },
    { domain: "bbb.org",         category: "consumer protection directory" },
    { domain: "angi.com",        category: "home services directory" },
    { domain: "thumbtack.com",   category: "service marketplace" },
    { domain: "nextdoor.com",    category: "neighborhood community platform" },
  ],
  "b2b-saas": [
    { domain: "g2.com",          category: "B2B review platform" },
    { domain: "capterra.com",    category: "software directory" },
    { domain: "trustradius.com", category: "B2B review platform" },
    { domain: "crunchbase.com",  category: "business intelligence platform" },
    { domain: "clutch.co",       category: "agency directory" },
  ],
  "ecommerce": [
    { domain: "trustpilot.com",       category: "consumer review platform" },
    { domain: "sitejabber.com",       category: "consumer review platform" },
    { domain: "resellerratings.com",  category: "consumer review platform" },
  ],
  "legal": [
    { domain: "avvo.com",        category: "legal directory" },
    { domain: "martindale.com",  category: "legal directory" },
    { domain: "findlaw.com",     category: "legal reference platform" },
    { domain: "justia.com",      category: "legal reference platform" },
  ],
  "real-estate": [
    { domain: "zillow.com",      category: "real estate platform" },
    { domain: "realtor.com",     category: "real estate directory" },
    { domain: "trulia.com",      category: "real estate platform" },
  ],
  "general": [
    { domain: "bbb.org",         category: "consumer protection directory" },
    { domain: "trustpilot.com",  category: "consumer review platform" },
  ],
};

async function checkDirectoryPresence(
  directory: DirectoryEntry,
  brandName: string,
): Promise<boolean> {
  if (!BRAVE_API_KEY) return false;
  try {
    const query = encodeURIComponent(`site:${directory.domain} "${brandName}"`);
    const url = `https://api.search.brave.com/res/v1/web/search?q=${query}&count=5`;
    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 false;
    const data = await res.json() as { web?: { results?: unknown[] } };
    return (data?.web?.results?.length ?? 0) > 0;
  } catch {
    return false;
  }
}

export interface DirectoryListingsResult {
  totalChecked: number;
  totalFound: number;
  foundDirectoryCategories: string[]; // deduplicated category labels, no domain names
}

export async function detectDirectoryListings(
  brandName: string,
  vertical: string,
): Promise<DirectoryListingsResult> {
  const directoryList = (DIRECTORY_MAP[vertical] ?? DIRECTORY_MAP["general"]!).slice(0, MAX_DIRECTORIES);

  const results = await Promise.allSettled(
    directoryList.map((dir) => checkDirectoryPresence(dir, brandName)),
  );

  const foundCategories: string[] = [];
  for (let i = 0; i < results.length; i++) {
    const r = results[i]!;
    if (r.status === "fulfilled" && r.value) {
      const cat = directoryList[i]!.category;
      if (!foundCategories.includes(cat)) foundCategories.push(cat);
    }
  }

  return {
    totalChecked: directoryList.length,
    totalFound: foundCategories.length,
    foundDirectoryCategories: foundCategories,
  };
}
