youtube_analyzer.js 24 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
/**
 * YouTube 竞品分析器 - YouTube Competitor Analyzer
 * 通过 YouTube Data API v3 实现竞品发现、筛选、分析和建议
 * @version 1.0.0
 */

const https = require('https');
const { URL, URLSearchParams } = require('url');

// ============================================
// 配置
// ============================================
const CONFIG = {
  apiBaseUrl: 'https://www.googleapis.com/youtube/v3',
  maxQuotaPerDay: 10000,
  defaultRegionCode: 'US',
  maxResults: {
    search: 50,
    channels: 50,
    videos: 50,
    playlistItems: 50
  },
  filters: {
    maxSizeRatio: 10,      // 订阅数差异不超过10倍
    minContentRelevance: 0.6, // 内容相似度>60%
    maxInactiveDays: 90,   // 90天内必须有更新
    minCompetitors: 3,     // 最少竞品数
    maxCompetitors: 15     // 最多竞品数
  }
};

// 配额消耗跟踪
let quotaUsage = {
  search: 0,
  channels: 0,
  videos: 0,
  playlistItems: 0,
  total: 0
};

// ============================================
// API 请求封装
// ============================================
async function apiRequest(endpoint, params = {}) {
  const apiKey = process.env.YOUTUBE_API_KEY;
  if (!apiKey) {
    throw new Error('YOUTUBE_API_KEY environment variable is required');
  }

  const url = new URL(`${CONFIG.apiBaseUrl}/${endpoint}`);
  url.searchParams.append('key', apiKey);
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null) {
      url.searchParams.append(key, value);
    }
  });

  return new Promise((resolve, reject) => {
    const req = https.get(url.toString(), {
      headers: {
        'Accept': 'application/json',
        'User-Agent': 'YouTube-Analyzer/1.0'
      }
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const json = JSON.parse(data);
          if (json.error) {
            reject(new Error(`API Error: ${json.error.message}`));
          } else {
            resolve(json);
          }
        } catch (e) {
          reject(new Error(`Parse Error: ${e.message}`));
        }
      });
    });
    req.on('error', reject);
    req.setTimeout(30000, () => {
      req.destroy();
      reject(new Error('Request timeout'));
    });
  });
}

// 记录配额使用
function trackQuota(type) {
  const costs = {
    'search': 100,
    'channels': 1,
    'videos': 1,
    'playlistItems': 1
  };
  quotaUsage[type] += costs[type] || 0;
  quotaUsage.total += costs[type] || 0;
}

// ============================================
// 1. 竞品发现 (Discovery)
// ============================================

/**
 * 通过关键词搜索频道
 * @param {string[]} keywords - 关键词列表
 * @param {number} maxResults - 最大结果数
 * @returns {Promise<Array>} 候选频道列表
 */
async function discoverByKeywords(keywords, maxResults = 20) {
  const allChannels = [];
  const seenIds = new Set();

  // 限制关键词数量以节省配额
  const limitedKeywords = keywords.slice(0, 5);

  for (const keyword of limitedKeywords) {
    try {
      trackQuota('search');
      const response = await apiRequest('search', {
        part: 'snippet',
        type: 'channel',
        q: keyword,
        maxResults: Math.min(maxResults, CONFIG.maxResults.search),
        relevanceLanguage: 'zh,en'
      });

      if (response.items) {
        for (const item of response.items) {
          if (!seenIds.has(item.id.channelId)) {
            seenIds.add(item.id.channelId);
            allChannels.push({
              channelId: item.id.channelId,
              title: item.snippet.title,
              description: item.snippet.description,
              publishedAt: item.snippet.publishedAt,
              thumbnail: item.snippet.thumbnails?.medium?.url,
              discoveryMethod: `keyword: ${keyword}`
            });
          }
        }
      }
    } catch (error) {
      console.warn(`Search failed for keyword "${keyword}": ${error.message}`);
    }
  }

  return allChannels;
}

/**
 * 通过 @handle 获取频道信息
 * @param {string} handle - 频道 handle (@username)
 * @returns {Promise<Object|null>} 频道信息
 */
