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

const MAX_INPUT_LENGTH = 1000;
const MAX_RETRIES = 2;

const GROQ_API_URL = 'https://api.groq.com/openai/v1/chat/completions';
const GROQ_MODEL = 'llama-3.1-8b-instant';

const SYSTEM_PROMPT = `You rewrite mobile app release notes professionally. Follow these rules exactly:

Format:
- If the user provides multiple items (2 or more), start with the intro line: "The following items have been covered in this build:" followed by each item as a bullet using "- " prefix
- If the user provides only 1 item, return just one clean sentence with no intro line and no bullet

Content rules:
- Rephrase each point to sound professional and clear
- Fix any typos or grammar errors in the original text
- NEVER add new points or information the user did not mention
- Return exactly the same number of items the user gave
- Each item should be 1 short sentence starting with a past-tense verb (e.g. "Integrated", "Resolved", "Implemented", "Updated", "Fixed")
- Put feature names or specific terms in quotes (e.g. "Add Conversation" feature)
- Return ONLY the improved text — no extra commentary, no markdown bold/headers, no wrapping in quotes`;

function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function callGroq(apiKey: string, trimmed: string, attempt = 0): Promise<Response> {
  const res = await fetch(GROQ_API_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      model: GROQ_MODEL,
      messages: [
        { role: 'system', content: SYSTEM_PROMPT },
        { role: 'user', content: trimmed },
      ],
      temperature: 0.15,
      max_tokens: 300,
      top_p: 0.8,
    }),
  });

  if (res.status === 429 && attempt < MAX_RETRIES) {
    const waitSec = Math.pow(2, attempt + 1);
    await sleep(waitSec * 1000);
    return callGroq(apiKey, trimmed, attempt + 1);
  }

  return res;
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const text: unknown = body?.text;

    if (!text || typeof text !== 'string') {
      return NextResponse.json({ error: 'Text is required.' }, { status: 400 });
    }

    const trimmed = text.trim();

    if (trimmed.length === 0) {
      return NextResponse.json({ error: 'Text cannot be empty.' }, { status: 400 });
    }

    if (trimmed.length > MAX_INPUT_LENGTH) {
      return NextResponse.json(
        { error: `Input must be ${MAX_INPUT_LENGTH} characters or less.` },
        { status: 400 },
      );
    }

    const apiKey = process.env.GROQ_API_KEY;
    if (!apiKey) {
      return NextResponse.json(
        { error: 'AI service is not configured. Add GROQ_API_KEY to your environment.' },
        { status: 503 },
      );
    }

    const groqRes = await callGroq(apiKey, trimmed);

    if (!groqRes.ok) {
      const errBody = await groqRes.text().catch(() => '');
      console.error('Groq API error:', groqRes.status, errBody);

      if (groqRes.status === 429) {
        return NextResponse.json(
          { error: 'AI rate limit reached. Please wait a moment and try again.' },
          { status: 429 },
        );
      }

      return NextResponse.json(
        { error: 'AI service returned an error. Please try again.' },
        { status: 502 },
      );
    }

    const data = await groqRes.json();
    const improved: string | undefined = data?.choices?.[0]?.message?.content;

    if (!improved) {
      return NextResponse.json(
        { error: 'AI did not return a result. Please try again.' },
        { status: 502 },
      );
    }

    return NextResponse.json({ improved: improved.trim() });
  } catch (err) {
    console.error('improve-release-notes error:', err);
    return NextResponse.json({ error: 'Unexpected error. Please try again.' }, { status: 500 });
  }
}
