const fs = require('fs');
const path = require('path');

// 1. 读取 package.json
const packageJson = require('./package.json');
const dependencies = packageJson.dependencies || {};
const devDependencies = packageJson.devDependencies || {};

// 2. 生成 Markdown 表格内容的函数
function generateTable(deps, title) {
  if (Object.keys(deps).length === 0) return '';

  let content = `\n### ${title}\n\n`;
  content += '| Package | Version |\n';
  content += '| :--- | :--- |\n';

  for (const [name, version] of Object.entries(deps)) {
    content += `| [${name}](https://www.npmjs.com/package/${name}) | \`${version}\` |\n`;
  }
  return content;
}

// 3. 组合内容
const depContent = generateTable(dependencies, '核心依赖 (Dependencies)') +
                   generateTable(devDependencies, '开发依赖 (DevDependencies)');

// 4. 读取 README.md
const readmePath = path.join(__dirname, 'README.md');
let readmeContent = fs.readFileSync(readmePath, 'utf8');

// 5. 替换标记之间的内容
const startMarker = '';
const endMarker = '';

const regex = new RegExp(`${startMarker}[\\s\\S]*?${endMarker}`);
const newContent = `${startMarker}\n${depContent}\n${endMarker}`;

if (readmeContent.match(regex)) {
  readmeContent = readmeContent.replace(regex, newContent);
  fs.writeFileSync(readmePath, readmeContent);
  console.log('✅ README.md 依赖列表已更新！');
} else {
  console.error('❌ 未在 README.md 中找到占位符 和 ');
}