/**
 * 本地文件存储 API
 * =================
 * 
 * 通过 Tauri 与 Rust 后端通信，操作本地文件系统
 * 存储位置: {app_local_data_dir}/ (应用私有数据目录)
 */

import { invoke } from '@tauri-apps/api/core';
import { ApiResponse, AlignmentResult } from '../types';
import type { ProjectMeta } from '../../types/project';

// 检查是否在 Tauri 环境中（Tauri 2.x 兼容）
interface TauriWindow extends Window {
  __TAURI_INTERNALS__?: unknown;
  __TAURI__?: unknown;
}

const isTauri = (): boolean => {
  if (typeof window === 'undefined') {return false;}
  // Tauri 2.x 使用 __TAURI_INTERNALS__ 或 __TAURI__
  return !!(window as TauriWindow).__TAURI_INTERNALS__ || !!(window as TauriWindow).__TAURI__;
};

// 安全调用 Tauri 命令
const safeInvoke = async <T>(cmd: string, args?: Record<string, unknown>): Promise<T | null> => {
  const tauriAvailable = isTauri();

  if (!tauriAvailable) {
    return null;
  }

  // Tauri 环境：真实调用
  try {
    const result = await invoke<T>(cmd, args);
    return result;
  } catch (e) {
    console.error(`[localStorage] invoke ${cmd} failed:`, e);
    throw e;
  }
};

/**
 * 本地重新导出 ProjectMeta，保持向后兼容
 * 新的代码建议直接从 '../../types/project' 导入
 */
export type { ProjectMeta } from '../../types/project';

/**
 * 分镜数据接口
 */
interface ProjectSegment {
  id: number;
  type: 'segment' | 'empty_shot';
  scene?: string;
  voiceover?: string;
  duration: string;
  videoPath?: string;  // 本地视频文件路径
  videoUrl?: string;   // 七牛云视频 URL（用于字幕生成等后续处理）
  elementId?: number;  // 分镜使用的形象ID
  voiceId?: string;    // 空镜使用的音色ID
  alignmentResult?: AlignmentResult; // 字幕打轴结果
  burnedVideoPath?: string; // 压制字幕后的视频路径
  burnedAt?: number;        // 压制字幕的时间戳
  audioStartTime?: number;  // 在完整配音音频中的开始时间（毫秒）
  audioEndTime?: number;    // 在完整配音音频中的结束时间（毫秒）
  actualDuration?: number;  // 实际时长（秒，基于字幕打轴）
  clipAudioPath?: string;   // 截取后的音频片段本地路径
  clipAudioUrl?: string;    // 截取后的音频片段七牛云 URL
  lipSyncTaskId?: string;      // Vidu 视频生成任务 ID
  lipSyncState?: string;       // Vidu 视频生成任务状态
  lipSyncVideoPath?: string;   // 视频生成本地路径
  lipSyncVideoUrl?: string;    // 视频生成 URL
  lipSyncStartTime?: number;   // 从人物素材截取的起始时间（秒）
  clipVideoPath?: string;      // 标准化后的片段视频本地路径（供 concat 使用）
  voiceVolume?: number;
  bgmVolume?: number;
  audioPath?: string;
  audioUrl?: string;
  emptyShotMaterial?: { url: string; duration: number };
}

/**
 * 本地项目存储 API
 */
