import { invoke } from '@tauri-apps/api/core';
import {
  ConversationSession,
  ConversationMessage,
  ConversationHistory,
  CreateConversationSessionRequest,
  AddMessageRequest,
  ConversationHistoryQuery,
  MultiTurnConversationRequest,
  MultiTurnConversationResponse,
  ConversationStats,
  SessionListQuery,
  SessionListResponse,
  ApiResponse,
} from '../types/conversation';

/**
 * 多轮对话服务类
 * 遵循前端开发规范的服务层设计，封装与后端的通信逻辑
 */
export class ConversationService {
  /**
   * 创建新会话
   */
  static async createSession(request: CreateConversationSessionRequest): Promise<ConversationSession> {
    try {
      const result = await invoke<ConversationSession>('create_conversation_session', { request });
      return result;
    } catch (error) {
      console.error('创建会话失败:', error);
      throw new Error(typeof error === 'string' ? error : '创建会话失败');
    }
  }

  /**
   * 获取会话信息
   */
  static async getSession(sessionId: string): Promise<ConversationSession | null> {
    try {
      const result = await invoke<ConversationSession | null>('get_conversation_session', { 
        sessionId 
      });
      return result;
    } catch (error) {
      console.error('获取会话失败:', error);
      throw new Error(typeof error === 'string' ? error : '获取会话失败');
    }
  }

  /**
   * 获取会话历史
   */
  static async getConversationHistory(query: ConversationHistoryQuery): Promise<ConversationHistory> {
    try {
      const result = await invoke<ConversationHistory>('get_conversation_history', { query });
      return result;
    } catch (error) {
      console.error('获取会话历史失败:', error);
      throw new Error(typeof error === 'string' ? error : '获取会话历史失败');
    }
  }

  /**
   * 获取会话列表
   */
  static async getSessions(query?: SessionListQuery): Promise<SessionListResponse> {
    try {
      const result = await invoke<SessionListResponse>('get_conversation_sessions', { 
        query: query || {} 
      });
      return result;
    } catch (error) {
      console.error('获取会话列表失败:', error);
      throw new Error(typeof error === 'string' ? error : '获取会话列表失败');
    }
  }

  /**
   * 删除会话
   */
  static async deleteSession(sessionId: string): Promise<void> {
    try {
      await invoke<void>('delete_conversation_session', { sessionId });
    } catch (error) {
      console.error('删除会话失败:', error);
      throw new Error(typeof error === 'string' ? error : '删除会话失败');
    }
  }

  /**
   * 添加消息到会话
   */
  static async addMessage(request: AddMessageRequest): Promise<ConversationMessage> {
    try {
      const result = await invoke<ConversationMessage>('add_conversation_message', { request });
      return result;
    } catch (error) {
      console.error('添加消息失败:', error);
      throw new Error(typeof error === 'string' ? error : '添加消息失败');
    }
  }

  /**
   * 多轮对话处理
   */
  static async processMultiTurnConversation(
    request: MultiTurnConversationRequest
  ): Promise<MultiTurnConversationResponse> {
    try {
      const result = await invoke<MultiTurnConversationResponse>(
        'process_multi_turn_conversation', 
        { request }
      );
      return result;
    } catch (error) {
      console.error('多轮对话处理失败:', error);
      throw new Error(typeof error === 'string' ? error : '多轮对话处理失败');
    }
  }

  /**
   * 获取会话统计信息
   */
  static async getConversationStats(): Promise<ConversationStats> {
    try {
      const result = await invoke<ConversationStats>('get_conversation_stats');
      return result;
    } catch (error) {
      console.error('获取会话统计失败:', error);
      throw new Error(typeof error === 'string' ? error : '获取会话统计失败');
    }
  }

  /**
   * 清理过期会话
   */
  static async cleanupExpiredSessions(maxInactiveDays: number): Promise<number> {
    try {
      const result = await invoke<number>('cleanup_expired_sessions', { maxInactiveDays });
      return result;
    } catch (error) {
      console.error('清理过期会话失败:', error);
      throw new Error(typeof error === 'string' ? error : '清理过期会话失败');
    }
  }

