/**
 * LLMO Content Brief Trigger
 * ──────────────────────────
 * Detects keywords that need content optimisation and creates
 * AiRecommendation records with type='content_brief_trigger'.
 * Briefs are ALWAYS created as drafts — never auto-published.
 */

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

export interface BriefTrigger {
  keyword: string;
  triggerReason: string;
  briefType: "new_content" | "optimize_existing" | "format_rewrite";
  priority: "high" | "medium" | "low";
  targetPage: string | null;
  dataPoints: {
    aiCitations: number;
    aiClicks: number;
    aiConversions: number;
    competitorsCited: string[];
    recommendedFormat: string;
  };
}

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

  const [r1, r2, r3, r4] = await Promise.allSettled([
    detectHighCitationLowClick(brandId, d30),
    detectCompetitorCitedBrandNot(brandId, d30),
    detectHighTrafficLowConversion(brandId, d30),
    detectQueryWithNoContent(brandId, d30),
  ]);

  for (const r of [r1, r2, r3, r4]) {
    if (r.status === "fulfilled") created += r.value;
  }

  return created;
}

// ─── Trigger: High Citations, Low Clicks ───────────────────────────────────

async function detectHighCitationLowClick(brandId: string, since: Date): Promise<number> {
  let count = 0;

  const citedKeywords = await prisma.aiCitation.findMany({
    where: { brandId, brandCited: true, checkedAt: { gte: since } },
    select: { keyword: true, citedUrl: true, citedSnippet: true },
  });

  const keywordCitations = new Map<string, { url: string | null; snippet: string | null; count: number }>();
  for (const c of citedKeywords) {
    const entry = keywordCitations.get(c.keyword) ?? { url: c.citedUrl, snippet: c.citedSnippet, count: 0 };
    entry.count++;
    keywordCitations.set(c.keyword, entry);
  }

  for (const [keyword, citation] of keywordCitations) {
    const clicks = await prisma.aiAttribution.count({
      where: {
        brandId,
        timestamp: { gte: since },
        queryContext: { contains: keyword.split(" ")[0] },
      },
    }).catch(() => 0);

    if (citation.count >= 2 && clicks <= 3) {
      const exists = await prisma.aiRecommendation.findFirst({
        where: {
          brandId,
          type: "content_brief_trigger",
          status: { in: ["pending", "in_progress"] },
          title: { contains: keyword.slice(0, 30) },
        },
        select: { id: true },
      });
      if (exists) continue;

      await prisma.aiRecommendation.create({
        data: {
          brandId,
          type: "content_brief_trigger",
          priority: "high",
          title: `Cited for "${keyword}" but few clicks — optimise for click-through`,
          insight: `You're cited in AI responses for "${keyword}" (${citation.count} citations) but only received ${clicks} clicks. The cited snippet may not be compelling enough.`,
          action: `Optimise the content at ${citation.url ?? "your target page"}: add a stronger CTA in the first paragraph, include specific differentiators, and add a patient testimonial or case study.`,
          impact: "Improving AI click-through rate from citation to visit typically doubles AI traffic for the keyword.",
          dataPoints: JSON.parse(JSON.stringify({
            keyword,
            citations: citation.count,
            clicks,
            citedUrl: citation.url,
            citedSnippet: citation.snippet,
            briefType: "optimize_existing",
            recommendedFormat: "FAQ with strong CTA",
          })),
          relatedKeywords: JSON.parse(JSON.stringify([keyword])),
          relatedPages: JSON.parse(JSON.stringify(citation.url ? [citation.url] : [])),
        },
      }).catch(() => null);
      count++;
    }

    if (count >= 3) break;
  }

  return count;
}

// ─── Trigger: Competitor Cited, Brand Not ──────────────────────────────────

async function detectCompetitorCitedBrandNot(brandId: string, since: Date): Promise<number> {
  let count = 0;

  const uncitedKeywords = await prisma.aiCitation.findMany({
    where: { brandId, brandCited: false, checkedAt: { gte: since } },
    select: { keyword: true, competitorsCited: true },
  });

  const byKeyword = new Map<string, string[]>();
  for (const c of uncitedKeywords) {
    const competitors = Array.isArray(c.competitorsCited)
      ? (c.competitorsCited as Array<{ domain?: string }>).map((cc) => cc.domain).filter(Boolean) as string[]
      : [];
    if (competitors.length > 0) {
      const existing = byKeyword.get(c.keyword) ?? [];
      existing.push(...competitors);
      byKeyword.set(c.keyword, [...new Set(existing)]);
    }
  }

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

    await prisma.aiRecommendation.create({
      data: {
        brandId,
        type: "content_brief_trigger",
        priority: "high",
        title: `Competitor cited for "${keyword}" — you're not`,
        insight: `${competitors[0]} is cited in AI responses for "${keyword}" but you are not. This is a content gap that competitors are exploiting.`,
        action: `Create or rewrite content targeting "${keyword}" in FAQ/structured format with comprehensive coverage (2,000+ words) and schema markup.`,
        impact: "Closing competitor citation gaps is the highest-ROI LLMO optimisation.",
        dataPoints: JSON.parse(JSON.stringify({
          keyword,
          competitorsCited: competitors.slice(0, 5),
          briefType: "format_rewrite",
          recommendedFormat: "Comprehensive FAQ with schema markup",
        })),
        relatedKeywords: JSON.parse(JSON.stringify([keyword])),
      },
    }).catch(() => null);
    count++;
    if (count >= 3) break;
  }

  return count;
}