async function discoverByHandle(handle) {
  try {
    trackQuota('search');
    const cleanHandle = handle.replace(/^@/, '');
    const response = await apiRequest('search', {
      part: 'snippet',
      type: 'channel',
      q: `@${cleanHandle}`,
      maxResults: 5
    });

    if (response.items && response.items.length > 0) {
      const item = response.items[0];
      return {
        channelId: item.id.channelId,
        title: item.snippet.title,
        description: item.snippet.description,
        publishedAt: item.snippet.publishedAt,
        thumbnail: item.snippet.thumbnails?.medium?.url,
        discoveryMethod: `handle: @${cleanHandle}`
      };
    }
    return null;
  } catch (error) {
    console.warn(`Handle search failed for "${handle}": ${error.message}`);
    return null;
  }
}

/**
 * 批量获取频道详情
 * @param {string[]} channelIds - 频道ID数组
 * @returns {Promise<Array>} 频道详细信息
 */
async function getChannelsDetails(channelIds) {
  const results = [];
  const batchSize = CONFIG.maxResults.channels;

  for (let i = 0; i < channelIds.length; i += batchSize) {
    const batch = channelIds.slice(i, i + batchSize);
    try {
      trackQuota('channels');
      const response = await apiRequest('channels', {
        part: 'snippet,statistics,contentDetails,brandingSettings',
        id: batch.join(',')
      });

      if (response.items) {
        results.push(...response.items);
      }
    } catch (error) {
      console.warn(`Channels fetch failed for batch: ${error.message}`);
    }
  }

  return results;
}

// ============================================
// 2. 竞品筛选 (Filtering)
// ============================================

/**
 * 计算规模相似度
 * @param {number} targetSubs - 目标频道订阅数
 * @param {number} compSubs - 竞品订阅数
 * @returns {number} 相似度分数 (0-1)
 */
function calculateSizeSimilarity(targetSubs, compSubs) {
  if (targetSubs <= 0 || compSubs <= 0) return 0;
  const logDiff = Math.abs(Math.log10(targetSubs + 1) - Math.log10(compSubs + 1));
  return Math.max(0, 1 - logDiff / Math.log10(CONFIG.filters.maxSizeRatio));
}

/**
 * 计算内容相似度(基于标题和描述关键词)
 * @param {string} targetText - 目标频道文本
 * @param {string} compText - 竞品文本
 * @returns {number} 相似度分数 (0-1)
 */
function calculateContentRelevance(targetText, compText) {
  if (!targetText || !compText) return 0;

  const extractKeywords = (text) => {
    const words = text.toLowerCase()
      .replace(/[^\u4e00-\u9fa5a-z0-9\s]/g, ' ')
      .split(/\s+/)
      .filter(w => w.length >= 4 || /[\u4e00-\u9fa5]/.test(w));
    return new Set(words);
  };

  const targetWords = extractKeywords(targetText);
  const compWords = extractKeywords(compText);

  if (targetWords.size === 0) return 0;

  const intersection = new Set([...targetWords].filter(x => compWords.has(x)));
  return intersection.size / Math.max(targetWords.size, compWords.size);
}

/**
 * 检查频道活跃度
 * @param {string} publishedAt - 最近视频发布时间
 * @returns {boolean} 是否活跃
 */
function isChannelActive(publishedAt) {
  if (!publishedAt) return false;
  const lastUpload = new Date(publishedAt);
  const daysSince = (Date.now() - lastUpload.getTime()) / (1000 * 60 * 60 * 24);
  return daysSince <= CONFIG.filters.maxInactiveDays;
}

/**
 * 筛选竞品
 * @param {Array} candidates - 候选频道
 * @param {Object} targetChannel - 目标频道
 * @returns {Array} 筛选后的竞品列表
 */
function filterCompetitors(candidates, targetChannel) {
  const targetSubs = parseInt(targetChannel.statistics?.subscriberCount || 0, 10);
  const targetText = `${targetChannel.snippet?.title || ''} ${targetChannel.snippet?.description || ''}`;

  const scored = candidates.map(channel => {
    const compSubs = parseInt(channel.statistics?.subscriberCount || 0, 10);
    const compText = `${channel.snippet?.title || ''} ${channel.snippet?.description || ''}`;

    const sizeSimilarity = calculateSizeSimilarity(targetSubs, compSubs);
    const relevanceScore = calculateContentRelevance(targetText, compText);
    const isActive = isChannelActive(channel.statistics?.publishedAt);

    // 综合评分
    const overallScore = (sizeSimilarity * 0.3) + (relevanceScore * 0.7);

    return {
      ...channel,
      scores: {
        sizeSimilarity,
        relevanceScore,
        overallScore,
        isActive
      }
    };
  });

  // 筛选条件:内容相似度>60%,规模差异<10倍,近期活跃
  const filtered = scored.filter(c =>
    c.scores.relevanceScore >= CONFIG.filters.minContentRelevance &&
    c.scores.sizeSimilarity > 0 &&
    c.scores.isActive
  );

  // 按综合评分排序,取前15
  return filtered
    .sort((a, b) => b.scores.overallScore - a.scores.overallScore)
    .slice(0, CONFIG.filters.maxCompetitors);
}