  /**
   * 更新会话标题
   */
  static async updateSessionTitle(sessionId: string, title: string): Promise<void> {
    try {
      await invoke<void>('update_session_title', { sessionId, title });
    } catch (error) {
      console.error('更新会话标题失败:', error);
      throw new Error(typeof error === 'string' ? error : '更新会话标题失败');
    }
  }

  /**
   * 生成会话摘要
   */
  static async generateSessionSummary(sessionId: string): Promise<string> {
    try {
      const result = await invoke<string>('generate_session_summary', { sessionId });
      return result;
    } catch (error) {
      console.error('生成会话摘要失败:', error);
      throw new Error(typeof error === 'string' ? error : '生成会话摘要失败');
    }
  }

  // 安全包装方法，返回ApiResponse格式

  /**
   * 安全创建会话
   */
  static async createSessionSafe(request: CreateConversationSessionRequest): Promise<ApiResponse<ConversationSession>> {
    try {
      const data = await this.createSession(request);
      return { data, success: true };
    } catch (error) {
      return { 
        error: error instanceof Error ? error.message : '创建会话失败', 
        success: false 
      };
    }
  }

  /**
   * 安全处理多轮对话
   */
  static async processMultiTurnConversationSafe(
    request: MultiTurnConversationRequest
  ): Promise<ApiResponse<MultiTurnConversationResponse>> {
    try {
      const data = await this.processMultiTurnConversation(request);
      return { data, success: true };
    } catch (error) {
      return { 
        error: error instanceof Error ? error.message : '多轮对话处理失败', 
        success: false 
      };
    }
  }

  /**
   * 安全获取会话历史
   */
  static async getConversationHistorySafe(
    query: ConversationHistoryQuery
  ): Promise<ApiResponse<ConversationHistory>> {
    try {
      const data = await this.getConversationHistory(query);
      return { data, success: true };
    } catch (error) {
      return { 
        error: error instanceof Error ? error.message : '获取会话历史失败', 
        success: false 
      };
    }
  }

  /**
   * 安全获取会话列表
   */
  static async getSessionsSafe(query?: SessionListQuery): Promise<ApiResponse<SessionListResponse>> {
    try {
      const data = await this.getSessions(query);
      return { data, success: true };
    } catch (error) {
      return { 
        error: error instanceof Error ? error.message : '获取会话列表失败', 
        success: false 
      };
    }
  }
}

/**
 * 多轮对话辅助工具类
 */
export class MultiTurnConversationHelper {
  /**
   * 创建简单的文本对话请求
   */
  static createTextConversationRequest(
    userMessage: string,
    sessionId?: string,
    options?: {
      includeHistory?: boolean;
      maxHistoryMessages?: number;
      systemPrompt?: string;
    }
  ): MultiTurnConversationRequest {
    return {
      session_id: sessionId,
      user_message: userMessage,
      include_history: options?.includeHistory ?? true,
      max_history_messages: options?.maxHistoryMessages ?? 1,
      system_prompt: options?.systemPrompt,
    };
  }

  /**
   * 验证会话ID格式
   */
  static isValidSessionId(sessionId: string): boolean {
    // 简单的UUID格式验证
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
    return uuidRegex.test(sessionId) || sessionId.startsWith('session_');
  }

  /**
   * 格式化响应时间
   */
  static formatResponseTime(responseTimeMs: number): string {
    if (responseTimeMs < 1000) {
      return `${responseTimeMs}ms`;
    } else if (responseTimeMs < 60000) {
      return `${(responseTimeMs / 1000).toFixed(1)}s`;
    } else {
      return `${(responseTimeMs / 60000).toFixed(1)}min`;
    }
  }

  /**
   * 检查响应是否成功
   */
  static isSuccessfulResponse(response: MultiTurnConversationResponse): boolean {
    return !!(response.assistant_message && response.message_id && response.session_id);
  }

  /**
   * 提取错误信息
   */
  static extractErrorMessage(error: unknown): string {
    if (typeof error === 'string') {
      return error;
    }
    if (error instanceof Error) {
      return error.message;
    }
    if (error && typeof error === 'object' && 'message' in error) {
      return String((error as any).message);
    }
    return '未知错误';
  }
}
