/**
 * POST /api/ai-avatar
 * --------------------
 * Chat endpoint for the meSEO AI Strategist avatar.
 *
 * Request body:
 *   {
 *     brandId:     string     — the selected brand
 *     currentPage: string     — the page the user is on (e.g. "/dashboard")
 *     message:     string     — the user's message
 *     history:     ChatMessage[] — previous conversation messages
 *   }
 *
 * Response:
 *   {
 *     reply:     string         — the AI's response text
 *     context:   { module, brand, page, metrics }  — page-aware context
 *     actions:   SuggestedAction[]   — clickable actions (navigate, create_task, etc.)
 *     followUps: SuggestedFollowUp[] — follow-up prompts the user can click
 *   }
 *
 * Phase 1: Returns a mock AI response built from the prompt builder.
 * Phase 2: Will call an actual LLM API (Claude/OpenAI) with the
 *           constructed messages.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { buildAvatarContext } from "@/lib/ai-avatar/context-builder";
import { retrieveForPage, retrieveByIntent } from "@/lib/ai-avatar/retrieval";
import { buildSystemPrompt, buildMessages } from "@/lib/ai-avatar/prompt-builder";
import { generateActions } from "@/lib/ai-avatar/actions";
import { createConversation, saveMessage } from "@/lib/ai-avatar/conversations";
import { callLlm, getLlmStatus } from "@/lib/ai-avatar/llm-client";
import { logAiInteraction } from "@/lib/services/ai-interaction-log";
import { log } from "@/lib/logger";
import type { ChatMessage } from "@/lib/ai-avatar/prompt-builder";

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const start = Date.now();

  // ── Auth ──
  const user = await getCurrentUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  // ── Parse request ──
  const body = await req.json();
  const { brandId, currentPage, message, history, conversationId: incomingConvId } = body as {
    brandId: string;
    currentPage: string;
    message: string;
    history: ChatMessage[];
    conversationId?: string | null;
  };

  if (!brandId || !message) {
    return NextResponse.json(
      { error: "brandId and message are required" },
      { status: 400 }
    );
  }

  // ── Build context ──
  const ctx = await buildAvatarContext(brandId, currentPage || "/", user.id);
  if (!ctx) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  // ── Retrieve module data (intent-based multi-module) ──
  const retrievals = await retrieveByIntent(ctx, message);
  const primaryModule = retrievals[0]?.module ?? "General";

  log.info("avatar", `Retrieved ${retrievals.length} modules: ${retrievals.map(r => r.module).join(", ")}`, {
    metadata: { brandId, modules: retrievals.map(r => r.module) },
  });

  // ── Build prompt (includes all retrieved module data) ──
  const systemPrompt = buildSystemPrompt(ctx, retrievals);
  const _messages = buildMessages(systemPrompt, history ?? [], message);

  // ── Call LLM (Anthropic → OpenAI → mock fallback) ──
  const llmResult = await callLlm(
    _messages,
    () => generateMockResponse(message, ctx, retrievals[0] ?? null)
  );
  const reply = llmResult.reply;

  // Admin observability — guardrail-scored audit log feeds /admin/ai-monitor.
  logAiInteraction({
    userId: user.id,
    brandId,
    feature: "ai_strategist",
    userPrompt: message,
    systemPrompt,
    aiResponse: reply,
    model: llmResult.model,
  });

  // Generate suggested actions and follow-up prompts
  const { actions, followUps } = generateActions(
    message,
    primaryModule,
    ctx.currentPage
  );

  // ── Persist conversation ──
  let conversationId = incomingConvId ?? null;
  try {
    // Create a new conversation if this is the first message
    if (!conversationId) {
      conversationId = await createConversation(user.id, brandId, message);
    }

    // Save the user's message
    await saveMessage(conversationId, "user", message, primaryModule);

    // Save the assistant's reply (with actions/followUps as metadata)
    await saveMessage(conversationId, "assistant", reply, primaryModule, {
      actions,
      followUps,
      context: {
        module: primaryModule ?? "General",
        brand: ctx.brandName,
        page: ctx.currentPage,
      },
    });
  } catch {
    // Persistence failure should not break the chat — log but continue
    log.error("avatar", "Failed to persist conversation", { userId: user.id, metadata: { brandId } });
  }

  log.apiRequest("/api/ai-avatar", "POST", 200, Date.now() - start, {
    userId: user.id,
    metadata: { module: primaryModule, brandId, currentPage, llmProvider: llmResult.provider, llmModel: llmResult.model },
  });

  // Return the reply + context + actions + follow-ups + conversationId
  return NextResponse.json({
    reply,
    conversationId,
    context: {
      module: primaryModule ?? "General",
      brand: ctx.brandName,
      page: ctx.currentPage,
      metrics: retrievals[0]?.metrics ?? {},
    },
    actions,
    followUps,
  });
}

// ─── Mock response generator (Phase 1) ───────────────────────────────────────

/**
 * Generates a structured response based on the user's question and context.
 * This simulates what the real LLM would produce using the prompt builder.
 */