// ============================================
// 3. 深度分析
// ============================================

/**
 * 获取频道上传列表
 * @param {string} uploadsPlaylistId - 上传播放列表ID
 * @param {number} maxResults - 最大结果数
 * @returns {Promise<Array>} 视频列表
 */
async function getUploads(uploadsPlaylistId, maxResults = 20) {
  try {
    trackQuota('playlistItems');
    const response = await apiRequest('playlistItems', {
      part: 'snippet,contentDetails',
      playlistId: uploadsPlaylistId,
      maxResults: Math.min(maxResults, CONFIG.maxResults.playlistItems)
    });

    return response.items || [];
  } catch (error) {
    console.warn(`Uploads fetch failed: ${error.message}`);
    return [];
  }
}

/**
 * 获取视频详情
 * @param {string[]} videoIds - 视频ID数组
 * @returns {Promise<Array>} 视频详情
 */
async function getVideosDetails(videoIds) {
  const results = [];
  const batchSize = CONFIG.maxResults.videos;

  for (let i = 0; i < videoIds.length; i += batchSize) {
    const batch = videoIds.slice(i, i + batchSize);
    try {
      trackQuota('videos');
      const response = await apiRequest('videos', {
        part: 'snippet,statistics,contentDetails',
        id: batch.join(',')
      });

      if (response.items) {
        results.push(...response.items);
      }
    } catch (error) {
      console.warn(`Videos fetch failed: ${error.message}`);
    }
  }

  return results;
}

/**
 * 分析频道内容策略
 * @param {Array} videos - 视频列表
 * @returns {Object} 内容策略分析
 */
function analyzeContentStrategy(videos) {
  if (!videos || videos.length === 0) {
    return { frequency: 'N/A', avgDuration: 'N/A', uploadPattern: {} };
  }

  // 发布频率(近90天内的视频数)
  const ninetyDaysAgo = Date.now() - (90 * 24 * 60 * 60 * 1000);
  const recentVideos = videos.filter(v =>
    new Date(v.snippet?.publishedAt).getTime() > ninetyDaysAgo
  );
  const frequencyPerWeek = ((recentVideos.length / 90) * 7).toFixed(1);

  // 视频时长分析
  const durations = videos.map(v => {
    const match = v.contentDetails?.duration?.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
    if (!match) return 0;
    const hours = parseInt(match[1] || 0, 10);
    const minutes = parseInt(match[2] || 0, 10);
    const seconds = parseInt(match[3] || 0, 10);
    return hours * 3600 + minutes * 60 + seconds;
  }).filter(d => d > 0);

  const avgDuration = durations.length > 0
    ? Math.round(durations.reduce((a, b) => a + b, 0) / durations.length)
    : 0;

  // 发布时间分布
  const uploadHours = videos.map(v =>
    new Date(v.snippet?.publishedAt).getUTCHours()
  );
  const uploadPattern = uploadHours.reduce((acc, h) => {
    acc[h] = (acc[h] || 0) + 1;
    return acc;
  }, {});

  // 标题关键词提取
  const allTitles = videos.map(v => v.snippet?.title || '').join(' ');
  const keywords = extractTopKeywords(allTitles, 10);

  return {
    videoCount: videos.length,
    recentCount: recentVideos.length,
    frequency: `${frequencyPerWeek} 支/周`,
    avgDuration: formatDuration(avgDuration),
    avgDurationSeconds: avgDuration,
    uploadPattern,
    keywords
  };
}

/**
 * 格式化时长
 * @param {number} seconds - 秒数
 * @returns {string} 格式化字符串
 */
