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

interface VideoMetadata {
  width: number;
  height: number;
  duration: number;
  fps: number;
}

interface VideoValidationResult {
  valid: boolean;
  duration: number;
  width: number;
  height: number;
  error?: string;
}

/**
 * 验证本地视频文件（格式、时长、分辨率）
 *
 * 通过 Rust 层 ffprobe 读取元数据，跨平台可靠，
 * 不依赖浏览器视频解码器。
 */
export async function validateLocalVideo(
  filePath: string,
  options?: { minDuration?: number; maxDuration?: number; requireResolution?: boolean }
): Promise<VideoValidationResult> {
  const { minDuration = 5, maxDuration = 20, requireResolution = true } = options || {};

  try {
    const resp = await invoke<{
      code: number;
      message: string;
      data?: VideoMetadata;
    }>('get_video_metadata_cmd', { request: { path: filePath } });

    if (resp.code !== 200 || !resp.data) {
      return {
        valid: false,
        duration: 0,
        width: 0,
        height: 0,
        error: resp.message || '读取视频元数据失败',
      };
    }

    const { width, height, duration } = resp.data;

    if (duration < minDuration || duration > maxDuration) {
      return {
        valid: false,
        duration,
        width,
        height,
        error: `视频时长 ${duration.toFixed(1)} 秒，要求 ${minDuration}-${maxDuration} 秒`,
      };
    }

    if (requireResolution && (width !== 1080 || height !== 1920)) {
      return {
        valid: false,
        duration,
        width,
        height,
        error: `视频分辨率 ${width}x${height}，要求 1080x1920`,
      };
    }

    return { valid: true, duration, width, height };
  } catch (e) {
    return {
      valid: false,
      duration: 0,
      width: 0,
      height: 0,
      error: `读取文件失败: ${e instanceof Error ? e.message : String(e)}`,
    };
  }
}
