"use strict";

/**
 * IP 大脑：采集抖音对标账号最新视频标题
 * 由 `/api/v1/nodejs-scripts?name=ip_brain_collect.js` 下发
 */

const {
  normalizeProfileUrl,
  scrapeDouyinProfile,
} = require("./douyin_profile_scraper.js");

globalThis.__nodejsMain = async function (params) {
  const raw = params?.url || params?.profileUrl || "";
  try {
    const url = await normalizeProfileUrl(raw);
    const data = await scrapeDouyinProfile(url);
    const titles = Array.isArray(data.videoTitles) ? data.videoTitles : [];
    if (titles.length === 0) {
      return {
        success: false,
        error:
          "未能采集到视频标题，请确认链接为抖音用户主页且已登录/可访问（可设置 AICLIENT_PUPPETEER_HEADLESS=0 查看浏览器）",
      };
    }
    return {
      success: true,
      accountName: data.accountName || "",
      pageUrl: data.pageUrl || url,
      videoTitles: titles,
    };
  } catch (e) {
    return {
      success: false,
      error: (e && e.message) || String(e),
    };
  }
};