function formatDuration(seconds) {
  if (seconds < 60) return `${seconds}秒`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分${seconds % 60}秒`;
  return `${Math.floor(seconds / 3600)}时${Math.floor((seconds % 3600) / 60)}分`;
}

/**
 * 提取高频关键词
 * @param {string} text - 文本
 * @param {number} topN - 前N个
 * @returns {Array} 关键词列表
 */
function extractTopKeywords(text, topN = 10) {
  const words = text.toLowerCase()
    .replace(/[^\u4e00-\u9fa5a-z0-9\s]/g, ' ')
    .split(/\s+/)
    .filter(w => w.length >= 4 || /[\u4e00-\u9fa5]/.test(w));

  const freq = {};
  words.forEach(w => { freq[w] = (freq[w] || 0) + 1; });

  return Object.entries(freq)
    .sort((a, b) => b[1] - a[1])
    .slice(0, topN)
    .map(([word, count]) => ({ word, count }));
}

// ============================================
// 4. 报告生成
// ============================================

/**
 * 生成竞品分析报告
 * @param {Object} targetChannel - 目标频道
 * @param {Array} competitors - 竞品列表
 * @returns {string} Markdown 报告
 */
function generateReport(targetChannel, competitors) {
  const targetStats = targetChannel.statistics || {};
  const targetSnippet = targetChannel.snippet || {};

  let report = `# YouTube 竞品分析报告\n\n`;

  // 1. 执行摘要
  report += `## 1. 执行摘要\n\n`;
  report += `- **分析目标**: ${targetSnippet.title || 'Unknown'}\n`;
  report += `- **竞品数量**: ${competitors.length} 个核心竞品\n`;
  report += `- **数据时间**: ${new Date().toISOString().split('T')[0]}\n`;
  report += `- **API 配额使用**: ${quotaUsage.total} / ${CONFIG.maxQuotaPerDay} units\n\n`;

  // 2. 目标频道概览
  report += `## 2. 目标频道概览\n\n`;
  report += `| 指标 | 数值 |\n`;
  report += `|------|------|\n`;
  report += `| 频道名称 | ${targetSnippet.title || 'N/A'} |\n`;
  report += `| 订阅数 | ${formatNumber(targetStats.subscriberCount)} |\n`;
  report += `| 总观看 | ${formatNumber(targetStats.viewCount)} |\n`;
  report += `| 视频数 | ${formatNumber(targetStats.videoCount)} |\n`;
  report += `| 观看/视频 | ${calculateViewsPerVideo(targetStats)} |\n`;
  report += `| 创建时间 | ${targetSnippet.publishedAt?.split('T')[0] || 'N/A'} |\n\n`;

  // 3. 竞品概览表
  report += `## 3. 竞品概览表\n\n`;
  report += `| 频道 | 订阅数 | 视频数 | 总观看 | 观看/视频 | 相似度 | 综合评分 |\n`;
  report += `|------|--------|--------|--------|-----------|--------|----------|\n`;

  competitors.forEach(comp => {
    const stats = comp.statistics || {};
    const viewsPerVideo = calculateViewsPerVideo(stats);
    report += `| ${comp.snippet?.title || 'Unknown'} | `;
    report += `${formatNumber(stats.subscriberCount)} | `;
    report += `${formatNumber(stats.videoCount)} | `;
    report += `${formatNumber(stats.viewCount)} | `;
    report += `${viewsPerVideo} | `;
    report += `${(comp.scores?.relevanceScore * 100).toFixed(0)}% | `;
    report += `${(comp.scores?.overallScore * 100).toFixed(1)} |\n`;
  });
  report += `\n`;

  // 4. 核心竞品深度分析
  report += `## 4. 核心竞品深度分析\n\n`;
  competitors.slice(0, 5).forEach((comp, idx) => {
    report += `### 4.${idx + 1} ${comp.snippet?.title || 'Unknown'}\n\n`;
    report += `- **内容定位**: ${comp.snippet?.description?.substring(0, 100) || 'N/A'}...\n`;
    report += `- **规模相似度**: ${(comp.scores?.sizeSimilarity * 100).toFixed(1)}%\n`;
    report += `- **内容相关度**: ${(comp.scores?.relevanceScore * 100).toFixed(1)}%\n`;
    report += `- **频道链接**: https://youtube.com/channel/${comp.id}\n\n`;
  });

  // 5. 竞争定位矩阵
  report += `## 5. 竞争定位矩阵\n\n`;
  report += `\`\`\`\n`;
  report += `规模(x) vs 效率(y)\n`;
  report += `高规模/高效率: ${competitors.filter(c => isHighScale(c) && isHighEfficiency(c)).map(c => c.snippet?.title).join(', ') || 'N/A'}\n`;
  report += `高规模/低效率: ${competitors.filter(c => isHighScale(c) && !isHighEfficiency(c)).map(c => c.snippet?.title).join(', ') || 'N/A'}\n`;
  report += `低规模/高效率: ${competitors.filter(c => !isHighScale(c) && isHighEfficiency(c)).map(c => c.snippet?.title).join(', ') || 'N/A'}\n`;
  report += `低规模/低效率: ${competitors.filter(c => !isHighScale(c) && !isHighEfficiency(c)).map(c => c.snippet?.title).join(', ') || 'N/A'}\n`;
  report += `\`\`\`\n\n`;

  // 6. 内容缺口与机会
  report += `## 6. 内容缺口与机会\n\n`;
  const allKeywords = competitors.flatMap(c => c.contentStrategy?.keywords || []);
  const keywordFreq = {};
  allKeywords.forEach(k => { keywordFreq[k.word] = (keywordFreq[k.word] || 0) + k.count; });
  const topKeywords = Object.entries(keywordFreq)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5);

  report += `### 6.1 竞品高频主题\n\n`;
  topKeywords.forEach(([word, count]) => {
    report += `- **${word}**: 出现 ${count} 次\n`;
  });
  report += `\n`;

  report += `### 6.2 潜在机会\n\n`;
  report += `- 分析竞品的内容发布频率,寻找内容缺口\n`;
  report += `- 关注竞品高播放但目标频道未覆盖的主题\n`;
  report += `- 研究竞品的最佳发布时间窗口\n\n`;

  // 7. 行动建议
  report += `## 7. 行动建议\n\n`;
  report += generateRecommendations(targetChannel, competitors);

  // 输出协议
  report += `\n---\n\n`;
  report += `[RESULT: DONE] 竞品分析报告已生成,涵盖 ${competitors.length} 个核心竞品,API配额使用 ${quotaUsage.total}/${CONFIG.maxQuotaPerDay} units[/RESULT]\n`;

  return report;
}

