import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

/**
 * 经验数据传输对象
 */
export interface ExperienceDto {
  id: string;
  experienceType: string;
  content: string;
  scenario: string;
  confidence: number;
  relatedCategory?: string;
  sourceConversationIds: string[];
  verificationStatus: string;
  isActive: boolean;
  usageCount: number;
  positiveCount: number;
  negativeCount: number;
  createdAt: Date;
  updatedAt: Date;
}

/**
 * 经验统计数据传输对象
 */
export interface ExperienceStatisticsDto {
  total: number;
  byStatus: Record<string, number>;
  byType: Record<string, number>;
}

/**
 * API 响应类型
 */
interface ApiResponse<T> {
  success: boolean;
  data: T;
}

/**
 * Knowledge Service 客户端
 * 用于调用 knowledge-service 的内部 API
 */
@Injectable()
export class KnowledgeClient {
  private readonly baseUrl: string;

  constructor(private configService: ConfigService) {
    this.baseUrl = this.configService.get<string>(
      'KNOWLEDGE_SERVICE_URL',
      'http://knowledge-service:3003',
    );
  }

  /**
   * 保存经验
   */
  async saveExperience(params: {
    experienceType: string;
    content: string;
    scenario: string;
    confidence: number;
    relatedCategory?: string;
    sourceConversationId: string;
  }): Promise<ExperienceDto> {
    const url = `${this.baseUrl}/api/internal/experiences`;

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(params),
      });
      const data = (await response.json()) as ApiResponse<ExperienceDto>;

      if (!data.success) {
        throw new Error('Failed to save experience');
      }

      return data.data;
    } catch (error) {
      console.error('[KnowledgeClient] Error saving experience:', error);
      throw error;
    }
  }

  /**
   * 获取经验统计
   */
  async getStatistics(): Promise<ExperienceStatisticsDto> {
    const url = `${this.baseUrl}/api/internal/experiences/statistics`;

    try {
      const response = await fetch(url);
      const data = (await response.json()) as ApiResponse<ExperienceStatisticsDto>;

      if (!data.success) {
        throw new Error('Failed to get statistics');
      }

      return data.data;
    } catch (error) {
      console.error('[KnowledgeClient] Error getting statistics:', error);
      throw error;
    }
  }

  /**
   * 统计经验数量
   */
  async countExperiences(options: {
    status?: string;
    isActive?: boolean;
  }): Promise<number> {
    const params = new URLSearchParams();

    if (options.status) params.append('status', options.status);
    if (options.isActive !== undefined) {
      params.append('isActive', options.isActive.toString());
    }

    const url = `${this.baseUrl}/api/internal/experiences/count?${params.toString()}`;

    try {
      const response = await fetch(url);
      const data = (await response.json()) as ApiResponse<{ count: number }>;

      if (!data.success) {
        throw new Error('Failed to count experiences');
      }

      return data.data.count;
    } catch (error) {
      console.error('[KnowledgeClient] Error counting experiences:', error);
      throw error;
    }
  }
}
