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

/**
 * Response Moderation Service
 *
 * Filters and moderates AI responses to ensure appropriate content
 * for parenting application.
 */

export interface ModerationResult {
  isAppropriate: boolean;
  filtered: boolean;
  reason?: string;
  filteredResponse?: string;
}

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

  // Inappropriate content patterns
  private readonly inappropriatePatterns = [
    // Harmful medical advice
    /do not (see|consult|contact) (a |your )?doctor/i,
    /you don't need (a |to see )?doctor/i,
    /skip the doctor/i,
    /doctors? (are|is) (unnecessary|not needed)/i,

    // Dangerous instructions
    /give (your )?baby (alcohol|wine|beer)/i,
    /shake (the |your )?baby/i,
    /leave (the |your )?baby (alone|unattended)/i,
    /don't vaccinate/i,
    /vaccines? (are|is) (dangerous|harmful|bad)/i,

    // Inappropriate content
    /\b(fuck|shit|damn|hell)\b/i,
    /sexual/i,
    /abuse/i,
    /violent/i,

    // Medical diagnosis (AI should never diagnose)
    /I (can )?diagnose (this|your child|the baby) (as|with)/i,
    /(your child|the baby) (has|definitely has)/i,
    /definitely (is|has) (autism|adhd|cancer|diabetes)/i,
  ];

  // Patterns that need to be softened/qualified
  private readonly qualificationNeeded = [
    {
      pattern: /your child (should|must|needs to)/i,
      replacement: 'many pediatricians recommend that children',
    },
    {
      pattern: /you (should|must|need to)/i,
      replacement: 'you may want to consider',
    },
    {
      pattern: /always/i,
      replacement: 'typically',
    },
    {
      pattern: /never/i,
      replacement: 'generally should not',
    },
    {
      pattern: /this (is|means)/i,
      replacement: 'this could be',
    },
  ];

  /**
   * Moderate AI response before returning to user
   */
  moderateResponse(response: string): ModerationResult {
    // Check for inappropriate content
    for (const pattern of this.inappropriatePatterns) {
      if (pattern.test(response)) {
        this.logger.warn(
          `Inappropriate content detected in AI response: ${pattern.source}`,
        );
        return {
          isAppropriate: false,
          filtered: true,
          reason: 'Contains inappropriate or potentially harmful content',
          filteredResponse: this.getFilteredResponse(),
        };
      }
    }

    // Apply qualification softening
    let filteredResponse = response;
    let wasFiltered = false;

    for (const qualification of this.qualificationNeeded) {
      const originalResponse = filteredResponse;
      filteredResponse = filteredResponse.replace(
        qualification.pattern,
        qualification.replacement,
      );

      if (filteredResponse !== originalResponse) {
        wasFiltered = true;
        this.logger.debug(
          `Softened language in AI response: ${qualification.pattern.source}`,
        );
      }
    }

    // Ensure medical disclaimer for medical topics
    if (
      this.containsMedicalContent(filteredResponse) &&
      !this.hasDisclaimer(filteredResponse)
    ) {
      filteredResponse = this.addGeneralDisclaimer(filteredResponse);
      wasFiltered = true;
    }

    return {
      isAppropriate: true,
      filtered: wasFiltered,
      filteredResponse: wasFiltered ? filteredResponse : undefined,
    };
  }

  /**
   * Check if response contains medical content
   */
  private containsMedicalContent(response: string): boolean {
    const medicalTerms = [
      /symptom/i,
      /treatment/i,
      /medicine/i,
      /medication/i,
      /diagnosis/i,
      /condition/i,
      /disease/i,
      /illness/i,
      /infection/i,
      /fever/i,
      /rash/i,
      /pain/i,
    ];

    return medicalTerms.some((term) => term.test(response));
  }

  /**
   * Check if response already has a disclaimer
   */
  private hasDisclaimer(response: string): boolean {
    const disclaimerKeywords = [
      /not a (medical|healthcare) professional/i,
      /consult (your|a) (doctor|pediatrician|healthcare provider)/i,
      /medical disclaimer/i,
      /not (medical|healthcare) advice/i,
    ];

    return disclaimerKeywords.some((keyword) => keyword.test(response));
  }

  /**
   * Add general medical disclaimer to response
   */
  private addGeneralDisclaimer(response: string): string {
    const disclaimer = `\n\n*Note: This information is for general knowledge only and is not medical advice. Please consult your pediatrician for medical concerns.*`;
    return response + disclaimer;
  }

  /**
   * Get filtered/safe response when inappropriate content detected
   */
  private getFilteredResponse(): string {
    return `I apologize, but I'm not able to provide that type of advice. As an AI assistant focused on parenting support, I need to stay within safe and appropriate boundaries.

For medical concerns, please consult your pediatrician or healthcare provider. They can provide proper diagnosis and treatment recommendations.

Is there something else I can help you with regarding childcare, routines, or general parenting questions?`;
  }

  /**
   * Validate response length and quality
   */
  validateResponseQuality(response: string): {
    isValid: boolean;
    reason?: string;
  } {
    // Check minimum length
    if (response.trim().length < 20) {
      return {
        isValid: false,
        reason: 'Response too short',
      };
    }

    // Check maximum length
    if (response.length > 5000) {
      return {
        isValid: false,
        reason: 'Response too long',
      };
    }

    // Check for repetition (same word/phrase repeated many times)
    const words = response.toLowerCase().split(/\s+/);
    const wordCounts = new Map<string, number>();

    for (const word of words) {
      if (word.length > 3) {
        wordCounts.set(word, (wordCounts.get(word) || 0) + 1);
      }
    }

    for (const [word, count] of wordCounts) {
      if (count > words.length * 0.15) {
        return {
          isValid: false,
          reason: `Excessive repetition detected (word: "${word}")`,
        };
      }
    }

    return { isValid: true };
  }

  /**
   * Filter profanity and inappropriate language
   */
  filterProfanity(text: string): string {
    const profanityList = [
      { pattern: /\bf+u+c+k+/gi, replacement: 'f***' },
      { pattern: /\bs+h+i+t+/gi, replacement: 's***' },
      { pattern: /\bd+a+m+n+/gi, replacement: 'd***' },
      { pattern: /\ba+s+s+h+o+l+e+/gi, replacement: 'a*******' },
      { pattern: /\bb+i+t+c+h+/gi, replacement: 'b****' },
      { pattern: /\bc+r+a+p+/gi, replacement: 'c***' },
    ];

    let filtered = text;
    for (const { pattern, replacement } of profanityList) {
      filtered = filtered.replace(pattern, replacement);
    }

    return filtered;
  }
}
