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

// 定义要替换的目录
const srcDir = path.join(__dirname, 'src');

// 定义要搜索的文件扩展名
const fileExtensions = ['.ts', '.html'];

// 替换 via.placeholder.com 链接的函数
function replacePlaceholderLinks(fileContent, filePath) {
  let modifiedContent = fileContent;
  let replacementCount = 0;

  // 正则表达式匹配 via.placeholder.com 链接
  const placeholderRegex = /https:\/\/via\.placeholder\.com\/(\d+)x(\d+)\/([0-9A-Fa-f]+)\/([0-9A-Fa-f]+)\?text=([^"']*)/g;

  // 替换匹配的链接
  modifiedContent = modifiedContent.replace(placeholderRegex, (match, width, height, bgColor, textColor, text) => {
    replacementCount++;
    
    // 根据文件类型和上下文决定返回什么
    if (filePath.endsWith('.html')) {
      // 对于HTML文件，返回一个带有内联样式的div作为占位图
      return `<div style="width: ${width}px; height: ${height}px; background-color: #${bgColor}; color: #${textColor}; display: flex; align-items: center; justify-content: center; font-size: ${Math.min(width, height) / 3}px; font-weight: bold;">${text}</div>`;
    } else if (filePath.endsWith('.ts')) {
      // 对于TypeScript文件，返回一个本地占位图配置对象
      return `{ width: ${width}, height: ${height}, bgColor: '#${bgColor}', textColor: '#${textColor}', text: '${text}' }`;
    }
    
    // 如果不是HTML或TS文件，保持原样
    return match;
  });

  return { modifiedContent, replacementCount };
}

// 遍历目录中的文件
function traverseDirectory(dir) {
  const files = fs.readdirSync(dir);
  let totalReplacements = 0;

  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      const subDirReplacements = traverseDirectory(filePath);
      totalReplacements += subDirReplacements;
    } else if (fileExtensions.some(ext => file.endsWith(ext))) {
      // 读取文件内容
      const fileContent = fs.readFileSync(filePath, 'utf8');
      
      // 替换 via.placeholder.com 链接
      const { modifiedContent, replacementCount } = replacePlaceholderLinks(fileContent, filePath);
      
      // 如果有替换，写入文件
      if (replacementCount > 0) {
        fs.writeFileSync(filePath, modifiedContent, 'utf8');
        console.log(`已替换 ${filePath} 中的 ${replacementCount} 个placeholder链接`);
        totalReplacements += replacementCount;
      }
    }
  });

  return totalReplacements;
}

// 执行替换操作
console.log('开始替换 via.placeholder.com 链接...');
const totalReplacements = traverseDirectory(srcDir);
console.log(`替换完成！总共替换了 ${totalReplacements} 个placeholder链接。`);