import { Controller, Get, Post, Body, Query } from '@nestjs/common';
import { MemoryService } from '../../application/services/memory.service';
import { ExperienceType } from '../../domain/entities/system-experience.entity';

/**
 * 内部 API 控制器
 * 仅供其他微服务调用（如 evolution-service）
 */
@Controller('internal/experiences')
export class InternalMemoryController {
  constructor(private memoryService: MemoryService) {}

  /**
   * 保存经验（由 evolution-service 调用）
   */
  @Post()
  async saveExperience(@Body() dto: {
    experienceType: string;
    content: string;
    scenario: string;
    confidence: number;
    relatedCategory?: string;
    sourceConversationId: string;
  }) {
    const experience = await this.memoryService.extractAndSaveExperience({
      experienceType: dto.experienceType as ExperienceType,
      content: dto.content,
      scenario: dto.scenario,
      confidence: dto.confidence,
      relatedCategory: dto.relatedCategory,
      sourceConversationId: dto.sourceConversationId,
    });
    return {
      success: true,
      data: {
        id: experience.id,
        experienceType: experience.experienceType,
        content: experience.content,
        scenario: experience.scenario,
        confidence: experience.confidence,
      },
    };
  }

  /**
   * 查找相似经验（用于去重检查）
   */
  @Post('find-similar')
  async findSimilarExperiences(@Body() dto: {
    experienceType: string;
    relatedCategory?: string;
  }) {
    // 返回同类型同类别的经验用于客户端去重
    // 实际的相似度检查在客户端进行
    const stats = await this.memoryService.getExperienceStatistics();
    return {
      success: true,
      data: {
        totalByType: stats.byType,
      },
    };
  }

  /**
   * 获取经验统计
   */
  @Get('statistics')
  async getStatistics() {
    const stats = await this.memoryService.getExperienceStatistics();
    return {
      success: true,
      data: {
        total: stats.total,
        byStatus: stats.byStatus,
        byType: stats.byType,
      },
    };
  }

  /**
   * 统计经验数量
   */
  @Get('count')
  async countExperiences(
    @Query('status') status?: string,
    @Query('isActive') isActive?: string,
  ) {
    const stats = await this.memoryService.getExperienceStatistics();

    let count = stats.total;
    if (status && stats.byStatus[status as keyof typeof stats.byStatus]) {
      count = stats.byStatus[status as keyof typeof stats.byStatus];
    }

    return {
      success: true,
      data: { count },
    };
  }
}