function generateMockResponse(
  message: string,
  ctx: { brandName: string; domain: string; currentPage: string },
  retrieval: { module: string; summary: string; metrics: Record<string, string | number> } | null
): string {
  const q = message.toLowerCase();
  const brand = ctx.brandName;

  // ── Traffic / performance questions ──
  if (q.includes("traffic") || q.includes("sessions") || q.includes("visit")) {
    return `**What's happening**
${brand} is seeing 12,480 organic sessions this month, up 8% from last month. AI search is contributing 1,100 sessions (+34% MoM) — your fastest-growing channel.

**Why it matters**
The 8% organic growth is solid, but AI search at +34% signals a shift in how users find you. If this trend continues, AI channels could represent 15% of your traffic within 6 months.

**What to do next**
1. **Protect organic growth** — publish 2 new content pieces targeting your top declining keywords
2. **Accelerate AI traffic** — optimize your top 5 pages for answer-ready formatting (FAQ schema, direct answers in H2s)
3. **Monitor weekly** — set up a signal alert for any organic traffic drop >5%`;
  }

  // ── Conversion questions ──
  if (q.includes("conversion") || q.includes("revenue") || q.includes("roi")) {
    return `**What's happening**
${brand} generated 487 conversions this month ($243.5K revenue) across 5 channels. Organic leads with 186 conversions at a 4.4% rate. AI Search has the highest revenue per conversion at $500.

**Why it matters**
Your ROI is 3.2x — healthy, but AI Search conversions are 2.6x more valuable than organic ones. This channel is underinvested relative to its conversion quality.

**What to do next**
1. **Double AI Search investment** — create 5 LLMO-optimized pages targeting high-intent queries
2. **Fix the social gap** — 264 assisted touches but only 34 direct conversions suggests social needs better landing pages
3. **Optimize phone CTA** — 46.2% of conversions are phone calls, ensure click-to-call is prominent on mobile`;
  }

  // ── Technical / audit questions ──
  if (q.includes("technical") || q.includes("audit") || q.includes("error") || q.includes("fix") || q.includes("broken")) {
    return `**What's happening**
${brand}'s site health score is 68/100. There are 17 errors (missing meta descriptions, broken links, duplicate titles), 34 warnings, and 12 notices. 89 audits are passing.

**Why it matters**
The 17 errors are actively hurting your rankings. Missing meta descriptions on 14 high-traffic pages are reducing click-through rate by an estimated 8%. The 17 broken links are wasting link equity.

**What to do next**
1. **Write meta descriptions for 14 pages** — low effort, high impact (+8% CTR)
2. **Fix 17 broken internal links** — recovers crawl efficiency and link equity
3. **Resolve duplicate titles on 6 pages** — stops keyword cannibalization (+3% rankings)`;
  }

  // ── Competitor questions ──
  if (q.includes("competitor") || q.includes("compete") || q.includes("moz") || q.includes("semrush")) {
    return `**What's happening**
${brand} ranks #4 among 6 tracked competitors with a visibility score of 74. Moz leads at 92 (+18 pts ahead), followed by SEMrush at 89. RankFast is the fastest riser (+16 pts in 6 months).

**Why it matters**
The 18-point gap to Moz is significant but not insurmountable. More importantly, no competitor covers AI/LLMO visibility — this is a blue ocean opportunity worth an estimated 12k visits/mo.

**What to do next**
1. **Own AI visibility** — publish 5-10 LLMO-optimized guides before competitors enter this space
2. **Target aging Moz content** — 40% of their top pages haven't been updated in 12+ months
3. **Monitor RankFast** — they're growing fast (+16 pts), set up a weekly competitor alert`;
  }

  // ── Content questions ──
  if (q.includes("content") || q.includes("brief") || q.includes("write") || q.includes("publish")) {
    return `**What's happening**
${brand} has 4 active SEO briefs and 3 LLMO briefs. 2 briefs are ready to publish (est. +2,100 visits/mo). Average SEO brief score is 72/100, LLMO brief score is 68/100.

**Why it matters**
The 2 ready-to-publish briefs represent immediate traffic you're leaving on the table. The LLMO score of 68 suggests your AI-optimized content needs more answer-ready formatting.

**What to do next**
1. **Publish the 2 ready briefs** — capture +2,100 visits/mo starting this week
2. **Improve LLMO scores** — add FAQ sections and direct-answer formatting to boost from 68 to 80+
3. **Create a brief for "AI visibility"** — no competitors are targeting this high-growth keyword cluster`;
  }

  // ── Local GEO questions ──
  if (q.includes("local") || q.includes("geo") || q.includes("city") || q.includes("market") || q.includes("seattle") || q.includes("denver") || q.includes("phoenix")) {
    return `**What's happening**
${brand} tracks 8 local markets. Seattle is your strongest (score 85, #1 in AI Visibility, +18 pts growth). Denver is completely untapped (11k searches/mo, zero presence). Phoenix is declining at -4 pts with all services below 52.

**Why it matters**
Seattle generates the most local conversions but Cascade SEO is gaining. Phoenix's decline means you're losing ground in a market you were building. Denver is pure upside — 11k monthly searches with no investment from you.

**What to do next**
1. **Protect Seattle** — publish 2 local guides/month to maintain your #1 AI Visibility position
2. **Enter Denver** — create a Denver location page this week (even a basic one starts generating signals within 30 days)
3. **Triage Phoenix** — audit indexed pages for thin content or cannibalization causing the decline`;
  }

  // ── Execution hub / tasks questions ──
  if (q.includes("task") || q.includes("overdue") || q.includes("execution") || q.includes("to-do") || q.includes("todo") || q.includes("backlog")) {
    return `**What's happening**
${brand} has 18 active tasks: 6 to-do, 7 in-progress, 5 completed. There are 3 overdue high-priority tasks — broken links (5 days late), meta descriptions (3 days late), and image compression (1 day late).

**Why it matters**
The 3 overdue tasks collectively affect 54 pages. Completing them would resolve your top technical issues and unlock an estimated +2,200 visits/mo and +26 leads/mo. Every day they stay open, you're losing traffic.

**What to do next**
1. **Today:** Complete 'Fix broken internal links' — it's 5 days overdue and affects 17 pages
2. **Tomorrow:** Finish 'Write meta descriptions' — 14 pages are missing them, +8% CTR expected
3. **This week:** Clear all 3 overdue tasks, then focus on 'Add structured data' (due in 2 days)`;
  }

  // ── Page launch questions ──
  if (q.includes("launch") || q.includes("page launch") || q.includes("pipeline") || q.includes("publish") || q.includes("go live")) {
    return `**What's happening**
${brand} has 8 pages in the launch pipeline: 2 drafting, 3 in review, 2 approved and ready to launch, 1 already live. The 2 ready pages target 'AI SEO' (1,900 searches/mo) and 'SEO checklist' (2,400 searches/mo).

**Why it matters**
The 2 approved pages are sitting idle — every day they're not live, you're missing an estimated +1,400 visits/mo combined. Your review stage is a bottleneck (avg 5 days, 3 pages currently waiting).

**What to do next**
1. **Launch today:** Push '/blog/ai-seo-guide' and '/resources/technical-checklist' live — they're already approved
2. **Speed up reviews** — 3 pages are waiting, try to clear the review queue within 48 hours
3. **Monitor your top performer** — '/blog/content-strategy' is driving 3,200 visits/mo since launch, consider updating it`;
  }

  // ── SEO content brief questions ──
  if (q.includes("seo brief") || q.includes("seo content") || q.includes("keyword") || q.includes("serp")) {
    return `**What's happening**
${brand} has 4 active SEO briefs (2 draft, 1 in review, 1 published). Average SEO score is 72/100. Internal linking is the weakest area at 58/100. Your top keyword target is 'technical SEO checklist' at 2,400 searches/mo.

**Why it matters**
The weak internal linking score means your content isn't passing authority effectively between pages. 2 of your 4 target keywords have featured snippets held by competitors — you need higher-quality structure to win them.

**What to do next**
1. **Strengthen internal links** — add 3-5 contextual links per brief to boost from 58 to 75+
2. **Target the featured snippets** — restructure the top 2 briefs with direct-answer H2s and bullet lists
3. **Fill the content gap** — create a brief targeting 'AI SEO' cluster before competitors claim it`;
  }

  // ── LLMO content brief questions ──
  if (q.includes("llmo") || q.includes("ai content") || q.includes("ai brief") || q.includes("answer-ready") || q.includes("chatgpt") || q.includes("perplexity")) {
    return `**What's happening**
${brand} has 3 active LLMO briefs (1 draft, 2 in review). Average LLMO score is 68/100. Answer-ready format is the weakest area at 55/100. 5 existing pages could be retrofitted for AI visibility with formatting changes only.

**Why it matters**
AI search engines like ChatGPT and Perplexity extract answers from well-structured content. Your score of 55 on answer-ready format means your content is being passed over in favor of competitors with clearer structure.

**What to do next**
1. **Retrofit 5 existing pages** — add FAQ blocks, direct-answer H2s, and structured data (fastest wins)
2. **Improve the 2 briefs in review** — focus on answer-ready formatting to raise score from 55 to 75+
3. **Target 'what is LLMO'** — 3,200 searches/mo with no authoritative AI-optimized page yet`;
  }

  // ── What should I do / priorities / help ──
  if (q.includes("what should") || q.includes("priority") || q.includes("help") || q.includes("where do i start") || q.includes("next step") || q.includes("focus")) {
    return `**What's happening**
Based on ${brand}'s data across all modules: 3 overdue high-priority tasks, 17 broken links, 14 pages missing meta descriptions, 2 pages ready to launch, 2 content briefs ready to publish, and Denver is an untapped market with 11k monthly searches.

**Why it matters**
The overdue tasks are your biggest risk — they're blocking +2,200 visits/mo. The ready-to-launch pages are your quickest wins (+1,400 visits/mo). Denver is your biggest opportunity for new market entry.

**What to do next**
1. **Today:** Clear the 3 overdue tasks (broken links, meta descriptions, image compression)
2. **This week:** Launch the 2 approved pages and publish the 2 ready content briefs (+3,500 visits/mo combined)
3. **This month:** Create a Denver location page and 3 LLMO guides to enter two untapped categories`;
  }

  // ── Page-aware default: use the retrieval data directly ──
  const mod = retrieval?.module ?? "Dashboard";
  const summaryLines = retrieval?.summary.split("\n").filter(l => l.startsWith("- ")) ?? [];
  const topPoints = summaryLines.slice(0, 4).map(l => l.replace(/^- /, "")).join(". ");

  return `**What's happening**
You're on the ${mod} page for ${brand} (${ctx.domain}). ${topPoints || "Your platform data is loaded and ready for analysis."}

**Why it matters**
The ${mod} data shows where ${brand} stands right now. Understanding these numbers helps you prioritize the actions that will have the biggest impact on your traffic, conversions, and rankings.

**What to do next**
1. Ask me something specific — "What's my biggest issue?" or "How can I improve my score?"
2. I have context for: traffic, conversions, technical health, competitors, local markets, content briefs, tasks, and page launches
3. Or try "What should I focus on this week?" for a cross-platform priority list`;
}
