/**
 * Keyword → AI Visibility → AI Attribution Pipeline
 * ──────────────────────────────────────────────────
 * Auto-generates AI monitoring queries from tracked keywords and
 * links AI attribution data back to keyword metrics.
 */

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

export function generateAiQueries(keyword: string, city?: string): string[] {
  const queries = [keyword];
  if (city) {
    queries.push(`best ${keyword} in ${city}`);
    queries.push(`${keyword} near me`);
  }
  queries.push(`what is ${keyword}`);
  return queries;
}

export async function getKeywordAiMetrics(brandId: string, since: Date) {
  const [citations, attributions] = await Promise.all([
    prisma.aiCitation.groupBy({
      by: ["keyword"],
      where: { brandId, brandCited: true, checkedAt: { gte: since } },
      _count: true,
    }).catch(() => []),
    prisma.aiAttribution.findMany({
      where: { brandId, timestamp: { gte: since }, queryContext: { not: null } },
      select: { queryContext: true, converted: true, dealValue: true },
    }).catch(() => []),
  ]);

  const citationMap = new Map(citations.map((c) => [c.keyword.toLowerCase(), typeof c._count === "number" ? c._count : 0]));

  // Match attributions to keywords by query context
  const keywordMetrics = new Map<string, { clicks: number; conversions: number; revenue: number }>();
  for (const attr of attributions) {
    const q = (attr.queryContext ?? "").replace(/^\[inferred\]\s*/i, "").toLowerCase();
    if (!q) continue;
    const existing = keywordMetrics.get(q) ?? { clicks: 0, conversions: 0, revenue: 0 };
    existing.clicks++;
    if (attr.converted) existing.conversions++;
    if (attr.dealValue) existing.revenue += attr.dealValue;
    keywordMetrics.set(q, existing);
  }

  return { citationMap, keywordMetrics };
}

export async function getKeywordAiOpportunities(brandId: string, since: Date) {
  const tracked = await prisma.trackedKeyword.findMany({
    where: { brandId, isActive: true },
    select: { keyword: true, rankings: { orderBy: { checkedAt: "desc" }, take: 1, select: { position: true } } },
  }).catch(() => []);

  const cited = await prisma.aiCitation.findMany({
    where: { brandId, brandCited: true, checkedAt: { gte: since } },
    select: { keyword: true },
    distinct: ["keyword"],
  }).catch(() => []);
  const citedSet = new Set(cited.map((c) => c.keyword.toLowerCase()));

  return tracked
    .filter((kw) => !citedSet.has(kw.keyword.toLowerCase()))
    .map((kw) => ({
      keyword: kw.keyword,
      position: kw.rankings[0]?.position ?? null,
      opportunity: "high_volume_no_citation",
    }));
}
