const LITELLM_URL = process.env.LITELLM_BASE_URL;
const LITELLM_KEY = process.env.LITELLM_API_KEY;
const CHAT_MODEL = process.env.CHAT_MODEL || "minimax-2.7";

interface ParentingContext {
  childName: string;
  childAge: string; // e.g. "8 months"
}

export async function answerParentingQuery(
  query: string,
  conversationHistory: { role: "user" | "assistant"; content: string }[],
  ctx: ParentingContext
): Promise<string> {
  if (!LITELLM_URL || !LITELLM_KEY) {
    return "AI is not configured. Please add LITELLM_BASE_URL and LITELLM_API_KEY.";
  }

  const systemPrompt = `You are Tia, a friendly baby care assistant helping parents with general baby care information.

${ctx.childName} is ${ctx.childAge} old.

STRICT RULES — follow without exception:
- NEVER diagnose, interpret symptoms, or give medical advice
- NEVER recommend medications, dosages, or treatments
- If the user describes symptoms, fever, rash, breathing issues, pain, or asks "is this normal" about a physical concern — refuse and say "That's something your pediatrician should evaluate, not me."
- ONLY provide general educational information from WHO, IAP, or AAP guidelines
- Always note: "This is general info, not medical advice."
- Keep responses under 200 words
- Be warm but clear`;

  try {
    const response = await fetch(`${LITELLM_URL}/v1/chat/completions`, {
      method: "POST",
      headers: { "Content-Type": "application/json", "Authorization": `Bearer ${LITELLM_KEY}` },
      body: JSON.stringify({
        model: CHAT_MODEL,
        messages: [
          { role: "system", content: systemPrompt },
          ...conversationHistory.slice(-6), // last 3 turns for context
          { role: "user", content: query },
        ],
        max_tokens: 300,
        temperature: 0.3,
      }),
    });

    if (!response.ok) throw new Error(`LLM HTTP ${response.status}`);
    const data = await response.json();
    return data.choices?.[0]?.message?.content || "I couldn't generate a response. Please try again.";
  } catch (e) {
    console.error("[parenting] error:", e);
    return "I couldn't connect to the AI right now. Please try again in a moment.";
  }
}
