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

const rootDir = path.resolve(__dirname, "./"); // 请替换为你的项目根目录

function walk(dir, callback) {
  fs.readdirSync(dir).forEach((f) => {
    const dirPath = path.join(dir, f);
    const isDirectory = fs.statSync(dirPath).isDirectory();
    isDirectory ? walk(dirPath, callback) : callback(path.join(dir, f));
  });
}

function convertImportToUse(content, filePath) {
  // 匹配 @import "xxx"; 或 @import 'xxx';
  return content.replace(/@import\s+["']([^"']+)["'];/g, (match, importPath) => {
    // 如果是 CSS 文件（例如 @import 'element-plus/dist/index.css'），不替换
    if (importPath.endsWith('.css')) return match;

    // vue 文件中 style 标签内容需保留缩进，稍微兼容
    const indent = match.match(/^\s*/)?.[0] ?? '';
    return `${indent}@use "${importPath}" as *;`;
  });
}

walk(rootDir, (filePath) => {
  if (filePath.endsWith(".scss") || filePath.endsWith(".vue")) {
    const content = fs.readFileSync(filePath, "utf8");
    if (content.includes("@import")) {
      const newContent = convertImportToUse(content, filePath);
      if (newContent !== content) {
        fs.writeFileSync(filePath, newContent, "utf8");
        console.log("✔ Converted:", filePath);
      }
    }
  }
});
