import { verifyAiSearchVisibility } from "../../ai-search-verification/agent";
import type { VerificationInput, VerificationResult } from "../../ai-search-verification/agent";
import type { AiSearchVerification } from "../types";
import type { IndustryContext } from "../synthesizers/industry-classifier";

export interface AiSearchVerificationInput {
  brandName: string;
  brandUrl: string;
  brandLocation?: string;
  industryContext: IndustryContext | null | undefined;
  competitors: string[];
}

export async function aggregateAiSearchVerification(
  input: AiSearchVerificationInput,
): Promise<AiSearchVerification | null> {
  const queries = input.industryContext?.suggestedQueries ?? [];
  if (!queries.length) return null;

  const verificationInput: VerificationInput = {
    brandName: input.brandName,
    brandUrl: input.brandUrl,
    industryVertical: input.industryContext?.industry ?? "general",
    trackedQueries: queries,
    brandCompetitors: input.competitors
      .slice(0, 5)
      .map((domain) => ({ name: domain, domain })),
    brandLocation: input.brandLocation,
  };

  const result = await verifyAiSearchVisibility(verificationInput);

  return {
    ...result,
    auditContextNarrative: buildNarrative(result.brandVisibility, input.brandName),
    comparisonToPredictions: buildComparison(result, input),
  };
}

function buildNarrative(
  visibility: VerificationResult["brandVisibility"],
  brandName: string,
): string {
  const pct = (r: number) => `${Math.round(r * 100)}%`;
  const lines: string[] = [];

  lines.push(
    `Across all AI search engines tested, ${brandName} appeared in ${pct(visibility.overallMentionRate)} of responses, ` +
      `with a citation rate of ${pct(visibility.overallCitationRate)}.`,
  );

  if (visibility.brandedQueryMentionRate < 0.6) {
    lines.push(
      `Brand-specific queries returned mentions only ${pct(visibility.brandedQueryMentionRate)} of the time, ` +
        `indicating weak entity recognition across AI platforms.`,
    );
  }

  if (visibility.nonBrandedMentionRate < 0.2) {
    lines.push(
      `Non-branded category queries rarely surface ${brandName}, ` +
        `suggesting competitors dominate AI-generated recommendations.`,
    );
  }

  if (visibility.overallMentionRate > 0.5) {
    lines.push(
      `Overall AI search visibility is strong — ${brandName} maintains meaningful presence across most query types.`,
    );
  }

  return lines.join(" ");
}

function buildComparison(
  result: VerificationResult,
  input: AiSearchVerificationInput,
): string {
  if (result.degraded) {
    return `Results are partial — ${result.failedEngines.length} engine(s) were unavailable during verification. Figures reflect successful engines only.`;
  }

  const mentionPct = Math.round(result.brandVisibility.overallMentionRate * 100);

  if (mentionPct >= 50) {
    return `AI search visibility aligns with or exceeds expectations for the ${input.industryContext?.industry ?? "industry"} vertical, suggesting strong content authority signals.`;
  }

  if (mentionPct >= 20) {
    return `AI visibility is moderate for this industry. Competitors likely have stronger entity presence in AI training data, requiring targeted content authority building.`;
  }

  return `AI visibility is below expectations. This is consistent with lower domain authority scores and suggests the site lacks sufficient E-E-A-T signals for AI engine citation.`;
}
