/**
 * Content Resonance Scoring
 * ─────────────────────────
 * Compares how AI-referred visitors engage with pages vs organic visitors.
 * Identifies which content formats and pages perform best with AI traffic.
 */

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

export interface ContentResonance {
  pageUrl: string;
  aiVisits: number;
  aiConvRate: number;
  aiAvgEngagement: number;
  organicVisits: number;
  organicConvRate: number;
  resonanceScore: number;
  aiLift: number;
  recommendation: string;
}

export async function calculateContentResonance(
  brandId: string,
  from: Date,
): Promise<ContentResonance[]> {
  // Get AI attribution data grouped by landing page
  const aiByPage = await prisma.aiAttribution.groupBy({
    by: ["landingPage"],
    where: { brandId, timestamp: { gte: from } },
    _count: true,
    _avg: { engagementScore: true },
    orderBy: { _count: { landingPage: "desc" } },
    take: 20,
  }).catch(() => []);

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

  // Get organic session data for the same pages
  const site = await prisma.trackedSite.findUnique({
    where: { brandId },
    select: { id: true },
  });

  const results: ContentResonance[] = [];

  for (const page of aiByPage) {
    const aiVisits = typeof page._count === "number" ? page._count : 0;
    if (aiVisits < 2) continue;

    const aiConversions = aiConvMap.get(page.landingPage) ?? 0;
    const aiConvRate = aiVisits > 0 ? Math.round((aiConversions / aiVisits) * 1000) / 10 : 0;
    const aiAvgEngagement = Math.round(page._avg.engagementScore ?? 0);

    // Count organic sessions landing on this page
    let organicVisits = 0;
    let organicConversions = 0;
    if (site) {
      organicVisits = await prisma.trackedSession.count({
        where: {
          trackedSiteId: site.id,
          entryPage: page.landingPage,
          startedAt: { gte: from },
        },
      }).catch(() => 0);

      // intentionally unfiltered: AI content analysis; organic vs paid comparison needs all rows
      organicConversions = await prisma.siteConversion.count({
        where: {
          brandId,
          pageUrl: page.landingPage,
          timestamp: { gte: from },
        },
      }).catch(() => 0);
    }

    const organicConvRate = organicVisits > 0 ? Math.round((organicConversions / organicVisits) * 1000) / 10 : 0;
    const aiLift = organicConvRate > 0 ? Math.round((aiConvRate / organicConvRate) * 10) / 10 : (aiConvRate > 0 ? 99 : 0);

    // Composite resonance score
    const convRateWeight = aiConvRate > organicConvRate ? 40 : 10;
    const engagementWeight = aiAvgEngagement > 50 ? 30 : 15;
    const volumeWeight = Math.min(aiVisits, 20) * 1;
    const resonanceScore = Math.min(100, Math.round(convRateWeight + engagementWeight + volumeWeight));

    // Generate recommendation
    let recommendation: string;
    if (aiLift >= 2) {
      recommendation = `AI visitors convert ${aiLift}x better on this page — replicate this content format for other pages.`;
    } else if (aiVisits > 10 && aiConvRate < 5) {
      recommendation = "High AI traffic but low conversion — add clearer CTAs and contact forms.";
    } else if (aiVisits > 5) {
      recommendation = "Performing well with AI traffic. Monitor and optimize.";
    } else {
      recommendation = "Early data — continue monitoring.";
    }

    results.push({
      pageUrl: page.landingPage,
      aiVisits,
      aiConvRate,
      aiAvgEngagement,
      organicVisits,
      organicConvRate,
      resonanceScore,
      aiLift,
      recommendation,
    });
  }

  return results.sort((a, b) => b.resonanceScore - a.resonanceScore);
}
