#!/usr/bin/env node
/**
 * 根据 Cocos 构建出的 index.html，生成可嵌入主站的片段说明
 *
 * node tools/patch-main-index.js build/web-desktop
 */
const fs = require('fs');
const path = require('path');

const buildDir = process.argv[2];
if (!buildDir) {
  console.error('Usage: node patch-main-index.js <build/web-desktop>');
  process.exit(1);
}

const indexPath = path.join(buildDir, 'index.html');
if (!fs.existsSync(indexPath)) {
  console.error('Not found:', indexPath);
  process.exit(1);
}

const html = fs.readFileSync(indexPath, 'utf8');

// 提取所有 script 标签（Cocos 启动链）
const scripts = [];
const re = /<script[^>]*src=["']([^"']+)["'][^>]*><\/script>/gi;
let m;
while ((m = re.exec(html)) !== null) {
  scripts.push(m[1]);
}

// 提取内联 script（System.import 等）
const inline = html.match(/<script>([\s\S]*?)<\/script>/gi) || [];

console.log('=== 复制到主站 index.html（替换 Unity Build 段）===\n');
console.log('<!-- ① 主站公共：放在 head 或 body 开头 -->');
console.log('<script src="cocos-bridge.js"></script>\n');
console.log('<!-- ② Cocos 启动脚本（路径相对主站页面，若游戏在 /cocos/ 子目录则加前缀 cocos/） -->');
for (const src of scripts) {
  const rel = src.startsWith('http') ? src : `cocos/${src.replace(/^\.\//, '')}`;
  console.log(`<script src="${rel}" charset="utf-8"></script>`);
}
console.log('\n<!-- ③ 容器（若主站已有 #GameDiv 可保留原 id） -->');
const canvasMatch = html.match(/<canvas[^>]*id=["']([^"']+)["'][^>]*>/i);
const divMatch = html.match(/id=["'](GameDiv|Cocos3dGameContainer)["']/i);
console.log('<!-- Cocos 构建页中的 canvas id:', canvasMatch ? canvasMatch[1] : 'GameCanvas', '-->');

if (inline.length) {
  console.log('\n<!-- ④ 内联启动（从 build/index.html 复制以下 block） -->');
  inline.forEach((block) => console.log(block));
}

console.log('\n=== 删除原 Unity 段 ===');
console.log('- Build/build.loader.js');
console.log('- createUnityInstance(...)');
