/**
 * Topic Cluster AI Coverage
 * ─────────────────────────
 * Aggregates AI citation and attribution metrics per topic cluster.
 * Shows which clusters have strong AI coverage and which need optimization.
 */

import { prisma } from "@/lib/prisma";

export interface ClusterAiCoverage {
  keyword: string;
  totalSubtopics: number;
  citedSubtopics: number;
  coverageRate: number;
  totalAiReferrals: number;
  totalAiConversions: number;
  recommendation: string;
}

export async function getClusterAiCoverage(
  brandId: string,
  clusterKeywords: string[],
  since: Date,
): Promise<ClusterAiCoverage> {
  if (clusterKeywords.length === 0) {
    return {
      keyword: "",
      totalSubtopics: 0,
      citedSubtopics: 0,
      coverageRate: 0,
      totalAiReferrals: 0,
      totalAiConversions: 0,
      recommendation: "No keywords in this cluster.",
    };
  }

  const lowerKeywords = clusterKeywords.map((k) => k.toLowerCase());

  const [citations, referrals, conversions] = await Promise.all([
    prisma.aiCitation.findMany({
      where: { brandId, brandCited: true, checkedAt: { gte: since } },
      select: { keyword: true },
      distinct: ["keyword"],
    }).catch(() => []),
    prisma.aiAttribution.count({
      where: { brandId, timestamp: { gte: since } },
    }).catch(() => 0),
    prisma.aiAttribution.count({
      where: { brandId, timestamp: { gte: since }, converted: true },
    }).catch(() => 0),
  ]);

  const citedKeywords = new Set(citations.map((c) => c.keyword.toLowerCase()));
  const citedInCluster = lowerKeywords.filter((k) => citedKeywords.has(k));
  const coverageRate = lowerKeywords.length > 0
    ? Math.round((citedInCluster.length / lowerKeywords.length) * 100)
    : 0;

  let recommendation: string;
  if (coverageRate >= 70) {
    recommendation = "Strong AI coverage. Focus on maintaining citations and improving positions.";
  } else if (coverageRate >= 30) {
    recommendation = `${lowerKeywords.length - citedInCluster.length} uncited keywords in this cluster. Add FAQ schema and structured content to improve coverage.`;
  } else {
    recommendation = `Only ${coverageRate}% AI coverage. Priority: add FAQ sections, schema markup, and interlink cluster pages.`;
  }

  return {
    keyword: clusterKeywords[0] ?? "",
    totalSubtopics: lowerKeywords.length,
    citedSubtopics: citedInCluster.length,
    coverageRate,
    totalAiReferrals: referrals,
    totalAiConversions: conversions,
    recommendation,
  };
}
