/**
 * 构建前自动：若 promotion/social 存在 .mov 且比对应 .mp4 新（或尚无 .mp4），则用 ffmpeg 转码。
 * - 无 .mov：直接通过
 * - 有 .mov 需更新但无 ffmpeg：失败（避免打出缺 mp4 的包）；可设 SKIP_PROMOTION_TRANSCODE=1 跳过
 */
import { existsSync, statSync } from 'fs'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { spawnSync } from 'child_process'

const __dirname = dirname(fileURLToPath(import.meta.url))
const SOCIAL = join(__dirname, '..', 'promotion', 'social')

/** 与 src/data/promotionVideos.js 中视频基名一致（不含扩展名） */
const VIDEO_BASES = [
  'video-calc-demo-1',
  'video-calc-demo-2',
  'video-aiword',
  'video-voice-office',
  'video-invoice-ai'
]

const FFMPEG_ARGS = (src, dst) => [
  '-y',
  '-i',
  src,
  '-c:v',
  'libx264',
  '-profile:v',
  'high',
  '-pix_fmt',
  'yuv420p',
  '-c:a',
  'aac',
  '-b:a',
  '128k',
  '-movflags',
  '+faststart',
  dst
]

function mtime(p) {
  try {
    return statSync(p).mtimeMs
  } catch {
    return 0
  }
}

function needsTranscode(movPath, mp4Path) {
  if (!existsSync(movPath)) return false
  if (!existsSync(mp4Path)) return true
  return mtime(movPath) > mtime(mp4Path)
}

function ffmpegWorks() {
  const r = spawnSync('ffmpeg', ['-hide_banner', '-version'], {
    encoding: 'utf8',
    stdio: ['ignore', 'pipe', 'pipe']
  })
  return r.status === 0
}

function runTranscode(movPath, mp4Path) {
  console.log(`[transcode] ${movPath} -> ${mp4Path}`)
  const r = spawnSync('ffmpeg', FFMPEG_ARGS(movPath, mp4Path), {
    stdio: 'inherit',
    env: process.env
  })
  return r.status === 0
}

function main() {
  if (process.env.SKIP_PROMOTION_TRANSCODE === '1' || process.env.SKIP_PROMOTION_TRANSCODE === 'true') {
    console.log('[transcode] 已跳过（SKIP_PROMOTION_TRANSCODE）')
    process.exit(0)
  }

  const todo = []
  for (const base of VIDEO_BASES) {
    const movPath = join(SOCIAL, `${base}.mov`)
    const mp4Path = join(SOCIAL, `${base}.mp4`)
    if (needsTranscode(movPath, mp4Path)) {
      todo.push({ movPath, mp4Path, base })
    }
  }

  if (todo.length === 0) {
    console.log('[transcode] 无需转码（无 .mov 或 .mp4 已最新）')
    process.exit(0)
  }

  if (!ffmpegWorks()) {
    console.error(
      '[transcode] 需要转码但未找到 ffmpeg。请安装并加入 PATH：https://ffmpeg.org/download.html\n' +
        '或设置 SKIP_PROMOTION_TRANSCODE=1 跳过（将依赖已存在的 .mp4）'
    )
    process.exit(1)
  }

  for (const { movPath, mp4Path, base } of todo) {
    if (!runTranscode(movPath, mp4Path)) {
      console.error(`[transcode] 失败: ${base}`)
      process.exit(1)
    }
    console.log(`[transcode] 完成: ${base}.mp4`)
  }

  console.log('[transcode] 全部完成')
  process.exit(0)
}

main()
