import { invoke } from '@tauri-apps/api/core';
import {
  RagGroundingRequest,
  RagGroundingResponse,
  RagGroundingConfig,
  RagGroundingConfigInfo,
  RagGroundingQueryOptions,
  RagGroundingQueryResult,
  RagGroundingServiceStatus,
  RagGroundingStats,
  DEFAULT_RAG_GROUNDING_CONFIG,
} from '../types/ragGrounding';

/**
 * RAG Grounding 服务
 * 提供基于检索增强生成的智能问答功能
 */
export class RagGroundingService {
  private static instance: RagGroundingService;
  private stats: RagGroundingStats = {
    totalQueries: 0,
    successfulQueries: 0,
    failedQueries: 0,
    averageResponseTime: 0,
    fastestResponseTime: Infinity,
    slowestResponseTime: 0,
  };

  private constructor() {}

  /**
   * 获取服务单例实例
   */
  public static getInstance(): RagGroundingService {
    if (!RagGroundingService.instance) {
      RagGroundingService.instance = new RagGroundingService();
    }
    return RagGroundingService.instance;
  }

  /**
   * 执行 RAG Grounding 查询
   */
  public async queryRagGrounding(
    userInput: string,
    options: RagGroundingQueryOptions = {}
  ): Promise<RagGroundingQueryResult> {
    const startTime = new Date();
    this.stats.totalQueries++;

    try {
      // 构建请求配置
      const config: RagGroundingConfig = {
        ...DEFAULT_RAG_GROUNDING_CONFIG,
        ...options.customConfig,
      };

      // 构建请求
      const request: RagGroundingRequest = {
        user_input: userInput,
        config,
        session_id: options.sessionId,
        include_history: options.includeHistory,
        max_history_messages: options.maxHistoryMessages,
        system_prompt: options.systemPrompt,
      };

      console.log('🔍 发起RAG Grounding查询:', { userInput, options });

      // 调用后端命令
      const response = await invoke<RagGroundingResponse>('query_rag_grounding', {
        request,
      });

      const endTime = new Date();
      const totalTime = endTime.getTime() - startTime.getTime();

      // 更新统计信息
      this.updateStats(true, totalTime);

      // 详细的控制台日志输出
      console.group('🎯 RAG Grounding 查询详情');
      console.log('📝 查询内容:', userInput);
      console.log('🔧 配置信息:', config);
      console.log('💬 AI 回答:', response.answer);
      console.log('⏱️ 后端响应时间:', response.response_time_ms + 'ms');
      console.log('🕐 前端总耗时:', totalTime + 'ms');
      console.log('🤖 使用模型:', response.model_used);

      if (response.grounding_metadata) {
        console.log('📊 Grounding 元数据:');
        console.log('  🔍 搜索查询:', response.grounding_metadata.search_queries);
        console.log('  📚 来源数量:', response.grounding_metadata.sources.length);

        if (response.grounding_metadata.sources.length > 0) {
          console.log('  📖 详细来源:');
          response.grounding_metadata.sources.forEach((source, index) => {
            console.log(`    ${index + 1}. 标题: ${source.title}`);
            if (source.content) {
              const contentStr = typeof source.content === 'string'
                ? source.content
                : JSON.stringify(source.content);
              console.log(`       内容: ${contentStr.substring(0, 100)}...`);
            }
            if (source.uri) {
              console.log(`       URI: ${source.uri}`);
            }
          });
        }
      }

      console.log('📈 服务统计:', {
        totalQueries: this.stats.totalQueries + 1,
        successRate: ((this.stats.successfulQueries + 1) / (this.stats.totalQueries + 1) * 100).toFixed(1) + '%',
        avgResponseTime: Math.round((this.stats.averageResponseTime * this.stats.totalQueries + totalTime) / (this.stats.totalQueries + 1)) + 'ms'
      });
      console.groupEnd();

      console.log('✅ RAG Grounding查询成功:', response);

      return {
        success: true,
        data: response,
        startTime,
        endTime,
        totalTime,
      };
    } catch (error) {
      const endTime = new Date();
      const totalTime = endTime.getTime() - startTime.getTime();

      // 更新统计信息
      this.updateStats(false, totalTime);

      console.error('❌ RAG Grounding查询失败:', error);

      return {
        success: false,
        error: this.formatError(error),
        startTime,
        endTime,
        totalTime,
      };
    }
  }

