// ─── Result aggregator ────────────────────────────────────────────────────────
// Post-processing pass that enriches EngineQueryResult[] with screenshots
// and builds the final VerificationResult shape.

import { captureAndUploadScreenshot } from "./screenshots/orchestrator";
import { closeBrowser } from "./screenshots/browser-pool";
import { parseCitations, aggregateDomainFrequencies, apexDomain } from "./citation-parser";
import type { EngineQueryResult, VerificationInput, VerificationResult } from "./agent";

export async function attachScreenshots(
  results: EngineQueryResult[],
  brandName: string,
): Promise<EngineQueryResult[]> {
  const enriched = await Promise.all(
    results.map(async (r) => {
      const url = await captureAndUploadScreenshot(r, brandName);
      return url ? { ...r, screenshotUrl: url } : r;
    }),
  );

  await closeBrowser();
  return enriched;
}

export function buildTopCitations(
  results: EngineQueryResult[],
  brandUrl: string,
  competitors: VerificationInput["brandCompetitors"],
): VerificationResult["topCitations"] {
  const allCitations = results.flatMap((r) => parseCitations(r.citations));
  const frequencies = aggregateDomainFrequencies(allCitations);
  const brandApex = apexDomain(brandUrl);
  const competitorApexes = new Set(competitors.map((c) => apexDomain(c.domain)));

  return frequencies.slice(0, 10).map((f) => ({
    domain: f.domain,
    citationCount: f.count,
    isBrandDomain: f.domain === brandApex,
    isCompetitorDomain: competitorApexes.has(f.domain),
  }));
}