export const localProjectApi = {
  /**
   * 保存项目元数据
   */
  saveMeta: async (projectId: string, meta: ProjectMeta): Promise<boolean> => {
    // 按指定字段顺序序列化
    const orderedMeta = {
      id: meta.id,
      title: meta.title,
      topic: meta.topic,
      categoryCode: meta.categoryCode,
      filename: meta.filename,
      status: meta.status,
      currentStep: meta.currentStep,
      createdAt: meta.createdAt,
      updatedAt: meta.updatedAt,
      coverPath: meta.coverPath,
      finalVideoPath: meta.finalVideoPath,
      finalVideoDuration: meta.finalVideoDuration,
      exportedAt: meta.exportedAt,
      selectedVoiceId: meta.selectedVoiceId,
      composedVideoUrl: meta.composedVideoUrl,
      composedVideoPath: meta.composedVideoPath,
      lipSyncTaskId: meta.lipSyncTaskId,
      lipSyncState: meta.lipSyncState,
      lipSyncedVideoPath: meta.lipSyncedVideoPath,
      lipSyncedVideoUrl: meta.lipSyncedVideoUrl,
      dubbingAudioUrl: meta.dubbingAudioUrl,
      dubbingAudioPath: meta.dubbingAudioPath,
      dubbingAudioDuration: meta.dubbingAudioDuration,
      voiceSpeed: meta.voiceSpeed,
      voiceVolume: meta.voiceVolume,
      voicePitch: meta.voicePitch,
      avatarMaterialPath: meta.avatarMaterialPath,
      avatarMaterialName: meta.avatarMaterialName,
      avatarMaterialDuration: meta.avatarMaterialDuration,
      subtitleAlignment: meta.subtitleAlignment,
      burnedVideoPath: meta.burnedVideoPath,
      mainTitle: meta.mainTitle,
      subTitle: meta.subTitle,
      mainTitlePreset: meta.mainTitlePreset,
      subTitlePreset: meta.subTitlePreset,
      captionPreset: meta.captionPreset,
      coverConfig: meta.coverConfig,
      bgmMusicId: meta.bgmMusicId,
      bgmMusicTitle: meta.bgmMusicTitle,
      bgmMusicPath: meta.bgmMusicPath,
      bgmVolume: meta.bgmVolume,
      version: meta.version,
      userUploadedMaterials: meta.userUploadedMaterials,
      stepDirtyFlags: meta.stepDirtyFlags,
    };
    const jsonContent = JSON.stringify(orderedMeta, null, 2);
    const res = await safeInvoke<ApiResponse<boolean>>('save_project_meta_raw', { 
      projectId: projectId, 
      jsonContent 
    });
    return res?.code === 200;
  },

  /**
   * 加载项目元数据
   */
  loadMeta: async (projectId: string): Promise<ProjectMeta | null> => {
    const res = await safeInvoke<ApiResponse<ProjectMeta>>('load_project_meta', { projectId: projectId });
    if (res?.code === 200 && res.data) {
      return res.data;
    }
    return null;
  },

  /**
   * 保存分镜数据
   */
  saveSegments: async (projectId: string, segments: ProjectSegment[]): Promise<boolean> => {
    // 按指定字段顺序序列化每个分镜
    const orderedSegments = segments.map(s => ({
      id: s.id,
      type: s.type,
      scene: s.scene,
      voiceover: s.voiceover,
      duration: s.duration,
      videoPath: s.videoPath,
      videoUrl: s.videoUrl,
      elementId: s.elementId,
      voiceId: s.voiceId,
      alignmentResult: s.alignmentResult,
      burnedVideoPath: s.burnedVideoPath,
      burnedAt: s.burnedAt,
      audioStartTime: s.audioStartTime,
      audioEndTime: s.audioEndTime,
      actualDuration: s.actualDuration,
      clipAudioPath: s.clipAudioPath,
      clipAudioUrl: s.clipAudioUrl,
      lipSyncTaskId: s.lipSyncTaskId,
      lipSyncState: s.lipSyncState,
      lipSyncVideoPath: s.lipSyncVideoPath,
      lipSyncVideoUrl: s.lipSyncVideoUrl,
      lipSyncStartTime: s.lipSyncStartTime,
      clipVideoPath: s.clipVideoPath,
      voiceVolume: s.voiceVolume,
      bgmVolume: s.bgmVolume,
      audioPath: s.audioPath,
      audioUrl: s.audioUrl,
      emptyShotMaterial: s.emptyShotMaterial,
    }));
    const jsonContent = JSON.stringify(orderedSegments, null, 2);
    const res = await safeInvoke<ApiResponse<boolean>>('save_project_segments_raw', { 
      projectId: projectId, 
      jsonContent 
    });
    return res?.code === 200;
  },

  /**
   * 加载分镜数据
   */
  loadSegments: async (projectId: string): Promise<ProjectSegment[]> => {
    const res = await safeInvoke<ApiResponse<ProjectSegment[]>>('load_project_segments', { projectId: projectId });
    if (res?.code === 200 && res.data) {
      return res.data;
    }
    return [];
  },

  /**
   * 列出所有本地项目
   */
  listProjects: async (): Promise<ProjectMeta[]> => {
    const res = await safeInvoke<ApiResponse<ProjectMeta[]>>('list_local_projects');
    if (res?.code === 200 && res.data) {
      return res.data;
    }
    return [];
  },

  /**
   * 删除本地项目
   */
  deleteProject: async (projectId: string): Promise<boolean> => {
    const res = await safeInvoke<ApiResponse<boolean>>('delete_local_project', { projectId: projectId });
    return res?.code === 200;
  },

  /**
   * 保存完整项目（元数据 + 分镜）
   */
  saveProject: async (
    projectId: string, 
    meta: ProjectMeta, 
    segments: ProjectSegment[]
  ): Promise<boolean> => {
    const [metaRes, segmentsRes] = await Promise.all([
      localProjectApi.saveMeta(projectId, meta),
      localProjectApi.saveSegments(projectId, segments)
    ]);
    return metaRes && segmentsRes;
  },

  /**
   * 加载完整项目
   */
  loadProject: async (projectId: string): Promise<{ meta: ProjectMeta | null; segments: ProjectSegment[] }> => {
    const [meta, segments] = await Promise.all([
      localProjectApi.loadMeta(projectId),
      localProjectApi.loadSegments(projectId)
    ]);
    return { meta, segments };
  },
};

/**
 * 生成项目 ID
 */
export function generateProjectId(): string {
  return `proj_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

/**
 * 获取当前项目 ID（从 store 或生成新的）
 */
export function getCurrentProjectId(): string {
  // 可以从 URL 参数、store 或 localStorage 获取
  // 这里简化处理，实际使用时需要更复杂的逻辑
  const stored = localStorage.getItem('current-project-id');
  if (stored) {
    return stored;
  }
  const newId = generateProjectId();
  localStorage.setItem('current-project-id', newId);
  return newId;
}

/**
 * 设置当前项目 ID
 */
export function setCurrentProjectId(projectId: string): void {
  localStorage.setItem('current-project-id', projectId);
}

