const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const { execSync } = require("child_process");
const CleanCSS = require("clean-css");
const { CSS_DIR, SITE_CSS_FILES } = require("./site-css-sources.js");

const ROOT = path.join(__dirname, "..");
const OUT_FILE = path.join(CSS_DIR, "site.bundle.css");
const INDEX_FILE = path.join(ROOT, "index.html");
const BUNDLE_LINK_RE = /href="css\/site\.bundle\.css\?v=[^"]+"/;

function runTailwind() {
  execSync(
    "npx tailwindcss -i ./src/tailwind.css -o ./css/app.css --minify",
    { cwd: ROOT, stdio: "inherit" },
  );
  fs.copyFileSync(path.join(ROOT, "src/theme-light.css"), path.join(CSS_DIR, "theme-light.css"));
  fs.copyFileSync(path.join(ROOT, "src/theme-dark.css"), path.join(CSS_DIR, "theme-dark.css"));
}

function expandImports(content, baseDir) {
  return content.replace(
    /@import\s+url\s*\(\s*["']?(\.\/?[^"')]+)["']?\s*\)\s*;?/g,
    (_, rel) => {
      const imported = path.resolve(baseDir, rel.replace(/^\.\//, ""));
      if (!fs.existsSync(imported)) return "";
      const inner = fs.readFileSync(imported, "utf8");
      return expandImports(inner, path.dirname(imported));
    },
  );
}

function readSources() {
  const missing = [];
  const chunks = SITE_CSS_FILES.map((file) => {
    const fullPath = path.join(CSS_DIR, file);
    if (!fs.existsSync(fullPath)) {
      missing.push(file);
      return null;
    }
    const raw = fs.readFileSync(fullPath, "utf8");
    return expandImports(raw, CSS_DIR);
  }).filter(Boolean);

  if (missing.length) {
    throw new Error(`Eksik CSS dosyası: ${missing.join(", ")}`);
  }
  return chunks.join("\n");
}

async function buildBundle() {
  runTailwind();

  const combined = readSources();
  const result = await new CleanCSS({
    level: 2,
    returnPromise: true,
  }).minify(combined);

  if (result.errors?.length) {
    throw new Error(result.errors.join("\n"));
  }

  const css = result.styles;
  const hash = crypto.createHash("sha256").update(css).digest("hex").slice(0, 10);

  fs.writeFileSync(OUT_FILE, css, "utf8");
  patchIndexHtml(hash);

  const kb = (Buffer.byteLength(css, "utf8") / 1024).toFixed(1);
  console.log(`site.bundle.css → ${kb} KB (${SITE_CSS_FILES.length} kaynak, v=${hash})`);
}

function patchIndexHtml(hash) {
  if (!fs.existsSync(INDEX_FILE)) return;
  const html = fs.readFileSync(INDEX_FILE, "utf8");
  const next = html.replace(
    BUNDLE_LINK_RE,
    `href="css/site.bundle.css?v=${hash}"`,
  );
  if (next === html) {
    console.warn("index.html bundle link güncellenemedi — href kontrol et.");
    return;
  }
  fs.writeFileSync(INDEX_FILE, next, "utf8");
}

buildBundle().catch((err) => {
  console.error(err.message || err);
  process.exit(1);
});
