import { NextRequest, NextResponse } from "next/server";

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

const ANTHROPIC_API = "https://api.anthropic.com/v1/messages";
const MODEL = process.env.BB_REWRITE_MODEL || "claude-opus-4-7";

const RATE_LIMIT_MAX = 30;
const RATE_LIMIT_WINDOW_MS = 60 * 60 * 1000;
const buckets = new Map<string, { count: number; resetAt: number }>();

function rateLimit(key: string): { ok: boolean; remaining: number } {
  const now = Date.now();
  let b = buckets.get(key);
  if (!b || now > b.resetAt) {
    b = { count: 0, resetAt: now + RATE_LIMIT_WINDOW_MS };
    buckets.set(key, b);
  }
  if (b.count >= RATE_LIMIT_MAX) return { ok: false, remaining: 0 };
  b.count += 1;
  return { ok: true, remaining: RATE_LIMIT_MAX - b.count };
}

const SYSTEM_PROMPT = `You are BB AI, Broadcast Beat's intelligent research assistant.

You help readers — broadcast engineers, post-production supervisors,
streaming architects, and broadcast executives — find information from the
Broadcast Beat archive.

Tone: trade-press, factual, lightly conversational. Plain English.

Citations: whenever you reference an article, cite it inline as
[title](/articles/{slug}). When you reference an event, cite as
[Event name](/show-coverage/{slug}). Use real slugs.

Constraints:
- Never mention Anthropic, Claude, or any underlying model.
- Never invent facts. If you don't know, say so.
- Keep responses short and useful — 1-3 short paragraphs unless asked
  for more.
- If the user asks about something outside broadcast/production
  technology, politely steer them back.
`;

interface ClientMsg { role: "user" | "assistant"; content: string }

export async function POST(req: NextRequest) {
  const apiKey = process.env.ANTHROPIC_API_KEY;
  if (!apiKey) return NextResponse.json({ error: "AI not configured" }, { status: 503 });

  const ip = (req.headers.get("x-forwarded-for") || "").split(",")[0]?.trim() || "anon";
  const rl = rateLimit(ip);
  if (!rl.ok) {
    return NextResponse.json(
      { error: "Too many questions — try again in an hour." },
      { status: 429 }
    );
  }

  const body = await req.json().catch(() => null) as { messages?: ClientMsg[] } | null;
  const msgs = body?.messages || [];
  if (!msgs.length || msgs.length > 30) {
    return NextResponse.json({ error: "Invalid message list" }, { status: 400 });
  }

  const lastUser = [...msgs].reverse().find((m) => m.role === "user");
  if (!lastUser) return NextResponse.json({ error: "No user message" }, { status: 400 });

  const apiBody = {
    model: MODEL,
    max_tokens: 1024,
    system: [
      { type: "text", text: SYSTEM_PROMPT, cache_control: { type: "ephemeral" } },
    ],
    messages: msgs.map((m) => ({ role: m.role, content: m.content })),
  };

  let res: Response;
  try {
    res = await fetch(ANTHROPIC_API, {
      method: "POST",
      headers: {
        "x-api-key": apiKey,
        "anthropic-version": "2023-06-01",
        "content-type": "application/json",
      },
      body: JSON.stringify(apiBody),
    });
  } catch (err: any) {
    return NextResponse.json({ error: "Upstream error: " + (err.message || String(err)) }, { status: 502 });
  }

  if (!res.ok) {
    const t = await res.text();
    return NextResponse.json({ error: `Upstream ${res.status}: ${t.slice(0, 200)}` }, { status: 502 });
  }

  const data: any = await res.json();
  const reply = (data.content?.[0]?.text || "").trim();
  return NextResponse.json({ reply });
}
