import { Injectable, Logger } from '@nestjs/common';

/**
 * Medical Safety Service
 *
 * Detects medical concerns in user messages and provides appropriate disclaimers
 * for COPPA compliance and parental safety.
 */

export interface MedicalSafetyCheck {
  requiresDisclaimer: boolean;
  severity: 'low' | 'medium' | 'high' | 'emergency';
  detectedKeywords: string[];
  disclaimer: string | null;
  emergencyHotlines?: EmergencyContact[];
}

export interface EmergencyContact {
  name: string;
  number: string;
  description: string;
}

@Injectable()
export class MedicalSafetyService {
  private readonly logger = new Logger(MedicalSafetyService.name);

  // Emergency medical keywords that trigger immediate disclaimers
  private readonly emergencyKeywords = [
    'not breathing',
    "can't breathe",
    'cannot breathe',
    'choking',
    'unconscious',
    'passed out',
    'blue lips',
    'turning blue',
    'seizure',
    'convulsion',
    'severe bleeding',
    'head injury',
    'fell on head',
    'neck injury',
    'broken bone',
    'severe burn',
    'poisoning',
    'swallowed',
    'allergic reaction',
    'anaphylaxis',
    'heart',
  ];

  // High-priority medical keywords
  private readonly highPriorityKeywords = [
    'fever over 104',
    'high fever',
    'vomiting blood',
    'blood in stool',
    'severe pain',
    'extreme pain',
    'dehydrated',
    "won't wake up",
    'lethargic',
    'rash all over',
    'difficulty breathing',
    'wheezing badly',
    'coughing blood',
    'severe diarrhea',
  ];

  // Medium-priority medical keywords
  private readonly mediumPriorityKeywords = [
    'fever',
    'temperature',
    'vomiting',
    'diarrhea',
    'rash',
    'cough',
    'cold',
    'flu',
    'sick',
    'pain',
    'hurt',
    'ache',
    'infection',
    'medicine',
    'medication',
    'antibiotic',
    'doctor',
    'pediatrician',
    'er',
    'emergency room',
    'urgent care',
    'breathing',
    'wheezing',
    'congestion',
    'runny nose',
    'ear infection',
    'sore throat',
    'stomach ache',
    'constipation',
    'allergies',
    'hives',
  ];

  // Mental health keywords (for parental mental health)
  private readonly mentalHealthKeywords = [
    'depressed',
    'depression',
    'anxious',
    'anxiety',
    'panic attack',
    'overwhelmed',
    "can't cope",
    'suicide',
    'suicidal',
    'self harm',
    'harm myself',
    'want to die',
    'postpartum depression',
    'ppd',
    'baby blues',
    'intrusive thoughts',
  ];

  /**
   * Check a message for medical safety concerns
   */
  checkMessage(message: string): MedicalSafetyCheck {
    const lowerMessage = message.toLowerCase();
    const detectedKeywords: string[] = [];
    let severity: 'low' | 'medium' | 'high' | 'emergency' = 'low';

    // Check for emergency keywords first
    for (const keyword of this.emergencyKeywords) {
      if (lowerMessage.includes(keyword.toLowerCase())) {
        detectedKeywords.push(keyword);
        severity = 'emergency';
      }
    }

    // If emergency, return immediately
    if (severity === 'emergency') {
      this.logger.warn(
        `Emergency medical keywords detected: ${detectedKeywords.join(', ')}`,
      );
      return {
        requiresDisclaimer: true,
        severity: 'emergency',
        detectedKeywords,
        disclaimer: this.getEmergencyDisclaimer(),
        emergencyHotlines: this.getEmergencyHotlines(),
      };
    }

    // Check for high-priority keywords
    for (const keyword of this.highPriorityKeywords) {
      if (lowerMessage.includes(keyword.toLowerCase())) {
        detectedKeywords.push(keyword);
        severity = 'high';
      }
    }

    if (severity === 'high') {
      this.logger.warn(
        `High-priority medical keywords detected: ${detectedKeywords.join(', ')}`,
      );
      return {
        requiresDisclaimer: true,
        severity: 'high',
        detectedKeywords,
        disclaimer: this.getHighPriorityDisclaimer(),
        emergencyHotlines: this.getEmergencyHotlines(),
      };
    }

    // Check for medium-priority keywords
    for (const keyword of this.mediumPriorityKeywords) {
      if (lowerMessage.includes(keyword.toLowerCase())) {
        detectedKeywords.push(keyword);
        severity = 'medium';
      }
    }

    if (severity === 'medium') {
      this.logger.debug(
        `Medium-priority medical keywords detected: ${detectedKeywords.join(', ')}`,
      );
      return {
        requiresDisclaimer: true,
        severity: 'medium',
        detectedKeywords,
        disclaimer: this.getMediumPriorityDisclaimer(),
      };
    }

    // Check for mental health keywords
    for (const keyword of this.mentalHealthKeywords) {
      if (lowerMessage.includes(keyword.toLowerCase())) {
        detectedKeywords.push(keyword);
        this.logger.warn(
          `Mental health keywords detected: ${detectedKeywords.join(', ')}`,
        );
        return {
          requiresDisclaimer: true,
          severity: 'high',
          detectedKeywords,
          disclaimer: this.getMentalHealthDisclaimer(),
          emergencyHotlines: this.getMentalHealthHotlines(),
        };
      }
    }

    // No medical concerns detected
    return {
      requiresDisclaimer: false,
      severity: 'low',
      detectedKeywords: [],
      disclaimer: null,
    };
  }

