import OpenAI from "openai";
import { OPENAI_MODEL } from "../config.js";

const client = process.env.OPENAI_API_KEY
  ? new OpenAI({ apiKey: process.env.OPENAI_API_KEY })
  : null;

export async function analyzePrompt(prompt) {
  if (!prompt?.trim()) {
    return { status: 400, body: { error: "Prompt is required." } };
  }

  if (!client) {
    return {
      status: 200,
      body: {
        result: `Demo mode: backend đã nhận prompt "${prompt}" nhưng chưa có OPENAI_API_KEY.`,
      },
    };
  }

  try {
    const response = await client.responses.create({
      model: OPENAI_MODEL,
      input: [
        {
          role: "system",
          content: "You are an NLP analysis assistant. Return a concise analysis in plain text.",
        },
        {
          role: "user",
          content: prompt,
        },
      ],
    });

    return {
      status: 200,
      body: {
        result: response.output_text || "No response text returned.",
      },
    };
  } catch (error) {
    return {
      status: 500,
      body: {
        error: "OpenAI request failed.",
        details: error.message,
      },
    };
  }
}
