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

export type Intent = "structured_query" | "memory_search" | "general_parenting" | "medical_redirect";

export interface ClassifierResult {
  intent: Intent;
  confidence: number;
  reasoning: string;
}

const SYSTEM_PROMPT = `You are a query classifier for a baby tracking app called Tia.
Classify the user's query into exactly ONE of these intents:

- "structured_query": User wants specific data from logs (sleep hours, feed count, diaper count, growth, medication status, vaccination status, last log entry). Examples: "How long did she sleep last night?", "How many feeds today?", "When was the last diaper change?", "What's her current weight?", "Is she due for any vaccines?", "Did she get her medicine today?"
- "memory_search": User wants to find photos or memories. Examples: "Show me photos of her first birthday", "Find pictures at the park", "Photos from last month".
- "general_parenting": General baby care questions, advice, milestones, education. Examples: "When do babies start solid food?", "Is 12 hours sleep normal for a 6 month old?", "What are signs of teething?", "How do I introduce peanuts?", "What milestones should she hit at 9 months?"
- "medical_redirect": Any symptom description, diagnosis request, medication dosage question. Examples: "She has a rash", "Is a temperature of 38 normal?", "Should I give her Crocin?", "She's not feeding well"

Respond ONLY with valid JSON in this format: {"intent": "...", "confidence": 0.95, "reasoning": "one sentence"}`;

export async function classifyIntent(query: string): Promise<ClassifierResult> {
  if (!LITELLM_URL || !LITELLM_KEY) {
    return { intent: "general_parenting", confidence: 0.5, reasoning: "AI not configured, defaulting" };
  }

  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: CLASSIFIER_MODEL,
        messages: [
          { role: "system", content: SYSTEM_PROMPT },
          { role: "user", content: query },
        ],
        max_tokens: 100,
        temperature: 0,
      }),
    });

    if (!response.ok) throw new Error(`Classifier HTTP ${response.status}`);

    const data = await response.json();
    const content: string = data.choices?.[0]?.message?.content || "";

    // Extract JSON even if wrapped in markdown
    const match = content.match(/\{[\s\S]*\}/);
    if (!match) throw new Error("No JSON in classifier response");

    const result = JSON.parse(match[0]) as ClassifierResult;

    const validIntents: Intent[] = ["structured_query", "memory_search", "general_parenting", "medical_redirect"];
    if (!validIntents.includes(result.intent)) {
      return { intent: "general_parenting", confidence: 0.5, reasoning: "Invalid intent, defaulting" };
    }

    return result;
  } catch (e) {
    console.error("[classifier] error:", e);
    return { intent: "general_parenting", confidence: 0.5, reasoning: "Classifier error, defaulting" };
  }
}
