import { invoke } from '@tauri-apps/api/core';

/**
 * VEO3 场景写作消息接口
 */
export interface Veo3SceneWriterMessage {
  content: string;
  attachments?: string[];
}

/**
 * VEO3 场景写作响应接口
 */
export interface Veo3SceneWriterResponse {
  success: boolean;
  content: string;
  error?: string;
  conversation_history?: string[];
}

/**
 * VEO3 场景写作会话状态接口
 */
export interface Veo3SceneWriterSession {
  session_id: string;
  conversation_history: string[];
  created_at: string;
  last_updated: string;
}

/**
 * 创建场景文件请求接口
 */
export interface CreateSceneFileRequest {
  session_id: string;
  file_path: string;
  file_name?: string;
}

/**
 * 创建场景文件响应接口
 */
export interface CreateSceneFileResponse {
  success: boolean;
  file_path?: string;
  extracted_json?: any;
  error?: string;
}

/**
 * VEO3 场景写作服务类
 * 封装与 Rust 后端 veo3-scene-writer crate 的通信逻辑
 */
export class Veo3SceneWriterService {
  private static instance: Veo3SceneWriterService;
  private sessionId: string;

  private constructor() {
    this.sessionId = `veo3-scene-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
  }

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

  /**
   * 发送文本消息到 VEO3 场景写作工具
   */
  public async sendMessage(message: string): Promise<Veo3SceneWriterResponse> {
    try {
      const response = await invoke<Veo3SceneWriterResponse>('veo3_scene_writer_send_message', {
        sessionId: this.sessionId,
        message: message
      });

      return response;
    } catch (error) {
      console.error('VEO3 场景写作消息发送失败:', error);
      return {
        success: false,
        content: '',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 发送带附件的消息到 VEO3 场景写作工具
   */
  public async sendMessageWithAttachments(
    message: string, 
    attachmentPaths: string[]
  ): Promise<Veo3SceneWriterResponse> {
    try {
      const response = await invoke<Veo3SceneWriterResponse>('veo3_scene_writer_send_message_with_attachments', {
        sessionId: this.sessionId,
        message: message,
        attachmentPaths: attachmentPaths
      });

      return response;
    } catch (error) {
      console.error('VEO3 场景写作带附件消息发送失败:', error);
      return {
        success: false,
        content: '',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 获取会话历史记录
   */
  public async getConversationHistory(): Promise<string[]> {
    try {
      const history = await invoke<string[]>('veo3_scene_writer_get_conversation_history', {
        sessionId: this.sessionId
      });

      return history;
    } catch (error) {
      console.error('获取 VEO3 场景写作会话历史失败:', error);
      return [];
    }
  }

  /**
   * 清除会话历史记录
   */
  public async clearConversation(): Promise<boolean> {
    try {
      await invoke('veo3_scene_writer_clear_conversation', {
        sessionId: this.sessionId
      });

      return true;
    } catch (error) {
      console.error('清除 VEO3 场景写作会话历史失败:', error);
      return false;
    }
  }

  /**
   * 获取当前会话ID
   */
  public getSessionId(): string {
    return this.sessionId;
  }

  /**
   * 重置会话（生成新的会话ID）
   */
  public resetSession(): void {
    this.sessionId = `veo3-scene-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
  }

  /**
   * 检查服务是否可用
   */
  public async checkServiceAvailability(): Promise<boolean> {
    try {
      await invoke('veo3_scene_writer_check_availability');
      return true;
    } catch (error) {
      console.error('VEO3 场景写作服务不可用:', error);
      return false;
    }
  }

  /**
   * 创建场景文件 - 从最近一次对话中提取JSON并保存
   */
  public async createSceneFile(
    filePath: string,
    fileName?: string
  ): Promise<CreateSceneFileResponse> {
    try {
      const response = await invoke<CreateSceneFileResponse>('veo3_scene_writer_create_scene_file', {
        request: {
          session_id: this.sessionId,
          file_path: filePath,
          file_name: fileName
        }
      });

      return response;
    } catch (error) {
      console.error('创建场景文件失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }
}

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

/**
 * 便捷函数：发送消息
 */
export const sendVeo3SceneWriterMessage = (message: string): Promise<Veo3SceneWriterResponse> => {
  return veo3SceneWriterService.sendMessage(message);
};

/**
 * 便捷函数：发送带附件的消息
 */
export const sendVeo3SceneWriterMessageWithAttachments = (
  message: string, 
  attachmentPaths: string[]
): Promise<Veo3SceneWriterResponse> => {
  return veo3SceneWriterService.sendMessageWithAttachments(message, attachmentPaths);
};

/**
 * 便捷函数：获取会话历史
 */
export const getVeo3SceneWriterConversationHistory = (): Promise<string[]> => {
  return veo3SceneWriterService.getConversationHistory();
};

/**
 * 便捷函数：清除会话
 */
export const clearVeo3SceneWriterConversation = (): Promise<boolean> => {
  return veo3SceneWriterService.clearConversation();
};

/**
 * 便捷函数：创建场景文件
 */
export const createVeo3SceneFile = (
  filePath: string,
  fileName?: string
): Promise<CreateSceneFileResponse> => {
  return veo3SceneWriterService.createSceneFile(filePath, fileName);
};