  /**
   * Get emergency disclaimer for immediate medical attention
   */
  private getEmergencyDisclaimer(): string {
    return `⚠️ **EMERGENCY - SEEK IMMEDIATE MEDICAL ATTENTION**

This appears to be a medical emergency. Please:

1. **Call 911 immediately** (or your local emergency number)
2. If your child is not breathing, begin CPR if trained
3. Do not delay seeking professional medical help

**I am an AI assistant and cannot provide emergency medical care. Your child needs immediate professional medical attention.**`;
  }

  /**
   * Get high-priority disclaimer
   */
  private getHighPriorityDisclaimer(): string {
    return `⚠️ **IMPORTANT MEDICAL NOTICE**

Your question involves symptoms that may require urgent medical attention. While I can provide general information, I am not a doctor and cannot diagnose medical conditions.

**Please contact your pediatrician or seek urgent care if:**
- Symptoms are severe or worsening
- Your child appears very ill or in distress
- You are worried about your child's condition

For immediate concerns, call your doctor's office or visit urgent care. If it's an emergency, call 911.`;
  }

  /**
   * Get medium-priority disclaimer
   */
  private getMediumPriorityDisclaimer(): string {
    return `📋 **Medical Disclaimer**

I can provide general information and parenting support, but I am not a medical professional. This information is not a substitute for professional medical advice, diagnosis, or treatment.

**Always consult your pediatrician for:**
- Medical advice about your child's health
- Diagnosis of symptoms or conditions
- Treatment recommendations or medication questions

If you're concerned about your child's health, please contact your healthcare provider.`;
  }

  /**
   * Get mental health disclaimer for parents
   */
  private getMentalHealthDisclaimer(): string {
    return `💙 **Mental Health Support**

I hear that you're going through a difficult time. Your mental health is important, and you deserve support.

**I am an AI assistant and cannot provide mental health treatment or crisis intervention.**

If you're experiencing a mental health crisis or having thoughts of harming yourself:

**Please reach out to these resources immediately:**

- **National Suicide Prevention Lifeline**: 988 (call or text)
- **Crisis Text Line**: Text HOME to 741741
- **Postpartum Support International**: 1-800-944-4773

You can also:
- Contact your doctor or mental health provider
- Go to your nearest emergency room
- Call 911 if you're in immediate danger

There is help available, and you don't have to go through this alone.`;
  }

  /**
   * Get emergency hotline numbers
   */
  private getEmergencyHotlines(): EmergencyContact[] {
    return [
      {
        name: 'Emergency Services',
        number: '911',
        description: 'For immediate life-threatening emergencies',
      },
      {
        name: 'Poison Control',
        number: '1-800-222-1222',
        description: 'For poisoning emergencies and questions',
      },
      {
        name: 'Nurse Hotline',
        number: 'Contact your insurance provider',
        description: 'Many insurance plans offer 24/7 nurse advice lines',
      },
    ];
  }

  /**
   * Get mental health hotline numbers
   */
  private getMentalHealthHotlines(): EmergencyContact[] {
    return [
      {
        name: '988 Suicide & Crisis Lifeline',
        number: '988',
        description: 'Free, confidential support 24/7 for people in distress',
      },
      {
        name: 'Crisis Text Line',
        number: 'Text HOME to 741741',
        description: 'Free, 24/7 crisis support via text message',
      },
      {
        name: 'Postpartum Support International',
        number: '1-800-944-4773',
        description: 'Support for postpartum depression and anxiety',
      },
      {
        name: 'SAMHSA National Helpline',
        number: '1-800-662-4357',
        description: 'Mental health and substance abuse referrals',
      },
    ];
  }

  /**
   * Prepend disclaimer to AI response if needed
   */
  prependDisclaimer(response: string, safetyCheck: MedicalSafetyCheck): string {
    if (!safetyCheck.requiresDisclaimer || !safetyCheck.disclaimer) {
      return response;
    }

    return `${safetyCheck.disclaimer}\n\n---\n\n${response}`;
  }
}
