import { defaultWebSiteId } from '../config'
import { promotionUrl, promotionMediaApiUrl } from '../utils/promotionAssets'

const SOCIAL = 'social'

/**
 * 产品视频与封面统一使用 promotion/social/ 下英文文件名（无空格、无中文路径），便于线上 URL 与 Nginx。
 * 视频请使用 **.mp4（H.264+AAC）** 以保证各系统浏览器可播；剪辑导出多为 .mov 时，用仓库 `scripts/transcode-promotion-videos.*` 转码后再部署。
 * 静态：/promotion/social/xxx.mp4；后台上传路径：promotion/social/ + 下列文件名，勾选「保留原文件名」。
 */
export const PROMOTION_VIDEOS_BASE = [
  {
    id: 'calc-demo-1',
    title: '操作与计算软件实例（一）',
    desc: '宇恒一号宣传片',
    relCover: `${SOCIAL}/video-calc-demo-1-cover.jpg`,
    relVideo: `${SOCIAL}/video-calc-demo-1.mp4`
  },
  {
    id: 'calc-demo-2',
    title: '操作与计算软件实例（二）',
    desc: '进阶操作与计算演示',
    relCover: `${SOCIAL}/video-calc-demo-2-cover.jpg`,
    relVideo: `${SOCIAL}/video-calc-demo-2.mp4`
  },
  {
    id: 'aiword',
    title: '宇恒一号 AI Word 简介',
    desc: 'AI Word 能力介绍',
    relCover: `${SOCIAL}/video-aiword-cover.jpg`,
    relVideo: `${SOCIAL}/video-aiword.mp4`
  },
  {
    id: 'voice',
    title: '语音办公实例',
    desc: '语音驱动办公流程',
    relCover: `${SOCIAL}/video-voice-office-cover.jpg`,
    relVideo: `${SOCIAL}/video-voice-office.mp4`
  },
  {
    id: 'invoice',
    title: 'AI 全自动办发票',
    desc: '发票场景自动化演示',
    relCover: `${SOCIAL}/video-invoice-ai-cover.jpg`,
    relVideo: `${SOCIAL}/video-invoice-ai.mp4`
  }
]

function responseLooksLikeSpaHtml(res) {
  const ct = (res.headers.get('content-type') || '').toLowerCase()
  return ct.includes('text/html')
}

function responseIsUsableAsset(res) {
  if (res.ok) return !responseLooksLikeSpaHtml(res)
  return res.status === 206
}

/**
 * 检测同域静态 /promotion/ 文件是否真实存在。
 * - 需配合 Nginx：`location ^~ /promotion/ { try_files $uri =404; }`，避免缺失时返回 index.html 误判为 200。
 * - HEAD 非 2xx 或疑似 SPA 回退时，再用 Range GET 探测（部分环境对大视频 HEAD 不友好）。
 * @param {string} url
 * @returns {Promise<boolean>}
 */
export async function promotionStaticUrlExists(url) {
  try {
    const head = await fetch(url, {
      method: 'HEAD',
      mode: 'same-origin',
      credentials: 'same-origin',
      cache: 'default'
    })
    if (head.ok && !responseLooksLikeSpaHtml(head)) return true

    const r = await fetch(url, {
      method: 'GET',
      headers: { Range: 'bytes=0-0' },
      mode: 'same-origin',
      credentials: 'same-origin',
      cache: 'default'
    })
    if (!responseIsUsableAsset(r)) return false
    if (responseLooksLikeSpaHtml(r)) return false
    return true
  } catch {
    return false
  }
}

const apiOnly =
  import.meta.env.VITE_PROMOTION_API_ONLY === '1' ||
  import.meta.env.VITE_PROMOTION_API_ONLY === 'true'

/**
 * 有静态则静态，否则（需 siteId）走 promotion-media API（单资源；列表请用 buildPromotionVideosAsync 批量逻辑）
 * @param {string} siteId
 * @param {string} relPath promotion 下相对路径，如 social/xxx.mp4
 */
export async function pickPromotionAssetUrl(siteId, relPath) {
  const sid = String(siteId || defaultWebSiteId || '').trim()
  if (apiOnly && sid) {
    return promotionMediaApiUrl(sid, relPath)
  }
  const staticUrl = promotionUrl(relPath)
  const hasStatic = await promotionStaticUrlExists(staticUrl)
  if (hasStatic) return staticUrl
  if (sid) return promotionMediaApiUrl(sid, relPath)
  return staticUrl
}

/**
 * 同步列表：首屏占位（须与 buildPromotionVideosAsync 一致，避免 apiOnly 时先请求一堆 /promotion/ 404）
 * @param {string} [siteId] 来自缓存的 site_id；会与 defaultWebSiteId 合并
 */
export function buildPromotionVideos(siteId) {
  const sid = String(siteId || defaultWebSiteId || '').trim()
  if (apiOnly && sid) {
    return PROMOTION_VIDEOS_BASE.map((v) => ({
      id: v.id,
      title: v.title,
      desc: v.desc,
      cover: promotionMediaApiUrl(sid, v.relCover),
      src: promotionMediaApiUrl(sid, v.relVideo)
    }))
  }
  return PROMOTION_VIDEOS_BASE.map((v) => ({
    id: v.id,
    title: v.title,
    desc: v.desc,
    cover: promotionUrl(v.relCover),
    src: promotionUrl(v.relVideo)
  }))
}

/**
 * 静态优先：只对「示例封面 + 示例视频」各探测一次，避免 Network 里出现 10+ 条 404。
 * 二者在静态均存在则全套走 /promotion/；否则有 siteId 时全套走 promotion-media API。
 * @param {string} siteId
 */
export async function buildPromotionVideosAsync(siteId) {
  const id = String(siteId || defaultWebSiteId || '').trim()
  const first = PROMOTION_VIDEOS_BASE[0]

  let useStatic = false
  if (apiOnly && id) {
    useStatic = false
  } else if (!apiOnly) {
    const [coverOk, videoOk] = await Promise.all([
      promotionStaticUrlExists(promotionUrl(first.relCover)),
      promotionStaticUrlExists(promotionUrl(first.relVideo))
    ])
    useStatic = coverOk && videoOk
  }

  return PROMOTION_VIDEOS_BASE.map((v) => {
    if (useStatic) {
      return {
        id: v.id,
        title: v.title,
        desc: v.desc,
        cover: promotionUrl(v.relCover),
        src: promotionUrl(v.relVideo)
      }
    }
    if (id) {
      return {
        id: v.id,
        title: v.title,
        desc: v.desc,
        cover: promotionMediaApiUrl(id, v.relCover),
        src: promotionMediaApiUrl(id, v.relVideo)
      }
    }
    return {
      id: v.id,
      title: v.title,
      desc: v.desc,
      cover: promotionUrl(v.relCover),
      src: promotionUrl(v.relVideo)
    }
  })
}

/** @deprecated 请用 buildPromotionVideos() 或 buildPromotionVideosAsync */
export const PROMOTION_VIDEOS = buildPromotionVideos()
