/**
 * 多轮对话相关类型定义
 * 遵循 Tauri 开发规范的类型安全设计
 */

/**
 * 消息角色类型
 */
export type MessageRole = 'user' | 'assistant' | 'system';

/**
 * 消息内容类型
 */
export interface MessageContent {
  type: 'text' | 'file' | 'inline_data';
  text?: string;
  file_uri?: string;
  mime_type?: string;
  data?: string;
  description?: string;
}

/**
 * 会话消息
 */
export interface ConversationMessage {
  id: string;
  session_id: string;
  role: MessageRole;
  content: MessageContent[];
  timestamp: string;
  metadata?: Record<string, any>;
}

/**
 * 会话会话
 */
export interface ConversationSession {
  id: string;
  title?: string;
  created_at: string;
  updated_at: string;
  is_active: boolean;
  metadata?: Record<string, any>;
}

/**
 * 创建会话请求
 */
export interface CreateConversationSessionRequest {
  title?: string;
  metadata?: Record<string, any>;
}

/**
 * 添加消息请求
 */
export interface AddMessageRequest {
  session_id: string;
  role: MessageRole;
  content: MessageContent[];
  metadata?: Record<string, any>;
}

/**
 * 会话历史查询参数
 */
export interface ConversationHistoryQuery {
  session_id: string;
  limit?: number;
  offset?: number;
  include_system_messages?: boolean;
}

/**
 * 会话历史响应
 */
export interface ConversationHistory {
  session: ConversationSession;
  messages: ConversationMessage[];
  total_count: number;
}

/**
 * 多轮对话请求
 */
export interface MultiTurnConversationRequest {
  session_id?: string;
  user_message: string;
  include_history?: boolean;
  max_history_messages?: number;
  system_prompt?: string;
  config?: Record<string, any>;
}

/**
 * 多轮对话响应
 */
export interface MultiTurnConversationResponse {
  session_id: string;
  assistant_message: string;
  message_id: string;
  response_time_ms: number;
  model_used: string;
  metadata?: Record<string, any>;
}

/**
 * 会话统计信息
 */
export interface ConversationStats {
  total_sessions: number;
  active_sessions: number;
  total_messages: number;
  average_messages_per_session: number;
}

/**
 * 会话清理配置
 */
export interface ConversationCleanupConfig {
  max_inactive_days: number;
  max_messages_per_session: number;
  auto_cleanup_enabled: boolean;
}

/**
 * 前端聊天消息（用于UI显示）
 */
export interface ChatMessage {
  id: string;
  type: MessageRole;
  content: string;
  timestamp: Date;
  status: 'sending' | 'sent' | 'error';
  metadata?: Record<string, any>;
}

/**
 * 聊天会话状态
 */
export interface ChatSessionState {
  session_id?: string;
  messages: ChatMessage[];
  isLoading: boolean;
  error?: string;
  hasHistory: boolean;
}

/**
 * 多轮对话配置选项
 */
export interface MultiTurnConversationOptions {
  sessionId?: string;
  includeHistory?: boolean;
  maxHistoryMessages?: number;
  systemPrompt?: string;
  temperature?: number;
  maxTokens?: number;
  timeout?: number;
}

/**
 * API响应包装器
 */
export interface ApiResponse<T> {
  data?: T;
  success: boolean;
  error?: string;
}

/**
 * 会话列表查询参数
 */
export interface SessionListQuery {
  limit?: number;
  offset?: number;
  search?: string;
  sort_by?: 'created_at' | 'updated_at' | 'title';
  sort_order?: 'ASC' | 'DESC';
}

/**
 * 会话列表响应
 */
export interface SessionListResponse {
  sessions: ConversationSession[];
  total_count: number;
  has_more: boolean;
}

/**
 * 消息发送状态
 */
export type MessageSendStatus = 'idle' | 'sending' | 'success' | 'error';

/**
 * 聊天界面配置
 */
export interface ChatInterfaceConfig {
  maxMessages: number;
  autoSave: boolean;
  showTimestamps: boolean;
  enableMarkdown: boolean;
  enableFileUpload: boolean;
  maxFileSize: number;
  allowedFileTypes: string[];
}

/**
 * 默认聊天界面配置
 */
export const DEFAULT_CHAT_CONFIG: ChatInterfaceConfig = {
  maxMessages: 100,
  autoSave: true,
  showTimestamps: true,
  enableMarkdown: true,
  enableFileUpload: false,
  maxFileSize: 10 * 1024 * 1024, // 10MB
  allowedFileTypes: ['image/jpeg', 'image/png', 'image/gif', 'text/plain'],
};

/**
 * 消息内容工具函数
 */
export const MessageContentUtils = {
  /**
   * 创建文本消息内容
   */
  createTextContent: (text: string): MessageContent => ({
    type: 'text',
    text,
  }),

  /**
   * 创建文件消息内容
   */
  createFileContent: (fileUri: string, mimeType: string, description?: string): MessageContent => ({
    type: 'file',
    file_uri: fileUri,
    mime_type: mimeType,
    description,
  }),

  /**
   * 创建内联数据消息内容
   */
  createInlineDataContent: (data: string, mimeType: string, description?: string): MessageContent => ({
    type: 'inline_data',
    data,
    mime_type: mimeType,
    description,
  }),

  /**
   * 提取消息的文本内容
   */
  extractTextContent: (content: MessageContent[]): string => {
    return content
      .filter(item => item.type === 'text')
      .map(item => item.text || '')
      .join(' ');
  },

  /**
   * 检查消息是否包含文件
   */
  hasFileContent: (content: MessageContent[]): boolean => {
    return content.some(item => item.type === 'file' || item.type === 'inline_data');
  },
};

/**
 * 会话工具函数
 */
export const ConversationUtils = {
  /**
   * 生成消息ID
   */
  generateMessageId: (): string => {
    return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
  },

  /**
   * 生成会话ID
   */
  generateSessionId: (): string => {
    return `session_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
  },

  /**
   * 格式化时间戳
   */
  formatTimestamp: (timestamp: string | Date): string => {
    const date = typeof timestamp === 'string' ? new Date(timestamp) : timestamp;
    return date.toLocaleString();
  },

  /**
   * 计算会话持续时间
   */
  calculateSessionDuration: (session: ConversationSession): string => {
    const start = new Date(session.created_at);
    const end = new Date(session.updated_at);
    const duration = end.getTime() - start.getTime();
    
    const minutes = Math.floor(duration / 60000);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 0) return `${days}天`;
    if (hours > 0) return `${hours}小时`;
    if (minutes > 0) return `${minutes}分钟`;
    return '刚刚';
  },
};
