/**
 * AntDv4 兼容：替换 ele-admin-pro Less 中的 colorPalette JS 调用
 * AntDv4 移除了 Less 的 colorPalette 函数，此脚本在 postinstall 时
 * 将 common.less 中的 ~`colorPalette(...)` 替换为实际颜色值。
 */
const fs = require('fs');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');

// 尝试多个可能的位置（pnpm 的 .pnpm store 和直接链接）
const possiblePaths = [
  path.join(rootDir, 'node_modules/ele-admin-pro/es/style/common.less'),
  path.join(rootDir, 'node_modules/.pnpm/node_modules/ele-admin-pro/es/style/common.less'),
];

// 也搜索 .pnpm 目录下的实际路径
const pnpmDir = path.join(rootDir, 'node_modules/.pnpm');
if (fs.existsSync(pnpmDir)) {
  const entries = fs.readdirSync(pnpmDir).filter(e => e.startsWith('ele-admin-pro'));
  for (const entry of entries) {
    possiblePaths.push(path.join(pnpmDir, entry, 'node_modules/ele-admin-pro/es/style/common.less'));
  }
}

let filePath = null;
for (const p of possiblePaths) {
  if (fs.existsSync(p)) {
    filePath = p;
    break;
  }
}

if (!fs.existsSync(filePath)) {
  console.log('[antd4-compat] common.less not found, skipping');
  process.exit(0);
}

let content = fs.readFileSync(filePath, 'utf8');
const original = content;

const primaryColors = { 1: '#e6f4ff', 2: '#bae0ff', 3: '#91caff', 4: '#69b1ff', 5: '#4096ff', 6: '#1677ff', 7: '#0958d9', 8: '#003eb3', 9: '#002c8c', 10: '#001d66' };
const successColors = { 1: '#f6ffed', 2: '#d9f7be', 3: '#b7eb8f', 4: '#95de64', 5: '#73d13d', 6: '#52c41a', 7: '#389e0d', 8: '#237804', 9: '#135200', 10: '#092b00' };
const warningColors = { 1: '#fffbe6', 2: '#fff1b8', 3: '#ffe58f', 4: '#ffd666', 5: '#ffc53d', 6: '#faad14', 7: '#d48806', 8: '#ad6800', 9: '#874d00', 10: '#612500' };
const errorColors = { 1: '#fff2f0', 2: '#ffccc7', 3: '#ffa39e', 4: '#ff7875', 5: '#ff4d4f', 6: '#f5222d', 7: '#cf1322', 8: '#a8071a', 9: '#820014', 10: '#5c0011' };

content = content.replace(/~`colorPalette\('@\{primary-color\}',\s*(\d+)\)\s*`/g, (m, idx) => primaryColors[idx] || '#1677ff');
content = content.replace(/~`colorPalette\('@\{success-color\}',\s*(\d+)\)\s*`/g, (m, idx) => successColors[idx] || '#52c41a');
content = content.replace(/~`colorPalette\('@\{warning-color\}',\s*(\d+)\)\s*`/g, (m, idx) => warningColors[idx] || '#faad14');
content = content.replace(/~`colorPalette\('@\{error-color\}',\s*(\d+)\)\s*`/g, (m, idx) => errorColors[idx] || '#ff4d4f');

if (content !== original) {
  fs.writeFileSync(filePath, content);
  console.log('[antd4-compat] Replaced colorPalette calls in common.less');
} else {
  console.log('[antd4-compat] No colorPalette calls found, skipping');
}
