/**
 * Auto-Query Expansion
 * ────────────────────
 * Discovers related queries from converting keywords and captured
 * AI query data. Adds them as AiRecommendation records for the
 * user to review and approve.
 */

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

interface ExpandedQuery {
  query: string;
  source: "converting_keyword" | "captured_query";
  sourceKeyword: string;
  estimatedVolume: number | null;
}

export async function expandConvertingQueries(brandId: string): Promise<number> {
  const d30 = new Date(Date.now() - 30 * 86_400_000);
  let created = 0;

  const convertingKeywords = await prisma.aiAttribution.groupBy({
    by: ["queryContext"],
    where: { brandId, timestamp: { gte: d30 }, converted: true, queryContext: { not: null } },
    _count: true,
    orderBy: { _count: { queryContext: "desc" } },
    take: 10,
  }).catch(() => []);

  for (const kw of convertingKeywords) {
    const keyword = kw.queryContext?.replace(/^\[inferred\]\s*/i, "").toLowerCase().trim();
    if (!keyword || keyword.length < 5) continue;

    const expansions = generateExpansions(keyword);
    if (expansions.length === 0) continue;

    const existing = await prisma.aiRecommendation.findFirst({
      where: {
        brandId,
        type: "query_expansion",
        status: { in: ["pending", "in_progress"] },
        title: { contains: keyword.slice(0, 30) },
      },
      select: { id: true },
    });
    if (existing) continue;

    await prisma.aiRecommendation.create({
      data: {
        brandId,
        type: "query_expansion",
        priority: "medium",
        title: `Expand monitoring for "${keyword}" (${expansions.length} related queries)`,
        insight: `"${keyword}" is generating conversions from AI traffic. ${expansions.length} related query variants could capture additional AI referrals.`,
        action: `Add these query variants to AI Visibility monitoring and Keyword Research: ${expansions.slice(0, 5).join(", ")}`,
        impact: `Converting keywords typically have 3-5x more discoverable long-tail variants.`,
        dataPoints: JSON.parse(JSON.stringify({
          sourceKeyword: keyword,
          conversions: typeof kw._count === "number" ? kw._count : 0,
          expansions,
        })),
        relatedKeywords: JSON.parse(JSON.stringify([keyword, ...expansions.slice(0, 10)])),
      },
    }).catch(() => null);
    created++;
  }

  return created;
}

export async function expandFromCapturedQueries(brandId: string): Promise<number> {
  const d30 = new Date(Date.now() - 30 * 86_400_000);
  let created = 0;

  const queries = await prisma.aiAttribution.findMany({
    where: { brandId, timestamp: { gte: d30 }, queryContext: { not: null } },
    select: { queryContext: true },
  });

  const queryGroups = new Map<string, number>();
  for (const q of queries) {
    if (!q.queryContext) continue;
    const normalized = q.queryContext.replace(/^\[inferred\]\s*/i, "").toLowerCase().trim();
    if (normalized.length < 5) continue;
    queryGroups.set(normalized, (queryGroups.get(normalized) ?? 0) + 1);
  }

  const modifiers = extractCommonModifiers(queryGroups);
  if (modifiers.length === 0) return 0;

  const existing = await prisma.aiRecommendation.findFirst({
    where: {
      brandId,
      type: "query_expansion",
      status: { in: ["pending", "in_progress"] },
      title: { contains: "query patterns" },
    },
    select: { id: true },
  });
  if (existing) return 0;

  await prisma.aiRecommendation.create({
    data: {
      brandId,
      type: "query_expansion",
      priority: "low",
      title: `${modifiers.length} common query patterns detected from AI traffic`,
      insight: `AI users frequently add modifiers like "${modifiers.slice(0, 3).join('", "')}" to queries. Monitoring these patterns could uncover more AI traffic opportunities.`,
      action: `Review captured query patterns and add high-value variants to your keyword monitoring.`,
      dataPoints: JSON.parse(JSON.stringify({
        modifiers,
        totalQueries: queries.length,
        uniqueQueries: queryGroups.size,
      })),
      relatedKeywords: JSON.parse(JSON.stringify(modifiers.slice(0, 10))),
    },
  }).catch(() => null);
  created++;

  return created;
}

// ─── Helpers ───────────────────────────────────────────────────────────────

function generateExpansions(keyword: string): string[] {
  const parts = keyword.split(/\s+/);
  const core = parts.slice(0, 4).join(" ");
  const expansions = new Set<string>();

  const suffixes = ["cost", "insurance", "near me", "reviews", "recovery time", "side effects"];
  const prefixes = ["best", "how much does", "is"];

  for (const suffix of suffixes) {
    const exp = `${core} ${suffix}`;
    if (exp !== keyword) expansions.add(exp);
  }

  for (const prefix of prefixes) {
    const exp = `${prefix} ${core}`;
    if (exp !== keyword) expansions.add(exp);
  }

  return [...expansions].slice(0, 15);
}

function extractCommonModifiers(queries: Map<string, number>): string[] {
  const modifierCounts = new Map<string, number>();

  for (const [query, count] of queries) {
    const words = query.split(/\s+/);
    const modifiers = ["cost", "price", "insurance", "near me", "reviews", "best", "vs", "how", "what", "recovery", "side effects"];
    for (const mod of modifiers) {
      if (query.includes(mod)) {
        modifierCounts.set(mod, (modifierCounts.get(mod) ?? 0) + count);
      }
    }
  }

  return [...modifierCounts.entries()]
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10)
    .map(([mod]) => mod);
}
