import { invoke } from '@tauri-apps/api/core';
import {
  AiClassification,
  CreateAiClassificationRequest,
  UpdateAiClassificationRequest,
  AiClassificationQuery,
  AiClassificationPreview,
  SortOrderUpdate,
  ApiResponse,
} from '../types/aiClassification';

/**
 * AI分类服务类
 * 遵循前端开发规范的服务层设计，封装与后端的通信逻辑
 */
export class AiClassificationService {
  /**
   * 创建AI分类
   */
  static async createClassification(request: CreateAiClassificationRequest): Promise<AiClassification> {
    try {
      const result = await invoke<AiClassification>('create_ai_classification', { request });
      return result;
    } catch (error) {
      console.error('创建AI分类失败:', error);
      throw new Error(typeof error === 'string' ? error : '创建AI分类失败');
    }
  }

  /**
   * 获取所有AI分类
   */
  static async getAllClassifications(query?: AiClassificationQuery): Promise<AiClassification[]> {
    try {
      const result = await invoke<AiClassification[]>('get_all_ai_classifications', { query });
      return result;
    } catch (error) {
      console.error('获取AI分类列表失败:', error);
      throw new Error(typeof error === 'string' ? error : '获取AI分类列表失败');
    }
  }

  /**
   * 根据ID获取AI分类
   */
  static async getClassificationById(id: string): Promise<AiClassification | null> {
    try {
      const result = await invoke<AiClassification | null>('get_ai_classification_by_id', { id });
      return result;
    } catch (error) {
      console.error('获取AI分类详情失败:', error);
      throw new Error(typeof error === 'string' ? error : '获取AI分类详情失败');
    }
  }

  /**
   * 更新AI分类
   */
  static async updateClassification(id: string, request: UpdateAiClassificationRequest): Promise<AiClassification | null> {
    try {
      const result = await invoke<AiClassification | null>('update_ai_classification', { id, request });
      return result;
    } catch (error) {
      console.error('更新AI分类失败:', error);
      throw new Error(typeof error === 'string' ? error : '更新AI分类失败');
    }
  }

  /**
   * 删除AI分类
   */
  static async deleteClassification(id: string): Promise<boolean> {
    try {
      const result = await invoke<boolean>('delete_ai_classification', { id });
      return result;
    } catch (error) {
      console.error('删除AI分类失败:', error);
      throw new Error(typeof error === 'string' ? error : '删除AI分类失败');
    }
  }

  /**
   * 获取AI分类总数
   */
  static async getClassificationCount(activeOnly?: boolean): Promise<number> {
    try {
      const result = await invoke<number>('get_ai_classification_count', { active_only: activeOnly });
      return result;
    } catch (error) {
      console.error('获取AI分类总数失败:', error);
      throw new Error(typeof error === 'string' ? error : '获取AI分类总数失败');
    }
  }

  /**
   * 生成AI分类预览
   */
  static async generatePreview(): Promise<AiClassificationPreview> {
    try {
      const result = await invoke<AiClassificationPreview>('generate_ai_classification_preview');
      return result;
    } catch (error) {
      console.error('生成AI分类预览失败:', error);
      throw new Error(typeof error === 'string' ? error : '生成AI分类预览失败');
    }
  }

  /**
   * 批量更新分类排序
   */
  static async updateSortOrders(updates: SortOrderUpdate[]): Promise<AiClassification[]> {
    try {
      // 转换为后端期望的格式 [id, sort_order]
      const updateTuples: [string, number][] = updates.map(update => [update.id, update.sort_order]);
      const result = await invoke<AiClassification[]>('update_ai_classification_sort_orders', { updates: updateTuples });
      return result;
    } catch (error) {
      console.error('批量更新排序失败:', error);
      throw new Error(typeof error === 'string' ? error : '批量更新排序失败');
    }
  }

  /**
   * 切换分类激活状态
   */
  static async toggleClassificationStatus(id: string): Promise<AiClassification | null> {
    try {
      const result = await invoke<AiClassification | null>('toggle_ai_classification_status', { id });
      return result;
    } catch (error) {
      console.error('切换分类状态失败:', error);
      throw new Error(typeof error === 'string' ? error : '切换分类状态失败');
    }
  }

  /**
   * 验证分类名称是否可用
   */
  static async validateClassificationName(name: string, excludeId?: string): Promise<boolean> {
    try {
      const result = await invoke<boolean>('validate_ai_classification_name', { 
        name, 
        exclude_id: excludeId 
      });
      return result;
    } catch (error) {
      console.error('验证分类名称失败:', error);
      throw new Error(typeof error === 'string' ? error : '验证分类名称失败');
    }
  }

