"use strict";

/**
 * 多平台视频发布（工作流步骤 07 / 一键自动）
 */
const { publishToPlatform, PLATFORM_LABELS } = require("./publish_platform.js");

globalThis.__nodejsMain = async function main(params) {
  const p = params || {};
  const platforms = Array.isArray(p.platforms) ? p.platforms : [];
  const videoPath = String(p.videoPath || "").trim();
  const coverPath = String(p.coverPath || "").trim();
  const title = String(p.title || "").trim();
  const description = String(p.description || title || "").trim();
  const tags = Array.isArray(p.tags) ? p.tags : [];
  const autoPublish = Boolean(p.autoPublish);

  if (!platforms.length) {
    return { success: false, error: "请至少选择一个发布平台" };
  }
  if (!videoPath) return { success: false, error: "缺少视频路径" };
  if (!coverPath) return { success: false, error: "缺少封面路径，请先在步骤 06 生成封面" };
  if (!title) return { success: false, error: "缺少标题，请先在步骤 04 生成标题" };

  const results = [];
  for (let i = 0; i < platforms.length; i++) {
    const item = platforms[i];
    const platform = item.platform;
    const accountId = item.accountId;
    const cookies = item.cookies || [];
    const label = PLATFORM_LABELS[platform] || platform;
    globalThis.__native?.emitProgress?.(
      `正在发布到${label}… (${i + 1}/${platforms.length})`,
    );
    try {
      const r = await publishToPlatform(platform, accountId, cookies, {
        videoPath,
        coverPath,
        title,
        description,
        tags,
        autoPublish,
        keepPageOpen: !autoPublish,
      });
      results.push({
        platform: label,
        platformKey: platform,
        success: Boolean(r.success),
        pending:
          r.status === "manual_pending" || r.status === "verification_required",
        status: r.status || (r.success ? "success" : "failed"),
        message: r.message || "",
        videoUrl: r.videoUrl || "",
      });
    } catch (e) {
      results.push({
        platform: label,
        platformKey: platform,
        success: false,
        pending: false,
        status: "failed",
        message: e.message || String(e),
      });
    }
    if (i < platforms.length - 1) {
      await new Promise((r) => setTimeout(r, 2000));
    }
  }

  const ok = results.filter((r) => r.success).length;
  const pending = results.filter((r) => r.pending).length;
  const failed = results.length - ok - pending;

  const keepBrowserOpen = results.some(
    (r) =>
      r.pending ||
      r.status === "manual_pending" ||
      r.status === "verification_required",
  );

  return {
    success: ok > 0 || pending > 0,
    keepBrowserOpen,
    results,
    summary: { ok, pending, failed, total: results.length },
    message:
      ok === results.length
        ? "全部发布成功"
        : pending > 0
          ? `成功 ${ok}，待确认 ${pending}，失败 ${failed}`
          : `成功 ${ok}，失败 ${failed}`,
  };
};
