import { build } from "esbuild";
import { copyFileSync, mkdirSync, readdirSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// File extensions to copy
const IMAGE_EXTENSIONS = [".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"];
const DATA_EXTENSIONS = [".json"];

// Recursively copy image files from src to dist
function copyImages(srcDir, distDir) {
  const entries = readdirSync(srcDir, { withFileTypes: true });

  for (const entry of entries) {
    const srcPath = join(srcDir, entry.name);
    const distPath = join(distDir, entry.name);

    if (entry.isDirectory()) {
      mkdirSync(distPath, { recursive: true });
      copyImages(srcPath, distPath);
    } else if (entry.isFile()) {
      const lastDot = entry.name.lastIndexOf(".");
      if (lastDot !== -1) {
        const ext = entry.name.toLowerCase().substring(lastDot);
        if (IMAGE_EXTENSIONS.includes(ext)) {
          mkdirSync(distDir, { recursive: true });
          copyFileSync(srcPath, distPath);
        }
      }
    }
  }
}

// Recursively copy data files (JSON, markdown, TypeScript definitions) from assets to dist
function copyAssets(srcDir, distDir) {
  const entries = readdirSync(srcDir, { withFileTypes: true });

  for (const entry of entries) {
    const srcPath = join(srcDir, entry.name);
    const distPath = join(distDir, entry.name);

    if (entry.isDirectory()) {
      mkdirSync(distPath, { recursive: true });
      copyAssets(srcPath, distPath);
    } else if (entry.isFile()) {
      const lastDot = entry.name.lastIndexOf(".");
      if (lastDot !== -1) {
        const ext = entry.name.toLowerCase().substring(lastDot);
        if (DATA_EXTENSIONS.includes(ext)) {
          mkdirSync(distDir, { recursive: true });
          copyFileSync(srcPath, distPath);
        }
      }
    }
  }
}

// Ensure dist directory exists
mkdirSync("dist", { recursive: true });

// Build JavaScript
await build({
  entryPoints: ["src/index.js"],
  bundle: true,
  splitting: true,
  format: "esm",
  outdir: "dist",
  sourcemap: true,
  platform: "browser",
});

// Copy HTML file
copyFileSync("src/index.html", "dist/index.html");

// Copy images
copyImages("src", "dist");

// Copy assets (JSON, markdown, TypeScript definitions)
copyAssets("src/assets", "dist/assets");

console.log("Build complete!");