  /**
   * 获取激活的分类列表（用于预览）
   */
  static async getActiveClassifications(): Promise<AiClassification[]> {
    return this.getAllClassifications({
      active_only: true,
      sort_by: 'sort_order',
      sort_order: 'ASC',
    });
  }

  /**
   * 获取所有分类（包括非激活的）
   */
  static async getAllClassificationsIncludingInactive(): Promise<AiClassification[]> {
    return this.getAllClassifications({
      active_only: false,
      sort_by: 'sort_order',
      sort_order: 'ASC',
    });
  }

  /**
   * 创建分类并返回包装的响应
   */
  static async createClassificationSafe(request: CreateAiClassificationRequest): Promise<ApiResponse<AiClassification>> {
    try {
      const data = await this.createClassification(request);
      return { data, success: true };
    } catch (error) {
      return { 
        error: error instanceof Error ? error.message : '创建分类失败', 
        success: false 
      };
    }
  }

  /**
   * 更新分类并返回包装的响应
   */
  static async updateClassificationSafe(id: string, request: UpdateAiClassificationRequest): Promise<ApiResponse<AiClassification | null>> {
    try {
      const data = await this.updateClassification(id, request);
      return { data, success: true };
    } catch (error) {
      return { 
        error: error instanceof Error ? error.message : '更新分类失败', 
        success: false 
      };
    }
  }

  /**
   * 删除分类并返回包装的响应
   */
  static async deleteClassificationSafe(id: string): Promise<ApiResponse<boolean>> {
    try {
      const data = await this.deleteClassification(id);
      return { data, success: true };
    } catch (error) {
      return { 
        error: error instanceof Error ? error.message : '删除分类失败', 
        success: false 
      };
    }
  }

  /**
   * 获取分类列表并返回包装的响应
   */
  static async getAllClassificationsSafe(query?: AiClassificationQuery): Promise<ApiResponse<AiClassification[]>> {
    try {
      const data = await this.getAllClassifications(query);
      return { data, success: true };
    } catch (error) {
      return { 
        error: error instanceof Error ? error.message : '获取分类列表失败', 
        success: false 
      };
    }
  }

  /**
   * 生成预览并返回包装的响应
   */
  static async generatePreviewSafe(): Promise<ApiResponse<AiClassificationPreview>> {
    try {
      const data = await this.generatePreview();
      return { data, success: true };
    } catch (error) {
      return { 
        error: error instanceof Error ? error.message : '生成预览失败', 
        success: false 
      };
    }
  }

  /**
   * 重新排序分类
   * 根据新的顺序数组重新设置所有分类的排序顺序
   */
  static async reorderClassifications(orderedIds: string[]): Promise<AiClassification[]> {
    const updates: SortOrderUpdate[] = orderedIds.map((id, index) => ({
      id,
      sort_order: index + 1,
    }));
    
    return this.updateSortOrders(updates);
  }

  /**
   * 复制分类
   * 创建一个现有分类的副本
   */
  static async duplicateClassification(id: string): Promise<AiClassification> {
    const original = await this.getClassificationById(id);
    if (!original) {
      throw new Error('要复制的分类不存在');
    }

    const request: CreateAiClassificationRequest = {
      name: `${original.name} (副本)`,
      prompt_text: original.prompt_text,
      description: original.description,
      sort_order: original.sort_order + 1,
    };

    return this.createClassification(request);
  }

  /**
   * 批量删除分类
   */
  static async deleteMultipleClassifications(ids: string[]): Promise<{ success: string[]; failed: string[] }> {
    const success: string[] = [];
    const failed: string[] = [];

    for (const id of ids) {
      try {
        const result = await this.deleteClassification(id);
        if (result) {
          success.push(id);
        } else {
          failed.push(id);
        }
      } catch (error) {
        failed.push(id);
      }
    }

    return { success, failed };
  }

  /**
   * 批量切换分类状态
   */
  static async toggleMultipleClassificationStatus(ids: string[]): Promise<AiClassification[]> {
    const results: AiClassification[] = [];

    for (const id of ids) {
      try {
        const result = await this.toggleClassificationStatus(id);
        if (result) {
          results.push(result);
        }
      } catch (error) {
        console.error(`切换分类 ${id} 状态失败:`, error);
      }
    }

    return results;
  }
}
