/**
 * POST /api/page-studio/rewrite
 *
 * Sends a text snippet to Claude and returns 3 rewrites: professional,
 * casual, and shorter. Used by the AI rewrite button in the Page Studio
 * settings panel. Body: { brandId, text, sectionType, fieldLabel? }
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { callLlm } from "@/lib/ai-avatar/llm-client";
import { logAiInteraction } from "@/lib/services/ai-interaction-log";

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

interface Body {
  brandId?: string;
  text?: string;
  sectionType?: string;
  fieldLabel?: string;
}

interface Alternative { label: string; text: string }
interface AiResponse { alternatives?: Alternative[] }

function extractJson(raw: string): string {
  let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "");
  const first = s.indexOf("{");
  const last = s.lastIndexOf("}");
  if (first >= 0 && last > first) s = s.slice(first, last + 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)) as Body | null;
  if (!body?.brandId || !body.text || !body.sectionType) {
    return NextResponse.json({ error: "brandId, text, sectionType required" }, { status: 400 });
  }

  const brand = await prisma.brand.findUnique({
    where: { id: body.brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const industry = brand.industry || "business";
  const systemPrompt = "You are a conversion copywriter. Respond ONLY with a JSON object — no markdown, no commentary.";
  const userPrompt = `Rewrite this text for a ${industry} company called ${brand.name}.
Current text: "${body.text}"
Section type: ${body.sectionType}${body.fieldLabel ? `\nField: ${body.fieldLabel}` : ""}

Provide 3 alternatives: one more professional, one more casual, one shorter.
Respond ONLY with this JSON shape:
{"alternatives":[{"label":"Professional","text":"..."},{"label":"Casual","text":"..."},{"label":"Shorter","text":"..."}]}`;

  const result = await callLlm(
    [
      { role: "system", content: systemPrompt },
      { role: "user", content: userPrompt },
    ],
    () => JSON.stringify({
      alternatives: [
        { label: "Professional", text: `${body.text}` },
        { label: "Casual", text: `${body.text}` },
        { label: "Shorter", text: body.text!.split(/\s+/).slice(0, 8).join(" ") + (body.text!.split(/\s+/).length > 8 ? "…" : "") },
      ],
    }),
    { maxTokens: 1000 },
  );

  logAiInteraction({
    userId: user.id,
    brandId: body.brandId,
    feature: "other",
    userPrompt,
    systemPrompt,
    aiResponse: result.reply,
    model: result.model,
    brandDomain: brand.domain,
  });

  let parsed: AiResponse;
  try {
    parsed = JSON.parse(extractJson(result.reply)) as AiResponse;
  } catch {
    return NextResponse.json({ error: "AI returned invalid JSON", raw: result.reply.slice(0, 300) }, { status: 500 });
  }

  const alternatives = (parsed.alternatives || [])
    .filter((a): a is Alternative => typeof a?.label === "string" && typeof a?.text === "string")
    .slice(0, 3);

  if (alternatives.length === 0) {
    return NextResponse.json({ error: "No alternatives returned" }, { status: 500 });
  }

  return NextResponse.json({ alternatives, provider: result.provider });
}
