/**
 * AI Strategist LLMO Context
 * ──────────────────────────
 * Builds LLMO intelligence context for the AI Strategist to use
 * when generating recommendations. Pulls from AiAttribution,
 * AiCitation, Content Resonance, and Competitor AI data.
 */

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

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

  const [totalReferrals, conversions, topPlatform, citations, topPage] = await Promise.all([
    prisma.aiAttribution.count({ where: { brandId, timestamp: { gte: d30 } } }).catch(() => 0),
    prisma.aiAttribution.count({ where: { brandId, timestamp: { gte: d30 }, converted: true } }).catch(() => 0),
    prisma.aiAttribution.groupBy({
      by: ["aiPlatform"],
      where: { brandId, timestamp: { gte: d30 } },
      _count: true,
      orderBy: { _count: { aiPlatform: "desc" } },
      take: 1,
    }).catch(() => []),
    prisma.aiCitation.count({ where: { brandId, brandCited: true, checkedAt: { gte: d30 } } }).catch(() => 0),
    prisma.aiAttribution.groupBy({
      by: ["landingPage"],
      where: { brandId, timestamp: { gte: d30 } },
      _count: true,
      orderBy: { _count: { landingPage: "desc" } },
      take: 1,
    }).catch(() => []),
  ]);

  if (totalReferrals === 0 && citations === 0) {
    return "No AI/LLMO attribution data available yet. The Site Tag is set up to detect AI referrals — data will appear once visitors arrive from AI platforms.";
  }

  const convRate = totalReferrals > 0 ? Math.round((conversions / totalReferrals) * 1000) / 10 : 0;
  const platform = topPlatform[0]?.aiPlatform ?? "unknown";
  const page = topPage[0]?.landingPage ?? "unknown";

  const parts = [
    `LLMO/AI Attribution (last 30 days):`,
    `- ${totalReferrals} AI referral visits, ${conversions} conversions (${convRate}% rate)`,
    `- Top AI platform: ${platform}`,
    `- Top AI landing page: ${page}`,
    `- ${citations} keywords where brand is cited in AI responses`,
  ];

  return parts.join("\n");
}