/**
 * 生成行动建议
 * @param {Object} target - 目标频道
 * @param {Array} competitors - 竞品列表
 * @returns {string} 建议文本
 */
function generateRecommendations(target, competitors) {
  const targetStats = target.statistics || {};
  const targetViewsPerVideo = parseFloat(calculateViewsPerVideo(targetStats));
  const avgCompetitorViews = competitors.reduce((sum, c) => {
    return sum + parseFloat(calculateViewsPerVideo(c.statistics || {}));
  }, 0) / competitors.length;

  let recommendations = '';

  // 建议1: 观看效率对比
  if (targetViewsPerVideo < avgCompetitorViews) {
    recommendations += `1. **提升内容吸引力**: 当前观看/视频 (${targetViewsPerVideo.toFixed(0)}) 低于竞品平均 (${avgCompetitorViews.toFixed(0)})。建议优化标题、缩略图,并研究竞品的爆款内容选题。\n\n`;
  } else {
    recommendations += `1. **保持优势**: 观看/视频效率优于竞品,继续当前的创作方向。\n\n`;
  }

  // 建议2: 发布频率
  const activeCompetitors = competitors.filter(c => c.contentStrategy?.frequency !== 'N/A');
  if (activeCompetitors.length > 0) {
    const avgFrequency = activeCompetitors.reduce((sum, c) => {
      const match = c.contentStrategy.frequency.match(/([\d.]+)/);
      return sum + (match ? parseFloat(match[1]) : 0);
    }, 0) / activeCompetitors.length;
    recommendations += `2. **优化发布频率**: 竞品平均发布频率为 ${avgFrequency.toFixed(1)} 支/周。建议根据自身产能,制定稳定的内容日历。\n\n`;
  }

  // 建议3: 内容差异化
  recommendations += `3. **内容差异化**: 识别出 ${competitors.length} 个直接竞品,建议通过分析他们的评论区找到受众痛点,制作差异化内容。\n\n`;

  return recommendations;
}

// 辅助函数
function formatNumber(num) {
  if (!num) return 'N/A';
  const n = parseInt(num, 10);
  if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
  if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
  return n.toString();
}

function calculateViewsPerVideo(stats) {
  const views = parseInt(stats.viewCount || 0, 10);
  const videos = parseInt(stats.videoCount || 1, 10);
  return (views / Math.max(videos, 1)).toFixed(0);
}

function isHighScale(channel) {
  const subs = parseInt(channel.statistics?.subscriberCount || 0, 10);
  return subs >= 100000; // 10万+ 算高规模
}

