import { execSync } from "node:child_process";
import { exists, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, parse } from "node:path";
import { JSDOM } from "jsdom";
import { optimize } from "svgo";

if (!Bun.which("picosvg")) {
    console.error(
        "🚨 picosvg is not installed. Please install it: https://github.com/googlefonts/picosvg",
    );
    process.exit(1);
}

if (!(await exists("icons.zip"))) {
    console.error("🚨 icons.zip is not found. Please place it in the root of the project");
    process.exit(2);
}

const iconsDir = await mkdtemp(join(tmpdir(), "icons-"));
const interDir = await mkdtemp(join(tmpdir(), "inter-"));

// Unzip the icons.zip file
try {
    execSync(`unzip icons.zip -d "${iconsDir}"`);
} catch (error) {
    console.error("Error unzipping icons.zip:", error.message);
}

// Read all SVG files in the icons directory
const files = (await readdir(iconsDir)).filter((file) => file.endsWith(".svg")).sort();

let bundleCode = "// Generated by SurrealDB UI Kit. Do not modify manually.\n\n";
let pureCode = "// Generated by SurrealDB UI Kit. Do not modify manually.\n\n";

for (const file of files) {
    const inputPath = join(iconsDir, file);
    const outputPath = join(interDir, file);
    execSync(`picosvg "${inputPath}" --output_file "${outputPath}"`);

    const { name } = parse(file);
    const svg = await readFile(outputPath, "utf8");
    const optimized = optimize(svg, {
        multipass: true,
        plugins: [
            {
                name: "mergePaths",
                params: {
                    force: true,
                    noSpaceAfterFlags: false,
                },
            },
        ],
    }).data;

    const dom = new JSDOM(optimized);
    const paths = dom.window.document.querySelectorAll("path");

    if (paths.length !== 1) {
        throw new Error(`Icon ${name} has ${paths.length} paths, expected 1`);
    }

    const iconPath = paths[0].getAttribute("d");

    bundleCode += `export const icon${name}: string = "${iconPath}";\n`;
    pureCode += `export { icon${name} as ${name} } from "./icons";\n`;

    console.log(`🔄 Converted ${name}`);
}

await writeFile("./src/constants/icons.ts", bundleCode);
await writeFile("./src/constants/icons-pure.ts", pureCode);

console.log("✅ Updated icons.ts and icons-pure.ts!");

await rm(iconsDir, { recursive: true });
await rm(interDir, { recursive: true });
