import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const parentDir = path.join(__dirname, '../..');

// 默认版本，如果没扫到就用这个
const versions = {
  'state': '1.0.11',
  'bootstrap': '1.0.0',
  'base': '1.0.7',
  'datatable': '1.0.6',
  'kanban': '1.0.0',
  'mindmap': '1.0.0',
  'chart': '1.0.0',
  'editor': '1.0.0'
};

// 1. 扫描同级目录获取最新版本号
try {
  const dirs = fs.readdirSync(parentDir);
  dirs.forEach(dir => {
    const pkgPath = path.join(parentDir, dir, 'package.json');
    if (fs.existsSync(pkgPath)) {
      try {
        const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
        if (pkg.name && pkg.name.startsWith('@apigo.cc/')) {
          const key = pkg.name.replace('@apigo.cc/', '').toLowerCase();
          if (pkg.version) {
            versions[key] = pkg.version;
          }
        }
      } catch (e) {
        console.warn(`Failed to parse ${pkgPath}:`, e.message);
      }
    }
  });
} catch (err) {
  console.error('Failed to read parent directory:', err.message);
}

console.log('Gathered versions:', versions);

// 2. 获取 loader 自己的版本号
const loaderPkgPath = path.join(__dirname, '../package.json');
let loaderVersion = '1.0.0';
try {
  const loaderPkg = JSON.parse(fs.readFileSync(loaderPkgPath, 'utf8'));
  loaderVersion = loaderPkg.version || '1.0.0';
} catch (e) {
  console.warn('Failed to read loader package.json:', e.message);
}

// 3. 更新 loader/src/index.js
const indexPath = path.join(__dirname, '../src/index.js');
if (fs.existsSync(indexPath)) {
  let indexContent = fs.readFileSync(indexPath, 'utf8');
  const versionsString = Object.entries(versions)
    .map(([k, v]) => `    '${k}': '${v}'`)
    .join(',\n');
  
  const newDefaultVersions = `const DEFAULT_VERSIONS = {\n${versionsString}\n};`;
  indexContent = indexContent.replace(/const DEFAULT_VERSIONS = \{[\s\S]*?\};/, newDefaultVersions);
  
  fs.writeFileSync(indexPath, indexContent, 'utf8');
  console.log('Updated loader/src/index.js DEFAULT_VERSIONS.');
}

// 4. 更新 loader/README.md
const readmePath = path.join(__dirname, '../README.md');
if (fs.existsSync(readmePath)) {
  let readmeContent = fs.readFileSync(readmePath, 'utf8');

  // 替换 Loader.load('state', 'bootstrap', 'base') 里的版本号
  // 支持形如 Loader.load('state:x.y.z', 'bootstrap:x.y.z', 'base:x.y.z')
  // 或者最原始的 Loader.load('state', 'bootstrap', 'base')
  readmeContent = readmeContent.replace(
    /Loader\.load\(([^)]*)\)/g,
    (match, p1) => {
      // 按照逗号拆分，但保留各行原样（包含可能的换行和注释）
      const items = p1.split(',');
      const newItems = items.map(item => {
        const trimmed = item.trim();
        if (trimmed.startsWith('//') || !trimmed) {
          return item;
        }
        
        // 提取清除引号后的内容进行路径和版本判断
        const cleanItem = trimmed.replace(/['"]/g, '');
        const colonIdx = cleanItem.indexOf(':');
        const name = colonIdx === -1 ? cleanItem : cleanItem.slice(0, colonIdx);
        const val = colonIdx === -1 ? '' : cleanItem.slice(colonIdx + 1);

        // 如果值里包含 http://, https://, ./, ../, / 说明是调试重定向路径，原样保留
        if (val && (/^(https?:|\.|\/)/.test(val))) {
          return item;
        }

        const key = name.toLowerCase();
        if (versions[key]) {
          // 尽量保留原有的包裹引号格式
          const quote = item.includes('"') ? '"' : "'";
          return `${quote}${key}:${versions[key]}${quote}`;
        }
        return item;
      });
      return `Loader.load(${newItems.join(',')})`;
    }
  );

  // 替换 cdn 链接及所有地方的 loader 版本
  readmeContent = readmeContent.replace(
    /(@apigo\.cc\/loader@)[0-9.]+(\/dist\/loader)/g,
    `$1${loaderVersion}$2`
  );

  // 替换 manual import 里的依赖版本，如：
  // "@apigo.cc/state": "https://cdn.jsdelivr.net/npm/@apigo.cc/state@1.0.11/dist/state.min.js",
  readmeContent = readmeContent.replace(
    /(\/@apigo\.cc\/([a-zA-Z0-9_-]+)@)[0-9.]+(\/dist\/)/g,
    (match, prefix, name, suffix) => {
      const key = name.toLowerCase();
      const ver = key === 'loader' ? loaderVersion : (versions[key] || 'latest');
      return `${prefix}${ver}${suffix}`;
    }
  );

  fs.writeFileSync(readmePath, readmeContent, 'utf8');
  console.log('Updated loader/README.md versions.');
}
