import fs from 'fs'
import axios from 'axios'

function parseChangelog(changelogText) {
  const result = [];
  const versionRegex = /^#{1,3} \[([\d.]+)\]/;
  const sectionRegex = /^### (.*?) \| (.*)$/;
  const breakingChangesRegex = /^### ⚠ BREAKING CHANGES$/;
  const descRegex = /^\* \*\*(.*?):?\*\* (.*?) \(/;

  let currentVersionObj = null;
  let currentSection = null;
  let isBreakingChanges = false;

  const lines = changelogText.split('\n');

  for (const line of lines) {
    const trimmedLine = line.trim();

    // 检查是否是版本行
    const versionMatch = trimmedLine.match(versionRegex);
    if (versionMatch) {
      // 保存当前版本对象（如果有）
      if (currentVersionObj) {
        // 清理空版本
        if (currentVersionObj.breakingChanges.length > 0 ||
          currentVersionObj.changes.length > 0) {
          result.push(currentVersionObj);
        }
      }

      // 创建新版本对象
      currentVersionObj = {
        version: versionMatch[1],
        breakingChanges: [],
        changes: []
      };
      isBreakingChanges = false;
      currentSection = null;
      continue;
    }

    if (!currentVersionObj) continue;

    // 检查是否是BREAKING CHANGES部分
    if (trimmedLine.match(breakingChangesRegex)) {
      isBreakingChanges = true;
      currentSection = {
        type: '重大变化',
        desc: []
      };
      currentVersionObj.changes.push(currentSection);
      continue;
    }

    // 检查是否是普通章节部分
    const sectionMatch = trimmedLine.match(sectionRegex);
    if (sectionMatch) {
      isBreakingChanges = false;
      currentSection = {
        type: sectionMatch[2],
        desc: []
      };
      currentVersionObj.changes.push(currentSection);
      continue;
    }

    // 收集描述内容
    const descMatch = trimmedLine.match(descRegex);
    if (descMatch) {
      const description = descMatch[2].trim();
      if (isBreakingChanges) {
        currentVersionObj.breakingChanges.push(description);
        if (currentSection) {
          currentSection.desc.push(description);
        }
      } else if (currentSection) {
        currentSection.desc.push(description);
      }
    }
  }

  // 添加最后一个版本对象
  if (currentVersionObj &&
    (currentVersionObj.breakingChanges.length > 0 ||
      currentVersionObj.changes.length > 0)) {
    result.push(currentVersionObj);
  }

  return result;
}

const changelog = './CHANGELOG.md'
const changeData = fs.readFileSync(changelog, 'utf-8')
const result = parseChangelog(changeData)
console.log(result)
axios({
  url: 'https://sfa.wxl66.cn/api/bi/front/version/core',
  method: 'POST',
  data: result
})
