import { v4 as uuidv4 } from 'uuid';

/**
 * 知识文章实体 - 存储移民相关的知识内容
 */
export class KnowledgeArticleEntity {
  id: string;

  /** 文章标题 */
  title: string;

  /** 文章内容（纯文本或Markdown） */
  content: string;

  /** 内容摘要（用于预览） */
  summary: string;

  /** 移民类别: QMAS, GEP, IANG, TTPS, CIES, TechTAS */
  category: string;

  /** 内容标签 */
  tags: string[];

  /** 来源: MANUAL(手动添加), CRAWL(爬取), EXTRACT(对话提取) */
  source: KnowledgeSource;

  /** 来源URL（如果是爬取的） */
  sourceUrl?: string;

  /** 内容向量（用于语义搜索） */
  embedding?: number[];

  /** 是否已发布 */
  isPublished: boolean;

  /** 引用次数（被对话引用） */
  citationCount: number;

  /** 点赞数（用户反馈有用） */
  helpfulCount: number;

  /** 点踩数（用户反馈无用） */
  unhelpfulCount: number;

  /** 质量评分 0-100 */
  qualityScore: number;

  /** 创建者ID */
  createdBy?: string;

  /** 最后更新者ID */
  updatedBy?: string;

  createdAt: Date;
  updatedAt: Date;

  private constructor() {}

  static create(params: {
    title: string;
    content: string;
    category: string;
    tags?: string[];
    source: KnowledgeSource;
    sourceUrl?: string;
    createdBy?: string;
  }): KnowledgeArticleEntity {
    const article = new KnowledgeArticleEntity();
    article.id = uuidv4();
    article.title = params.title;
    article.content = params.content;
    article.summary = KnowledgeArticleEntity.generateSummary(params.content);
    article.category = params.category;
    article.tags = params.tags || [];
    article.source = params.source;
    article.sourceUrl = params.sourceUrl;
    article.isPublished = false;
    article.citationCount = 0;
    article.helpfulCount = 0;
    article.unhelpfulCount = 0;
    article.qualityScore = 50; // 默认中等质量
    article.createdBy = params.createdBy;
    article.createdAt = new Date();
    article.updatedAt = new Date();
    return article;
  }

  static fromPersistence(data: Partial<KnowledgeArticleEntity>): KnowledgeArticleEntity {
    const article = new KnowledgeArticleEntity();
    Object.assign(article, data);
    return article;
  }

  /**
   * 生成内容摘要
   */
  private static generateSummary(content: string, maxLength = 200): string {
    const plainText = content
      .replace(/#+\s/g, '')  // 移除Markdown标题
      .replace(/\*\*/g, '')   // 移除加粗
      .replace(/\n+/g, ' ')   // 换行转空格
      .trim();

    if (plainText.length <= maxLength) {
      return plainText;
    }
    return plainText.substring(0, maxLength) + '...';
  }

  /**
   * 更新内容
   */
  updateContent(title: string, content: string, updatedBy?: string): void {
    this.title = title;
    this.content = content;
    this.summary = KnowledgeArticleEntity.generateSummary(content);
    this.updatedBy = updatedBy;
    this.updatedAt = new Date();
    // 内容更新后需要重新生成向量
    this.embedding = undefined;
  }

  /**
   * 设置内容向量
   */
  setEmbedding(embedding: number[]): void {
    this.embedding = embedding;
    this.updatedAt = new Date();
  }

  /**
   * 发布文章
   */
  publish(): void {
    this.isPublished = true;
    this.updatedAt = new Date();
  }

  /**
   * 取消发布
   */
  unpublish(): void {
    this.isPublished = false;
    this.updatedAt = new Date();
  }

  /**
   * 增加引用次数
   */
  incrementCitation(): void {
    this.citationCount++;
    this.recalculateQualityScore();
  }

  /**
   * 记录用户反馈
   */
  recordFeedback(helpful: boolean): void {
    if (helpful) {
      this.helpfulCount++;
    } else {
      this.unhelpfulCount++;
    }
    this.recalculateQualityScore();
  }

  /**
   * 重新计算质量评分
   */
  private recalculateQualityScore(): void {
    // 基础分50分
    let score = 50;

    // 引用次数加分（最多+20）
    score += Math.min(this.citationCount * 2, 20);

    // 用户反馈（最多±30）
    const totalFeedback = this.helpfulCount + this.unhelpfulCount;
    if (totalFeedback > 0) {
      const helpfulRatio = this.helpfulCount / totalFeedback;
      score += Math.round((helpfulRatio - 0.5) * 60);
    }

    this.qualityScore = Math.max(0, Math.min(100, score));
  }
}

export enum KnowledgeSource {
  MANUAL = 'MANUAL',      // 手动添加
  CRAWL = 'CRAWL',        // 网页爬取
  EXTRACT = 'EXTRACT',    // 对话提取
  IMPORT = 'IMPORT',      // 批量导入
}
