/**
 * Content Auditor — Analyzes all pages using GSC data, classifies
 * each into action buckets, detects cannibalization, and calls
 * Claude for strategic recommendations.
 */

import { prisma } from "@/lib/prisma";
import { callLlm } from "@/lib/ai-avatar/llm-client";

export type PageAction = "keep" | "update" | "merge" | "delete" | "optimize" | "cannibalized";

export interface AuditedPage {
  url: string;
  clicks30d: number;
  clicksPrev30d: number;
  trend: "growing" | "stable" | "declining" | "dead";
  position: number;
  ctr: number;
  impressions: number;
  topKeywords: string[];
  action: PageAction;
  reason: string;
  cannibalizationGroup?: string;
}

function extractJson(raw: string): string {
  let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "");
  const f = s.indexOf("{"), l = s.lastIndexOf("}");
  if (f >= 0 && l > f) s = s.slice(f, l + 1);
  return s;
}

export async function auditContent(brandId: string): Promise<{ totalPages: number; results: AuditedPage[]; aiSummary: string | null }> {
  const now = new Date();
  const d30 = new Date(now.getTime() - 30 * 86400000);
  const d60 = new Date(now.getTime() - 60 * 86400000);
  const d90 = new Date(now.getTime() - 90 * 86400000);

  // Current period (30d)
  const current = await prisma.gscPage.groupBy({
    by: ["pageUrl"],
    where: { brandId, date: { gte: d30 } },
    _sum: { clicks: true, impressions: true },
    _avg: { ctr: true, position: true },
  });

  // Previous period (30-60d)
  const previous = await prisma.gscPage.groupBy({
    by: ["pageUrl"],
    where: { brandId, date: { gte: d60, lt: d30 } },
    _sum: { clicks: true },
  });
  const prevMap = new Map(previous.map((p) => [p.pageUrl, p._sum.clicks ?? 0]));

  // Top keywords per page
  const queryData = await prisma.gscQuery.findMany({
    where: { brandId, date: { gte: d30 } },
    select: { query: true, clicks: true },
    orderBy: { clicks: "desc" },
    take: 500,
  });

  // Detect cannibalization: keywords ranking for multiple pages
  const kwPages = new Map<string, Set<string>>();
  // Use page-level data for keyword attribution (simplified)

  const results: AuditedPage[] = [];
  const actionCounts: Record<PageAction, number> = { keep: 0, update: 0, merge: 0, delete: 0, optimize: 0, cannibalized: 0 };

  for (const page of current) {
    const clicks = page._sum.clicks ?? 0;
    const prevClicks = prevMap.get(page.pageUrl) ?? 0;
    const impressions = page._sum.impressions ?? 0;
    const position = page._avg.position ?? 0;
    const ctr = (page._avg.ctr ?? 0) * 100;

    let trend: AuditedPage["trend"] = "stable";
    if (clicks === 0 && impressions === 0) trend = "dead";
    else if (prevClicks > 0 && clicks > prevClicks * 1.1) trend = "growing";
    else if (prevClicks > 0 && clicks < prevClicks * 0.8) trend = "declining";

    let action: PageAction = "keep";
    let reason = "Performing well";
    if (trend === "dead") { action = "delete"; reason = "No traffic or impressions in 30 days"; }
    else if (impressions > 100 && ctr < 2) { action = "optimize"; reason = `High impressions (${impressions}) but low CTR (${ctr.toFixed(1)}%)`; }
    else if (trend === "declining" && clicks < 10) { action = "update"; reason = "Declining traffic — needs refresh"; }
    else if (clicks < 5 && impressions < 50) { action = "merge"; reason = "Thin content — consider merging with related page"; }

    actionCounts[action]++;
    results.push({ url: page.pageUrl, clicks30d: clicks, clicksPrev30d: prevClicks, trend, position, ctr, impressions, topKeywords: [], action, reason });
  }

  results.sort((a, b) => b.impressions - a.impressions);

  // AI summary
  const brand = await prisma.brand.findUnique({ where: { id: brandId }, select: { name: true } });
  let aiSummary: string | null = null;
  try {
    const prompt = `Analyze this content inventory for ${brand?.name || "this brand"}:
Total pages: ${results.length}
Actions: keep=${actionCounts.keep}, update=${actionCounts.update}, optimize=${actionCounts.optimize}, merge=${actionCounts.merge}, delete=${actionCounts.delete}
Top declining: ${results.filter((r) => r.trend === "declining").slice(0, 5).map((r) => r.url).join(", ") || "none"}
Dead pages: ${actionCounts.delete}

Provide a brief executive summary (3-4 sentences) of content health and top 3 priority actions.`;

    const res = await callLlm(
      [{ role: "system", content: "You are a content strategy expert. Be concise." }, { role: "user", content: prompt }],
      () => `${results.length} pages analyzed. ${actionCounts.keep} performing well, ${actionCounts.update + actionCounts.optimize} need attention, ${actionCounts.delete} can be removed.`,
      { maxTokens: 1500 },
    );
    aiSummary = res.reply;
  } catch { /* non-critical */ }

  return { totalPages: results.length, results, aiSummary };
}
