// 模板管理相关类型定义

export interface Template {
  id: string;
  name: string;
  description?: string;
  project_id?: string;
  canvas_config: CanvasConfig;
  duration: number; // 模板总时长（微秒）
  fps: number;
  materials: TemplateMaterial[];
  tracks: Track[];
  import_status: ImportStatus;
  source_file_path?: string;
  created_at: string;
  updated_at: string;
  is_active: boolean;
}

export interface CanvasConfig {
  width: number;
  height: number;
  ratio: string; // "original", "16:9", "9:16", etc.
}

export interface TemplateMaterial {
  id: string;
  template_id: string;
  original_id: string; // 原始剪映素材ID
  name: string;
  material_type: TemplateMaterialType;
  original_path: string; // 原始本地路径
  remote_url?: string; // 上传后的远程URL
  file_size?: number;
  duration?: number; // 素材时长（微秒）
  width?: number;
  height?: number;
  upload_status: UploadStatus;
  metadata?: string; // JSON格式的额外元数据
  created_at: string;
  updated_at: string;
}

export interface Track {
  id: string;
  template_id: string;
  name: string;
  track_type: TrackType;
  track_index: number; // 轨道索引
  segments: TrackSegment[];
  created_at: string;
  updated_at: string;
}

/**
 * 片段匹配规则类型
 * 匹配Rust enum的序列化格式
 */
export type SegmentMatchingRule =
  | "FixedMaterial"
  | { AiClassification: { category_id: string; category_name: string } }
  | "RandomMatch";

/**
 * 片段匹配规则辅助函数
 */
export const SegmentMatchingRuleHelper = {
  /**
   * 创建固定素材规则
   */
  createFixedMaterial(): SegmentMatchingRule {
    return "FixedMaterial";
  },

  /**
   * 创建AI分类规则
   */
  createAiClassification(categoryId: string, categoryName: string): SegmentMatchingRule {
    return { AiClassification: { category_id: categoryId, category_name: categoryName } };
  },

  /**
   * 创建随机匹配规则
   */
  createRandomMatch(): SegmentMatchingRule {
    return "RandomMatch";
  },

  /**
   * 获取规则的显示名称
   */
  getDisplayName(rule: SegmentMatchingRule): string {
    if (rule === "FixedMaterial") {
      return '固定素材';
    } else if (typeof rule === 'object' && 'AiClassification' in rule) {
      return `AI分类: ${rule.AiClassification.category_name}`;
    } else if (rule === "RandomMatch") {
      return '随机匹配';
    }
    return '未知规则';
  },

  /**
   * 检查是否为固定素材
   */
  isFixedMaterial(rule: SegmentMatchingRule): boolean {
    return rule === "FixedMaterial";
  },

  /**
   * 检查是否为AI分类
   */
  isAiClassification(rule: SegmentMatchingRule): boolean {
    return typeof rule === 'object' && 'AiClassification' in rule;
  },

  /**
   * 检查是否为随机匹配
   */
  isRandomMatch(rule: SegmentMatchingRule): boolean {
    return rule === "RandomMatch";
  },

  /**
   * 获取AI分类信息
   */
  getAiClassificationInfo(rule: SegmentMatchingRule): { category_id: string; category_name: string } | null {
    if (typeof rule === 'object' && 'AiClassification' in rule) {
      return rule.AiClassification;
    }
    return null;
  }
};

export interface TrackSegment {
  id: string;
  track_id: string;
  template_material_id?: string; // 关联的模板素材ID
  name: string;
  start_time: number; // 开始时间（微秒）
  end_time: number;   // 结束时间（微秒）
  duration: number;   // 片段时长（微秒）
  segment_index: number; // 片段在轨道中的索引
  properties?: string; // JSON格式的片段属性
  matching_rule: SegmentMatchingRule; // 片段匹配规则
  created_at: string;
  updated_at: string;
}

