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

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

  /**
   * Filters knowledge base content based on keywords.
   * In a real implementation, this might use semantic search or simple keyword filtering.
   * For now, we'll implement a simple relevance-based filtering.
   */
  filterContent(content: string, keywords: string[]): string {
    if (!keywords || keywords.length === 0) {
      return content;
    }

    this.logger.log(
      `Filtering content with ${keywords.length} keywords: ${keywords.join(', ')}`,
    );

    // Split content into paragraphs or sections
    const sections = content.split(/\n\n+/);

    // Score each section based on keyword matches (case-insensitive)
    const scoredSections = sections.map((section) => {
      let score = 0;
      const lowerSection = section.toLowerCase();

      keywords.forEach((keyword) => {
        const lowerKeyword = keyword.toLowerCase();
        const matches = lowerSection.split(lowerKeyword).length - 1;
        score += matches;
      });

      return { section, score };
    });

    // Sort sections by score and take the most relevant ones
    // If content is huge, we might want to limit the total length
    const relevantSections = scoredSections
      .filter((s) => s.score > 0)
      .sort((a, b) => b.score - a.score)
      .map((s) => s.section);

    // If no sections matched, return a sample or the original content
    if (relevantSections.length === 0) {
      this.logger.warn(
        'No sections matched keywords, returning first 5000 characters',
      );
      return content.substring(0, 5000);
    }

    this.logger.log(
      `Found ${relevantSections.length} relevant sections out of ${sections.length}`,
    );

    // Return combined relevant sections (up to a reasonable limit)
    return relevantSections.join('\n\n').substring(0, 50000);
  }
}
