/**
 * POST /api/content/humanization-check
 * Runs the algorithmic humanization scorer on supplied content.
 * Optionally rewrites content via Claude when action=humanize.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { scoreHumanization } from "@/lib/services/humanization-scorer";
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 {
  content?: string;
  action?: "score" | "humanize";
  brandId?: string;
}

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?.content || body.content.length < 50) {
    return NextResponse.json({ error: "Content must be at least 50 characters" }, { status: 400 });
  }

  // Score-only mode (default)
  if (body.action !== "humanize") {
    const result = scoreHumanization(body.content);
    return NextResponse.json(result);
  }

  // Humanize mode — rewrite via Claude then re-score
  const userPrompt = `Rewrite this content to sound more naturally human. Add sentence length variety, use contractions where appropriate, vary paragraph lengths, reduce AI-typical transition words (Furthermore, Moreover, Additionally), add conversational first-person voice where appropriate.\n\nContent:\n${body.content}`;
  const result = await callLlm(
    [
      { role: "system", content: "You are an expert content editor. Rewrite the content to sound naturally human while keeping the same information and heading structure. Do NOT change any # / ## / ### headings." },
      { role: "user", content: userPrompt },
    ],
    () => body.content!,
    { maxTokens: 4000 },
  );

  const humanized = result.reply;

  logAiInteraction({
    userId: user.id,
    brandId: body.brandId ?? null,
    feature: "other",
    userPrompt,
    aiResponse: humanized,
    model: result.model,
  });
  const beforeScore = scoreHumanization(body.content);
  const afterScore = scoreHumanization(humanized);

  return NextResponse.json({
    humanizedContent: humanized,
    before: beforeScore,
    after: afterScore,
    provider: result.provider,
  });
}
