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

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.join(__dirname, "..");
const incoming = path.join(root, "public/images/icons/_incoming_settings");
const iconsDir = path.join(root, "public/images/icons");

function findSvg(folderKeyword, fileName) {
  const dirs = fs.readdirSync(incoming, { withFileTypes: true });
  const match = dirs.find((d) => d.isDirectory() && d.name.includes(folderKeyword));
  if (!match) {
    console.warn(`Folder not found for: ${folderKeyword}`);
    return null;
  }
  const p = path.join(incoming, match.name, "vuesax", "bold", fileName);
  return fs.existsSync(p) ? p : null;
}

function normalizeSvg(content, fill = "#292D32") {
  return content
    .replace(/#292D32/gi, fill)
    .replace(/fill="#9A9A9A"/gi, `fill="${fill}"`)
    .replace(/stroke="#9A9A9A"/gi, `stroke="${fill}"`);
}

function copyFrom(src, destName, fill) {
  if (!src) return false;
  const content = normalizeSvg(fs.readFileSync(src, "utf8"), fill);
  fs.writeFileSync(path.join(iconsDir, destName), content, "utf8");
  return true;
}

const jobs = [
  ["اشتراک", "share.svg", "share.svg"],
  ["seting", "setting.svg", "edit.svg"],
  ["درباره", "info-circle.svg", "contact.svg"],
  ["verify", "verify.svg", "verify.svg"],
  ["verify", "verify.svg", "verify2.svg"],
  ["verify", "verify.svg", "verify3.svg"],
  ["like", "heart.svg", "heart.svg"],
  ["like", "heart.svg", "red-heart.svg", "#EF4444"],
  ["درخواست", "document-normal.svg", "offer.svg"],
  ["عمکاری", "link-square.svg", "link-square.svg"],
  ["عمکاری", "link-square.svg", "celo-(celo).svg"],
  ["تاریک", "moon.svg", "moon.svg"],
  ["روشن", "sun.svg", "sun.svg"],
  ["احراز", "user-square.svg", "user-square.svg"],
  ["بیلبورد", "flash-circle.svg", "flash-circle.svg"],
  ["شبا", "user-tick.svg", "user-tick.svg"],
  ["تخصص", "instagram.svg", "instagram.svg"],
  ["کامنت", "message-text.svg", "message-text.svg"],
];

let n = 0;
for (const [folder, file, dest, fill] of jobs) {
  const src = findSvg(folder, file);
  if (copyFrom(src, dest, fill || "#292D32")) {
    n++;
    console.log(`OK ${dest}`);
  }
}

fs.rmSync(incoming, { recursive: true, force: true });
console.log(`Applied ${n} icon files.`);
