/**
 * POST /api/writing-assistant/ai-rewrite — AI rewrite, expand, or simplify.
 * Body: { brandId, text, mode: "rewrite"|"expand"|"simplify", keyword?, industry? }
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { callLlm } from "@/lib/ai-avatar/llm-client";
import { getEnrichmentContext, formatEnrichmentForPrompt } from "@/lib/services/enrichment-context";
import { logAiInteraction } from "@/lib/services/ai-interaction-log";

export const dynamic = "force-dynamic";
export const maxDuration = 30;

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 POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null);
  if (!body?.text || !body?.mode) return NextResponse.json({ error: "text and mode required" }, { status: 400 });

  const { text, mode, keyword, industry, brandId } = body as { text: string; mode: string; keyword?: string; industry?: string; brandId?: string };

  // Include enrichment context for brand-specific rewrites
  let enrichmentSuffix = "";
  if (brandId) {
    const enrichment = await getEnrichmentContext(brandId);
    const eText = formatEnrichmentForPrompt(enrichment);
    if (eText) enrichmentSuffix = `\n\nBrand context from uploaded documents:\n${eText.slice(0, 4000)}\nUse brand terminology and expertise when rewriting.`;
  }

  let prompt = "";
  if (mode === "rewrite") {
    prompt = `Rewrite this text 3 different ways. Same meaning, varied style.${keyword ? ` Keep target keyword "${keyword}".` : ""}\n\nText: "${text}"\n\nReturn JSON: {"alternatives":["version1","version2","version3"]}`;
  } else if (mode === "expand") {
    prompt = `Expand this sentence into a full paragraph with supporting details.${industry ? ` Industry: ${industry}.` : ""} Keep factual and authoritative.\n\nText: "${text}"\n\nReturn JSON: {"expanded":"the expanded paragraph"}`;
  } else {
    prompt = `Simplify this to 6th-grade reading level without losing meaning.\n\nText: "${text}"\n\nReturn JSON: {"simplified":"the simplified text"}`;
  }

  const result = await callLlm(
    [{ role: "system", content: "You are a content writing expert. Respond ONLY with JSON." }, { role: "user", content: prompt + enrichmentSuffix }],
    () => JSON.stringify(mode === "rewrite" ? { alternatives: [text, text, text] } : mode === "expand" ? { expanded: text } : { simplified: text }),
    { maxTokens: 2000 },
  );

  logAiInteraction({
    userId: user.id,
    brandId: brandId ?? null,
    feature: "other",
    userPrompt: prompt + enrichmentSuffix,
    aiResponse: result.reply,
    model: result.model,
  });

  try {
    return NextResponse.json(JSON.parse(extractJson(result.reply)));
  } catch {
    return NextResponse.json({ error: "AI returned invalid response" }, { status: 500 });
  }
}
