/**
 * Referring Domain Network Estimator
 * -------------------------------------
 * PROXY: This signal estimates referring domain network via search-result-based
 * mention counting. It is intentionally conservative and biased toward
 * high-visibility domains. Upgrade path: integrate dedicated backlink data
 * provider in a future phase.
 *
 * 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 = 8_000;

// Reuse the same tier-1 domain set as editorial-mentions for consistency.
const TIER1_DOMAINS = new Set([
  "nytimes.com", "wsj.com", "washingtonpost.com", "bbc.com", "bbc.co.uk",
  "reuters.com", "bloomberg.com", "ft.com", "theguardian.com", "npr.org",
  "ap.org", "apnews.com", "forbes.com", "businessinsider.com", "cnbc.com",
  "cnn.com", "axios.com", "theatlantic.com", "newyorker.com", "time.com",
  "economist.com", "wired.com", "techcrunch.com", "gov", "edu",
]);

function classifyDomainTier(domain: string): 1 | 2 | 3 {
  const d = domain.toLowerCase();
  if (TIER1_DOMAINS.has(d) || d.endsWith(".gov") || d.endsWith(".edu")) return 1;
  if (/trade|industry|medical|health|tech|law|finance|dive\.com|today\.com/.test(d)) return 2;
  return 3;
}

function apexDomain(url: string): string {
  try {
    return new URL(url).hostname.replace(/^www\./, "");
  } catch {
    return url;
  }
}

export interface ReferringDomainsResult {
  uniqueReferringDomainCount: number;
  tier1ReferringCount: number;
  qualityScore: number; // 0-100
}

export async function estimateReferringDomains(
  brandDomain: string,
): Promise<ReferringDomainsResult> {
  const zero: ReferringDomainsResult = { uniqueReferringDomainCount: 0, tier1ReferringCount: 0, qualityScore: 0 };

  if (!BRAVE_API_KEY) return zero;

  const cleanDomain = brandDomain.replace(/^https?:\/\//, "").replace(/\/$/, "").split("/")[0] ?? brandDomain;

  try {
    const query = encodeURIComponent(`"${cleanDomain}" -site:${cleanDomain}`);
    const url = `https://api.search.brave.com/res/v1/web/search?q=${query}&count=50`;
    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 zero;
    const data = await res.json() as { web?: { results?: Array<{ url: string }> } };
    const results = data?.web?.results ?? [];

    const domains = new Set(results.map((r) => apexDomain(r.url)));
    const domainList = [...domains];
    const tier1Count = domainList.filter((d) => classifyDomainTier(d) === 1).length;
    const tier2Count = domainList.filter((d) => classifyDomainTier(d) === 2).length;
    const tier3Count = domainList.filter((d) => classifyDomainTier(d) === 3).length;
    const total = domainList.length || 1;
    const qualityScore = Math.min(100, Math.round((tier1Count * 100 + tier2Count * 60 + tier3Count * 20) / total));

    return {
      uniqueReferringDomainCount: domainList.length,
      tier1ReferringCount: tier1Count,
      qualityScore,
    };
  } catch (err) {
    console.warn("[referring-domains] estimation failed:", err instanceof Error ? err.message : err);
    return zero;
  }
}
