import { Injectable } from '@nestjs/common';
import { ExperienceExtractorService } from '../../infrastructure/claude/experience-extractor.service';
import { ConversationClient } from '../../adapters/outbound/clients/conversation.client';
import { KnowledgeClient } from '../../adapters/outbound/clients/knowledge.client';
import { v4 as uuidv4 } from 'uuid';
import { EvolutionTaskResult } from '../dtos/evolution.dto';

/**
 * 进化服务
 * 负责系统的自我学习和进化
 *
 * 遵循微服务架构原则：
 * - 通过 ConversationClient 调用 conversation-service API 获取对话数据
 * - 通过 KnowledgeClient 调用 knowledge-service API 保存经验
 * - 不直接访问其他服务的数据库表
 */
@Injectable()
export class EvolutionService {
  constructor(
    private conversationClient: ConversationClient,
    private knowledgeClient: KnowledgeClient,
    private experienceExtractor: ExperienceExtractorService,
  ) {}

  /**
   * 执行进化任务 - 分析最近的对话并提取经验
   */
  async runEvolutionTask(options?: {
    hoursBack?: number;
    limit?: number;
    minMessageCount?: number;
  }): Promise<EvolutionTaskResult> {
    const taskId = uuidv4();
    const hoursBack = options?.hoursBack || 24;
    const limit = options?.limit || 50;
    const minMessageCount = options?.minMessageCount || 4;

    const result: EvolutionTaskResult = {
      taskId,
      status: 'success',
      conversationsAnalyzed: 0,
      experiencesExtracted: 0,
      knowledgeGapsFound: 0,
      errors: [],
    };

    console.log(`[Evolution] Starting task ${taskId}`);

    try {
      // 1. 通过 API 获取待分析的对话
      const conversations = await this.conversationClient.findConversations({
        status: 'ENDED',
        hoursBack,
        minMessageCount,
        limit,
      });

      console.log(`[Evolution] Found ${conversations.length} conversations to analyze`);

      // 2. 分析每个对话
      const allKnowledgeGaps: string[] = [];

      for (const conversation of conversations) {
        try {
          // 通过 API 获取对话消息
          const messages = await this.conversationClient.getMessages(conversation.id);

          // 分析对话
          const analysis = await this.experienceExtractor.analyzeConversation({
            conversationId: conversation.id,
            messages: messages.map(m => ({
              role: m.role as 'user' | 'assistant',
              content: m.content,
            })),
            category: conversation.category,
            hasConverted: conversation.hasConverted,
            rating: conversation.rating,
          });

          // 通过 API 保存提取的经验到 knowledge-service
          for (const exp of analysis.experiences) {
            try {
              await this.knowledgeClient.saveExperience({
                experienceType: exp.type,
                content: exp.content,
                scenario: exp.scenario,
                confidence: exp.confidence,
                relatedCategory: exp.relatedCategory,
                sourceConversationId: conversation.id,
              });
              result.experiencesExtracted++;
            } catch (saveError) {
              console.error(`[Evolution] Failed to save experience:`, saveError);
              result.errors.push(`Save experience: ${(saveError as Error).message}`);
            }
          }

          // 收集知识缺口
          allKnowledgeGaps.push(...analysis.knowledgeGaps);

          result.conversationsAnalyzed++;
        } catch (error) {
          result.errors.push(`Conversation ${conversation.id}: ${(error as Error).message}`);
        }
      }

      // 3. 汇总知识缺口
      const uniqueGaps = [...new Set(allKnowledgeGaps)];
      result.knowledgeGapsFound = uniqueGaps.length;

      console.log(`[Evolution] Task ${taskId} completed:`, result);

      if (result.errors.length > 0) {
        result.status = 'partial';
      }

      return result;
    } catch (error) {
      console.error(`[Evolution] Task ${taskId} failed:`, error);
      result.status = 'failed';
      result.errors.push((error as Error).message);
      return result;
    }
  }

  /**
   * 获取进化统计信息
   */
  async getEvolutionStatistics(): Promise<{
    totalExperiences: number;
    pendingExperiences: number;
    approvedExperiences: number;
    activeExperiences: number;
    recentConversationsAnalyzed: number;
    topExperienceTypes: Array<{ type: string; count: number }>;
  }> {
    // 通过 API 获取经验统计
    const stats = await this.knowledgeClient.getStatistics();

    // 通过 API 获取最近分析的对话数（过去7天）
    const recentConversations = await this.conversationClient.countConversations({
      status: 'ENDED',
      daysBack: 7,
    });

    // 转换类型分布为数组格式
    const topExperienceTypes = Object.entries(stats.byType)
      .map(([type, count]) => ({ type, count: count as number }))
      .sort((a, b) => b.count - a.count)
      .slice(0, 5);

    return {
      totalExperiences: stats.total,
      pendingExperiences: stats.byStatus['PENDING'] || 0,
      approvedExperiences: stats.byStatus['APPROVED'] || 0,
      activeExperiences: stats.byStatus['ACTIVE'] || 0,
      recentConversationsAnalyzed: recentConversations,
      topExperienceTypes,
    };
  }

  /**
   * 获取系统健康报告
   */
  async getSystemHealthReport(): Promise<{
    overall: 'healthy' | 'warning' | 'critical';
    metrics: Array<{
      name: string;
      value: number;
      threshold: number;
      status: 'good' | 'warning' | 'critical';
    }>;
    recommendations: string[];
  }> {
    const stats = await this.getEvolutionStatistics();
    const metrics: Array<{
      name: string;
      value: number;
      threshold: number;
      status: 'good' | 'warning' | 'critical';
    }> = [];
    const recommendations: string[] = [];

    // 检查待验证经验堆积
    const pendingRatio = stats.pendingExperiences / Math.max(1, stats.totalExperiences);
    metrics.push({
      name: '待验证经验比例',
      value: Math.round(pendingRatio * 100),
      threshold: 50,
      status: pendingRatio > 0.5 ? 'warning' : 'good',
    });
    if (pendingRatio > 0.5) {
      recommendations.push('待验证经验过多，建议及时审核');
    }

    // 检查活跃经验数量
    metrics.push({
      name: '活跃经验数量',
      value: stats.activeExperiences,
      threshold: 10,
      status: stats.activeExperiences < 10 ? 'warning' : 'good',
    });
    if (stats.activeExperiences < 10) {
      recommendations.push('活跃经验较少，系统学习能力有限');
    }

    // 检查最近分析的对话
    metrics.push({
      name: '近7天分析对话数',
      value: stats.recentConversationsAnalyzed,
      threshold: 50,
      status: stats.recentConversationsAnalyzed < 50 ? 'warning' : 'good',
    });

    // 计算总体健康状态
    const criticalCount = metrics.filter(m => m.status === 'critical').length;
    const warningCount = metrics.filter(m => m.status === 'warning').length;

    let overall: 'healthy' | 'warning' | 'critical' = 'healthy';
    if (criticalCount > 0) {
      overall = 'critical';
    } else if (warningCount > 1) {
      overall = 'warning';
    }

    return { overall, metrics, recommendations };
  }
}
