/**
 * AI Attribution Engine
 * ─────────────────────
 * Creates and updates AiAttribution records for the full LLMO/GEO/AEO
 * funnel: citation → click → engagement → conversion → outcome.
 *
 * Called from:
 *   - /api/collect (when eventType === 'ai_referral')
 *   - /api/site-tag/conversion (when session has AI attribution)
 *   - /api/cron/ai-citation-check (when DataForSEO detects citations)
 */

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

/**
 * Infer a readable query from a landing page URL slug.
 * Fast, requires no API calls, always returns something useful.
 * Prefixed with "[inferred]" so downstream consumers can distinguish
 * from captured queries.
 */
export function inferQueryFromLandingPage(landingPage: string): string {
  try {
    const pathname = landingPage.startsWith("http")
      ? new URL(landingPage).pathname
      : landingPage;
    const segments = pathname.split("/").filter(Boolean);
    // Skip language prefixes (es, en, fr, de, pt, etc.)
    const meaningful = segments.filter((s) => s.length > 2 && !/^[a-z]{2}$/.test(s));
    const slug = meaningful[meaningful.length - 1] ?? "";
    if (!slug) return "[inferred] site visit";
    const readable = slug
      .replace(/[-_]/g, " ")
      .replace(/\s+/g, " ")
      .trim();
    return `[inferred] ${readable}`.slice(0, 500);
  } catch {
    return "[inferred] site visit";
  }
}

export async function createAiAttribution(args: {
  brandId: string;
  sessionId: string;
  platform: string;
  channel: string;
  referrerUrl?: string;
  queryContext?: string;
  landingPage: string;
}): Promise<void> {
  try {
    const captured = args.queryContext?.trim();
    const queryContext = captured
      ? captured.slice(0, 500)
      : inferQueryFromLandingPage(args.landingPage);

    await prisma.$transaction(
      (tx) => tx.aiAttribution.create({
        data: {
          brandId: args.brandId,
          sessionId: args.sessionId,
          channel: args.channel,
          aiPlatform: args.platform,
          referrerUrl: args.referrerUrl?.slice(0, 2048) ?? null,
          queryContext,
          landingPage: args.landingPage.slice(0, 2048),
        },
      }),
      { timeout: 5000 },
    );
  } catch (err) {
    console.error("[ai-attribution] create failed:", err instanceof Error ? err.message : String(err));
  }
}

export async function attributeConversion(args: {
  brandId: string;
  sessionId: string;
  conversionType: string;
  conversionPage: string;
  conversionId?: string;
}): Promise<void> {
  try {
    await prisma.$transaction(async (tx) => {
      const attribution = await tx.aiAttribution.findFirst({
        where: { brandId: args.brandId, sessionId: args.sessionId },
        select: { id: true },
      });
      if (!attribution) return;

      await tx.aiAttribution.update({
        where: { id: attribution.id },
        data: {
          converted: true,
          conversionType: args.conversionType,
          conversionPage: args.conversionPage,
          conversionId: args.conversionId ?? null,
          conversionTimestamp: new Date(),
        },
      });
    }, { timeout: 5000 });
  } catch (err) {
    console.error("[ai-attribution] conversion update failed:", err instanceof Error ? err.message : String(err));
  }
}

export async function getAiAttributionSummary(brandId: string, since: Date) {
  const [total, converted, byPlatform, byChannel, topPages] = await Promise.all([
    prisma.aiAttribution.count({ where: { brandId, timestamp: { gte: since } } }),
    prisma.aiAttribution.count({ where: { brandId, timestamp: { gte: since }, converted: true } }),
    prisma.aiAttribution.groupBy({
      by: ["aiPlatform"],
      where: { brandId, timestamp: { gte: since } },
      _count: true,
      orderBy: { _count: { aiPlatform: "desc" } },
    }),
    prisma.aiAttribution.groupBy({
      by: ["channel"],
      where: { brandId, timestamp: { gte: since } },
      _count: true,
    }),
    prisma.aiAttribution.groupBy({
      by: ["landingPage"],
      where: { brandId, timestamp: { gte: since } },
      _count: true,
      orderBy: { _count: { landingPage: "desc" } },
      take: 10,
    }),
  ]);

  const convRate = total > 0 ? Math.round((converted / total) * 1000) / 10 : 0;

  // Per-platform conversion counts
  const platformConversions = await prisma.aiAttribution.groupBy({
    by: ["aiPlatform"],
    where: { brandId, timestamp: { gte: since }, converted: true },
    _count: true,
  }).catch(() => []);
  const convByPlatform = new Map(platformConversions.map((p) => [p.aiPlatform, p._count]));

  return {
    totalReferrals: total,
    conversions: converted,
    conversionRate: convRate,
    byPlatform: byPlatform.map((p) => ({
      platform: p.aiPlatform ?? "unknown",
      visits: typeof p._count === "number" ? p._count : 0,
      conversions: convByPlatform.get(p.aiPlatform) ?? 0,
    })),
    byChannel: byChannel.map((c) => ({
      channel: c.channel,
      count: typeof c._count === "number" ? c._count : 0,
    })),
    topPages: topPages.map((p) => ({
      page: p.landingPage,
      visits: typeof p._count === "number" ? p._count : 0,
    })),
  };
}
