import { v4 as uuidv4 } from 'uuid';

/**
 * 系统经验实体 - 存储系统从对话中学习到的经验
 * 用于系统自我进化
 */
export class SystemExperienceEntity {
  id: string;

  /** 经验类型 */
  experienceType: ExperienceType;

  /** 经验内容/描述 */
  content: string;

  /** 经验的置信度 0-100 */
  confidence: number;

  /** 应用场景描述 */
  scenario: string;

  /** 相关移民类别 */
  relatedCategory?: string;

  /** 来源对话ID列表 */
  sourceConversationIds: string[];

  /** 验证状态 */
  verificationStatus: VerificationStatus;

  /** 验证者（管理员）ID */
  verifiedBy?: string;

  /** 验证时间 */
  verifiedAt?: Date;

  /** 使用次数（被应用到对话中） */
  usageCount: number;

  /** 正面反馈次数 */
  positiveCount: number;

  /** 负面反馈次数 */
  negativeCount: number;

  /** 内容向量 */
  embedding?: number[];

  /** 是否激活使用 */
  isActive: boolean;

  createdAt: Date;
  updatedAt: Date;

  private constructor() {}

  static create(params: {
    experienceType: ExperienceType;
    content: string;
    scenario: string;
    relatedCategory?: string;
    sourceConversationId: string;
    confidence?: number;
  }): SystemExperienceEntity {
    const experience = new SystemExperienceEntity();
    experience.id = uuidv4();
    experience.experienceType = params.experienceType;
    experience.content = params.content;
    experience.scenario = params.scenario;
    experience.relatedCategory = params.relatedCategory;
    experience.sourceConversationIds = [params.sourceConversationId];
    experience.confidence = params.confidence ?? 50;
    experience.verificationStatus = VerificationStatus.PENDING;
    experience.usageCount = 0;
    experience.positiveCount = 0;
    experience.negativeCount = 0;
    experience.isActive = false; // 默认不激活，需要验证后才激活
    experience.createdAt = new Date();
    experience.updatedAt = new Date();
    return experience;
  }

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

  /**
   * 添加来源对话
   */
  addSourceConversation(conversationId: string): void {
    if (!this.sourceConversationIds.includes(conversationId)) {
      this.sourceConversationIds.push(conversationId);
      // 多个对话都产生相同经验，提高置信度
      this.confidence = Math.min(100, this.confidence + 5);
      this.updatedAt = new Date();
    }
  }

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

  /**
   * 管理员验证通过
   */
  approve(adminId: string): void {
    this.verificationStatus = VerificationStatus.APPROVED;
    this.verifiedBy = adminId;
    this.verifiedAt = new Date();
    this.isActive = true;
    this.confidence = Math.min(100, this.confidence + 20);
    this.updatedAt = new Date();
  }

  /**
   * 管理员验证拒绝
   */
  reject(adminId: string): void {
    this.verificationStatus = VerificationStatus.REJECTED;
    this.verifiedBy = adminId;
    this.verifiedAt = new Date();
    this.isActive = false;
    this.updatedAt = new Date();
  }

  /**
   * 记录使用
   */
  recordUsage(): void {
    this.usageCount++;
  }

  /**
   * 记录反馈
   */
  recordFeedback(positive: boolean): void {
    if (positive) {
      this.positiveCount++;
      this.confidence = Math.min(100, this.confidence + 2);
    } else {
      this.negativeCount++;
      this.confidence = Math.max(0, this.confidence - 5);

      // 负面反馈过多则自动停用
      if (this.negativeCount > 5 && this.negativeCount > this.positiveCount * 2) {
        this.isActive = false;
        this.verificationStatus = VerificationStatus.DEPRECATED;
      }
    }
    this.updatedAt = new Date();
  }

  /**
   * 合并相似经验
   */
  mergeWith(other: SystemExperienceEntity): void {
    // 合并来源对话
    other.sourceConversationIds.forEach(id => {
      if (!this.sourceConversationIds.includes(id)) {
        this.sourceConversationIds.push(id);
      }
    });

    // 合并统计数据
    this.usageCount += other.usageCount;
    this.positiveCount += other.positiveCount;
    this.negativeCount += other.negativeCount;

    // 重新计算置信度
    this.confidence = Math.min(100, (this.confidence + other.confidence) / 2 + 10);

    this.updatedAt = new Date();
  }
}

export enum ExperienceType {
  // 问答相关
  COMMON_QUESTION = 'COMMON_QUESTION',        // 常见问题
  ANSWER_TEMPLATE = 'ANSWER_TEMPLATE',        // 回答模板
  CLARIFICATION = 'CLARIFICATION',            // 澄清方式

  // 用户行为
  USER_PATTERN = 'USER_PATTERN',              // 用户行为模式
  CONVERSION_TRIGGER = 'CONVERSION_TRIGGER',  // 转化触发点

  // 知识相关
  KNOWLEDGE_GAP = 'KNOWLEDGE_GAP',            // 知识缺口
  KNOWLEDGE_UPDATE = 'KNOWLEDGE_UPDATE',      // 知识更新

  // 对话技巧
  CONVERSATION_SKILL = 'CONVERSATION_SKILL',  // 对话技巧
  OBJECTION_HANDLING = 'OBJECTION_HANDLING',  // 异议处理

  // 其他
  CUSTOM = 'CUSTOM',                          // 自定义经验
}

export enum VerificationStatus {
  PENDING = 'PENDING',       // 待验证
  APPROVED = 'APPROVED',     // 已通过
  REJECTED = 'REJECTED',     // 已拒绝
  DEPRECATED = 'DEPRECATED', // 已弃用
}