  /**
   * 测试 RAG Grounding 连接
   */
  public async testConnection(): Promise<RagGroundingServiceStatus> {
    const lastChecked = new Date();

    try {
      console.log('🔧 测试RAG Grounding连接');

      const connectionTest = await invoke<string>('test_rag_grounding_connection');
      const config = await this.getConfig();

      console.log('✅ RAG Grounding连接测试成功:', connectionTest);

      return {
        available: true,
        lastChecked,
        connectionTest,
        config,
      };
    } catch (error) {
      console.error('❌ RAG Grounding连接测试失败:', error);

      return {
        available: false,
        lastChecked,
        connectionTest: this.formatError(error),
      };
    }
  }

  /**
   * 获取 RAG Grounding 配置信息
   */
  public async getConfig(): Promise<RagGroundingConfigInfo> {
    try {
      console.log('📋 获取RAG Grounding配置信息');

      const config = await invoke<RagGroundingConfigInfo>('get_rag_grounding_config');

      console.log('✅ 获取RAG Grounding配置成功:', config);

      return config;
    } catch (error) {
      console.error('❌ 获取RAG Grounding配置失败:', error);
      throw new Error(`获取配置失败: ${this.formatError(error)}`);
    }
  }

  /**
   * 获取服务统计信息
   */
  public getStats(): RagGroundingStats {
    return { ...this.stats };
  }

  /**
   * 重置统计信息
   */
  public resetStats(): void {
    this.stats = {
      totalQueries: 0,
      successfulQueries: 0,
      failedQueries: 0,
      averageResponseTime: 0,
      fastestResponseTime: Infinity,
      slowestResponseTime: 0,
    };
  }

  /**
   * 更新统计信息
   */
  private updateStats(success: boolean, responseTime: number): void {
    if (success) {
      this.stats.successfulQueries++;
    } else {
      this.stats.failedQueries++;
    }

    // 更新响应时间统计
    if (responseTime < this.stats.fastestResponseTime) {
      this.stats.fastestResponseTime = responseTime;
    }
    if (responseTime > this.stats.slowestResponseTime) {
      this.stats.slowestResponseTime = responseTime;
    }

    // 计算平均响应时间
    const totalResponseTime = this.stats.averageResponseTime * (this.stats.totalQueries - 1) + responseTime;
    this.stats.averageResponseTime = totalResponseTime / this.stats.totalQueries;

    this.stats.lastQueryTime = new Date();
  }

  /**
   * 格式化错误信息
   */
  private formatError(error: any): string {
    if (typeof error === 'string') {
      return error;
    }
    if (error?.message) {
      return error.message;
    }
    return JSON.stringify(error);
  }
}

/**
 * 导出服务实例
 */
export const ragGroundingService = RagGroundingService.getInstance();

/**
 * 便捷方法：执行 RAG Grounding 查询
 */
export async function queryRagGrounding(
  userInput: string,
  options?: RagGroundingQueryOptions
): Promise<RagGroundingQueryResult> {
  return ragGroundingService.queryRagGrounding(userInput, options);
}

/**
 * 便捷方法：测试 RAG Grounding 连接
 */
export async function testRagGroundingConnection(): Promise<RagGroundingServiceStatus> {
  return ragGroundingService.testConnection();
}

/**
 * 便捷方法：获取 RAG Grounding 配置
 */
export async function getRagGroundingConfig(): Promise<RagGroundingConfigInfo> {
  return ragGroundingService.getConfig();
}

/**
 * 便捷方法：获取 RAG Grounding 统计信息
 */
export function getRagGroundingStats(): RagGroundingStats {
  return ragGroundingService.getStats();
}