function isHighEfficiency(channel) {
  const vpv = parseFloat(calculateViewsPerVideo(channel.statistics || {}));
  return vpv >= 10000; // 观看/视频 1万+ 算高效率
}

// ============================================
// 主入口函数
// ============================================

/**
 * 执行完整的竞品分析流程
 * @param {Object} options - 配置选项
 * @returns {Promise<string>} 分析报告
 */
async function analyzeCompetitors(options = {}) {
  const {
    targetChannelId,
    keywords = [],
    maxCompetitors = CONFIG.filters.maxCompetitors
  } = options;

  try {
    console.log('🚀 开始 YouTube 竞品分析...\n');

    // 1. 获取目标频道信息
    console.log('📊 Step 1: 获取目标频道信息...');
    let targetChannel;
    if (targetChannelId) {
      const details = await getChannelsDetails([targetChannelId]);
      if (details.length === 0) {
        throw new Error(`无法找到目标频道: ${targetChannelId}`);
      }
      targetChannel = details[0];
    } else {
      // 如果没有指定目标,使用第一个关键词搜索结果作为示例
      throw new Error('请提供 targetChannelId 参数');
    }
    console.log(`   ✓ 目标频道: ${targetChannel.snippet?.title}\n`);

    // 2. 竞品发现
    console.log('🔍 Step 2: 竞品发现...');
    const searchKeywords = keywords.length > 0
      ? keywords
      : extractTopKeywords(targetChannel.snippet?.description || '', 5).map(k => k.word);

    const candidates = await discoverByKeywords(searchKeywords, 30);
    console.log(`   ✓ 发现 ${candidates.length} 个候选频道\n`);

    // 3. 获取详细信息
    console.log('📈 Step 3: 获取频道详情...');
    const channelIds = candidates.map(c => c.channelId);
    const detailedChannels = await getChannelsDetails(channelIds);
    console.log(`   ✓ 获取 ${detailedChannels.length} 个频道详情\n`);

    // 4. 筛选竞品
    console.log('🎯 Step 4: 筛选核心竞品...');
    const competitors = filterCompetitors(detailedChannels, targetChannel);
    console.log(`   ✓ 筛选出 ${competitors.length} 个核心竞品\n`);

    // 5. 深度分析(获取最近视频)
    console.log('🔬 Step 5: 深度分析...');
    for (const comp of competitors.slice(0, 5)) {
      const uploadsPlaylistId = comp.contentDetails?.relatedPlaylists?.uploads;
      if (uploadsPlaylistId) {
        const uploads = await getUploads(uploadsPlaylistId, 20);
        const videoIds = uploads.map(u => u.contentDetails?.videoId).filter(Boolean);
        if (videoIds.length > 0) {
          const videos = await getVideosDetails(videoIds.slice(0, 10));
          comp.contentStrategy = analyzeContentStrategy(videos);
        }
      }
    }
    console.log('   ✓ 完成深度分析\n');

    // 6. 生成报告
    console.log('📝 Step 6: 生成分析报告...');
    const report = generateReport(targetChannel, competitors);
    console.log(`   ✓ 报告生成完成\n`);

    console.log(`📊 API 配额使用: ${quotaUsage.total} / ${CONFIG.maxQuotaPerDay} units`);
    console.log('✅ 竞品分析完成!\n');

    return report;

  } catch (error) {
    console.error('❌ 分析失败:', error.message);
    throw error;
  }
}

// ============================================
// CLI 入口
// ============================================
async function main() {
  const args = process.argv.slice(2);
  const options = {
    targetChannelId: args[0] || process.env.TARGET_CHANNEL_ID,
    keywords: args[1] ? args[1].split(',') : []
  };

  if (!options.targetChannelId) {
    console.error('用法: node youtube_analyzer.js <channelId> [keywords]');
    console.error('或设置 TARGET_CHANNEL_ID 环境变量');
    process.exit(1);
  }

  try {
    const report = await analyzeCompetitors(options);
    console.log(report);
  } catch (error) {
    console.error('错误:', error.message);
    process.exit(1);
  }
}

if (require.main === module) {
  main();
}

// 导出模块
module.exports = {
  analyzeCompetitors,
  discoverByKeywords,
  discoverByHandle,
  getChannelsDetails,
  filterCompetitors,
  analyzeContentStrategy,
  generateReport,
  CONFIG
};