// ─── Trigger: High AI Traffic, Low Conversion ─────────────────────────────

async function detectHighTrafficLowConversion(brandId: string, since: Date): Promise<number> {
  let count = 0;

  const pages = await prisma.aiAttribution.groupBy({
    by: ["landingPage"],
    where: { brandId, timestamp: { gte: since } },
    _count: true,
    orderBy: { _count: { landingPage: "desc" } },
    take: 10,
  }).catch(() => []);

  const convByPage = await prisma.aiAttribution.groupBy({
    by: ["landingPage"],
    where: { brandId, timestamp: { gte: since }, converted: true },
    _count: true,
  }).catch(() => []);
  const convMap = new Map(convByPage.map((r) => [r.landingPage, typeof r._count === "number" ? r._count : 0]));

  for (const page of pages) {
    const visits = typeof page._count === "number" ? page._count : 0;
    if (visits < 10) continue;

    const conversions = convMap.get(page.landingPage) ?? 0;
    const rate = visits > 0 ? conversions / visits : 0;
    if (rate >= 0.1) continue;

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

    await prisma.aiRecommendation.create({
      data: {
        brandId,
        type: "content_brief_trigger",
        priority: "medium",
        title: `High AI traffic, low conversion on ${page.landingPage}`,
        insight: `${page.landingPage} receives ${visits} AI referrals/month but only ${conversions} conversions (${Math.round(rate * 100)}%). AI visitors are arriving but not converting.`,
        action: "Add inline appointment/contact form, sticky phone CTA in first viewport, and insurance FAQ section. Pages with these elements convert AI visitors at 3x higher rate.",
        impact: `Improving to 15% conversion could add ~${Math.round(visits * 0.15 - conversions)} conversions/month.`,
        dataPoints: JSON.parse(JSON.stringify({
          page: page.landingPage,
          aiVisits: visits,
          conversions,
          convRate: Math.round(rate * 1000) / 10,
          briefType: "optimize_existing",
          recommendedFormat: "Add conversion elements",
        })),
        relatedPages: JSON.parse(JSON.stringify([page.landingPage])),
      },
    }).catch(() => null);
    count++;
    if (count >= 2) break;
  }

  return count;
}

// ─── Trigger: AI Query With No Content ─────────────────────────────────────

async function detectQueryWithNoContent(brandId: string, since: Date): Promise<number> {
  let count = 0;

  const queries = await prisma.aiAttribution.findMany({
    where: { brandId, timestamp: { gte: since }, 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 sorted = [...queryGroups.entries()].sort((a, b) => b[1] - a[1]);

  for (const [query, queryCount] of sorted.slice(0, 5)) {
    if (queryCount < 5) continue;

    const matchingPages = await prisma.aiAttribution.findMany({
      where: { brandId, timestamp: { gte: since }, queryContext: { contains: query.split(" ")[0] } },
      select: { landingPage: true },
      distinct: ["landingPage"],
      take: 3,
    }).catch(() => []);

    if (matchingPages.length >= 2) continue;

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

    await prisma.aiRecommendation.create({
      data: {
        brandId,
        type: "content_brief_trigger",
        priority: "medium",
        title: `Create content for AI query: "${query}"`,
        insight: `AI users are searching for "${query}" (${queryCount} queries this month) but you don't have dedicated content for this topic.`,
        action: `Create a comprehensive page targeting "${query}" with FAQ structure, schema markup, and strong conversion elements.`,
        dataPoints: JSON.parse(JSON.stringify({
          query,
          queryCount,
          briefType: "new_content",
          recommendedFormat: "FAQ-structured page with schema markup",
        })),
        relatedKeywords: JSON.parse(JSON.stringify([query])),
      },
    }).catch(() => null);
    count++;
    if (count >= 2) break;
  }

  return count;
}
