// Medical intent detection for AI guardrails

export const MEDICAL_KEYWORDS = [
  // symptoms
  "fever", "temperature", "vomit", "throw up", "diarrhea", "rash",
  "breathing", "breath", "cough", "wheeze", "lethargy", "lethargic",
  "unconscious", "seizure", "convulsion", "blood", "bleeding",
  "swollen", "swelling", "bruise", "injury", "hurt", "pain",
  "infection", "pus", "discharge", "dehydration", "dehydrated",
  "refusing feed", "won't eat", "won't drink", "no wet diaper",
  "yellow skin", "jaundice", "blue lips", "limp",
  // diagnostic phrasing
  "is it normal", "is this normal", "should I worry", "should i worry",
  "what's wrong", "whats wrong", "diagnose", "what could", "what might",
  // medication
  "how much medicine", "dosage", "give my baby", "can I give",
  "tylenol", "crocin", "paracetamol", "ibuprofen", "antibiotic",
];

export const ESCALATION_RULES = {
  fever: "For babies under 12 months, any fever above 100.4°F (38°C) requires same-day pediatrician contact. Above 102°F at any age is same-day.",
  breathing: "Any unusual breathing pattern, fast breathing, or pulling at the chest is an immediate doctor visit.",
  feeding: "Refusing all feeds for 8+ hours, or no wet diaper for 6+ hours, needs urgent attention.",
  lethargy: "If your baby seems unusually sleepy, hard to wake, or floppy, call your pediatrician now.",
  vomiting: "More than 2 vomiting episodes, or projectile vomiting, needs same-day medical care.",
  rash: "A rash with fever, or any rash that spreads quickly, needs to be seen.",
  injury: "Any head injury, fall from height, or visible wound needs assessment.",
  default: "This is something a pediatrician needs to evaluate, not me.",
} as const;

export type MedicalCategory = keyof typeof ESCALATION_RULES;

export function detectMedicalIntent(query: string): {
  isMedical: boolean;
  category: MedicalCategory;
  matchedKeyword: string | null;
} {
  const lower = query.toLowerCase();

  for (const kw of MEDICAL_KEYWORDS) {
    if (lower.includes(kw)) {
      let category: MedicalCategory = "default";

      if (/fever|temperature/.test(lower)) category = "fever";
      else if (/breath|cough|wheeze/.test(lower)) category = "breathing";
      else if (/lethargy|lethargic|unconscious|limp/.test(lower)) category = "lethargy";
      else if (/feed|drink|eat|diaper/.test(lower)) category = "feeding";
      else if (/vomit|throw up/.test(lower)) category = "vomiting";
      else if (/rash/.test(lower)) category = "rash";
      else if (/injury|hurt|blood|bleeding|fall|head/.test(lower)) category = "injury";

      return { isMedical: true, category, matchedKeyword: kw };
    }
  }

  return { isMedical: false, category: "default", matchedKeyword: null };
}