/**
 * CTA Optimizer
 * ─────────────
 * Analyzes brand conversion data and recommends optimal CTA
 * configuration via Claude AI.
 */

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

export interface CTARecommendation {
  recommendedText: string;
  recommendedType: "form" | "phone" | "both";
  recommendedPosition: "hero" | "sticky_bottom" | "after_testimonials";
  reasoning: string;
  alternatives: 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 optimizeCTA(
  brandId: string,
  currentCTA: string,
): Promise<CTARecommendation> {
  const d30 = new Date(Date.now() - 30 * 86400000);

  const [convs, brand] = await Promise.all([
    // intentionally unfiltered: internal service; uses raw counts intentionally
    prisma.siteConversion.findMany({
      where: { brandId, timestamp: { gte: d30 } },
      select: { conversionType: true, pageUrl: true, lastTouchChannel: true },
    }),
    prisma.brand.findUnique({
      where: { id: brandId },
      include: { profile: { select: { industry: true, services: true } } },
    }),
  ]);

  const benchmarks = await prisma.industryBenchmark.findMany({
    where: { industry: brand?.industry ?? "" },
    select: { metric: true, value: true },
  }).catch(() => [] as { metric: string; value: number }[]);

  const total = convs.length || 1;
  // Every SiteConversion.conversionType value that resolves to the
  // form_submitted / phone_call canonical — including the legacy /
  // alias names written by different detection paths (form-phone.js
  // writes "phone_call" + "phone_number_click"; older /api/site-tag/
  // conversion posts wrote "click_to_call"). Previously only the raw
  // "form_submit" / "phone_call" strings were matched, so the CTA
  // optimiser under-counted phone calls by ~3× for any brand using
  // the tel-link + text-pattern detectors.
  const FORM_TYPES = new Set(["form_submit", "form_submitted", "form_submission"]);
  const PHONE_TYPES = new Set(["phone_call", "phone_number_click", "click_to_call"]);
  const forms = convs.filter((c) => FORM_TYPES.has(c.conversionType)).length;
  const calls = convs.filter((c) => PHONE_TYPES.has(c.conversionType)).length;
  const formPct = Math.round((forms / total) * 100);
  const callPct = Math.round((calls / total) * 100);

  // Find top converting page CTAs
  const pageCounts: Record<string, number> = {};
  convs.forEach((c) => {
    if (c.pageUrl) pageCounts[c.pageUrl] = (pageCounts[c.pageUrl] || 0) + 1;
  });
  const topPages = Object.entries(pageCounts)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 3)
    .map(([url]) => url);

  const benchMap: Record<string, number> = {};
  benchmarks.forEach((b) => { benchMap[b.metric] = b.value; });

  const industry = brand?.profile?.industry || brand?.industry || "general";

  const result = await callLlm([
    { role: "system", content: "You are a conversion rate optimization expert. Respond ONLY with JSON." },
    {
      role: "user",
      content: `Optimize the CTA for a ${industry} business.

Current CTA: "${currentCTA}"
Conversion data (last 30 days):
- ${formPct}% of conversions come from forms
- ${callPct}% come from phone calls
- Total conversions: ${total}
- Top converting pages: ${topPages.join(", ") || "none"}
${benchMap["avg_ctr"] ? `- Industry avg CTR: ${benchMap["avg_ctr"].toFixed(1)}%` : ""}

Return JSON:
{"recommendedText":"CTA button text","recommendedType":"form|phone|both","recommendedPosition":"hero|sticky_bottom|after_testimonials","reasoning":"why this will convert better","alternatives":["alt CTA 1","alt CTA 2","alt CTA 3"]}`,
    },
  ], () => JSON.stringify({
    recommendedText: callPct > formPct ? "Call Now" : "Get a Free Quote",
    recommendedType: callPct > formPct ? "phone" : "form",
    recommendedPosition: "hero",
    reasoning: `Based on ${total} conversions, ${callPct > formPct ? "phone calls" : "form submissions"} convert best.`,
    alternatives: ["Schedule a Consultation", "Get Started Today", "Request a Quote"],
  }), { maxTokens: 1500 });

  try {
    return JSON.parse(extractJson(result.reply)) as CTARecommendation;
  } catch {
    return {
      recommendedText: callPct > formPct ? "Call Now" : "Get a Free Quote",
      recommendedType: callPct > formPct ? "phone" : "form",
      recommendedPosition: "hero",
      reasoning: "Using default recommendation based on conversion data.",
      alternatives: ["Schedule a Consultation", "Get Started Today", "Request a Quote"],
    };
  }
}