export enum TemplateMaterialType {
  Video = "Video",
  Audio = "Audio",
  Image = "Image",
  Text = "Text",
  Effect = "Effect",
  Sticker = "Sticker",
  Canvas = "Canvas",
  Other = "Other"
}

export enum TrackType {
  Video = "Video",
  Audio = "Audio",
  Text = "Text",
  Sticker = "Sticker",
  Effect = "Effect",
  Other = "Other"
}

export enum ImportStatus {
  Pending = "Pending",     // 等待导入
  Parsing = "Parsing",     // 解析中
  Uploading = "Uploading", // 上传中
  Processing = "Processing", // 处理中
  Completed = "Completed", // 完成
  Failed = "Failed"        // 失败
}

export enum UploadStatus {
  Pending = "Pending",     // 等待上传
  Uploading = "Uploading", // 上传中
  Completed = "Completed", // 上传完成
  Failed = "Failed",       // 上传失败
  Skipped = "Skipped"      // 跳过（文件不存在等）
}

export interface CreateTemplateRequest {
  name: string;
  description?: string;
  project_id?: string;
  source_file_path: string; // draft_content.json文件路径
}

export interface ImportTemplateRequest {
  file_path: string; // draft_content.json文件路径
  template_name?: string; // 自定义模板名称
  project_id?: string;
  auto_upload: boolean; // 是否自动上传素材到云端
}

export interface BatchImportRequest {
  folder_path: string; // 包含多个draft_content.json的文件夹路径
  project_id?: string;
  auto_upload: boolean;
  max_concurrent?: number; // 最大并发数
}

export interface ImportProgress {
  template_id: string;
  template_name: string;
  status: ImportStatus;
  total_materials: number;
  uploaded_materials: number;
  failed_materials: number;
  current_operation: string;
  error_message?: string;
  progress_percentage: number; // 0.0 - 100.0
}

// 剪映草稿内容结构（用于解析）
export interface DraftContent {
  id: string;
  canvas_config: {
    width: number;
    height: number;
    ratio: string;
  };
  duration: number;
  fps: number;
  materials: {
    videos?: DraftVideo[];
    audios?: DraftAudio[];
    images?: DraftImage[];
    texts?: DraftText[];
    stickers?: DraftSticker[];
    effects?: DraftEffect[];
    canvases?: DraftCanvas[];
  };
  tracks?: DraftTrack[];
}

export interface DraftVideo {
  id: string;
  material_name: string;
  path: string;
  duration: number;
  width: number;
  height: number;
  has_audio: boolean;
  type: string;
}

export interface DraftAudio {
  id: string;
  name: string;
  path: string;
  duration: number;
  type: string;
}

export interface DraftImage {
  id: string;
  material_name: string;
  path: string;
  width: number;
  height: number;
  type: string;
}

export interface DraftText {
  id: string;
  content: string;
  font_family?: string;
  font_size?: number;
  color?: string;
}

export interface DraftSticker {
  id: string;
  name: string;
  path?: string;
  type: string;
}

export interface DraftEffect {
  id: string;
  name: string;
  path?: string;
  type: string;
}

export interface DraftCanvas {
  id: string;
  color?: string;
  image?: string;
  type: string;
}

export interface DraftTrack {
  id: string;
  type: string;
  segments: DraftSegment[];
}

export interface DraftSegment {
  id: string;
  material_id: string;
  start: number;
  duration: number;
  target_timerange: {
    start: number;
    duration: number;
  };
}

// API响应类型
export interface TemplateListResponse {
  templates: Template[];
  total: number;
  page: number;
  page_size: number;
}

export interface TemplateDetailResponse {
  template: Template;
}

export interface ImportProgressResponse {
  progress: ImportProgress;
}

// 上传相关类型
export interface UploadPresignRequest {
  key: string;
  content_type: string;
}

export interface UploadPresignResponse {
  url: string;
  urn: string;
  expired_at: string;
}

// 错误类型
export interface TemplateError {
  code: string;
  message: string;
  details?: Record<string, any>;
}
