import {
  DEFAULT_CATEGORY_ICONS
} from "./chunk-NGEKE4DQ.mjs";
import {
  simple_icons_hex_default
} from "./chunk-7TIXAYVC.mjs";
import {
  __dirname
} from "./chunk-EOKQCSHI.mjs";

// src/output.ts
import fs from "fs-extra";
import path from "path";
import chalk from "chalk";
import { createRequire } from "module";
var require2 = createRequire(import.meta.url);
async function writeOutput(outPath, techs, config, format = "json", assetsOutPath) {
  const outDirectory = path.dirname(outPath);
  await fs.ensureDir(outDirectory);
  let availableLogos = /* @__PURE__ */ new Set();
  if (assetsOutPath) {
    availableLogos = await copyAssets(techs, assetsOutPath, config);
  }
  if (format === "json") {
    await fs.writeJSON(
      outPath,
      {
        generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
        tech: techs
      },
      { spaces: 2 }
    );
    console.log(chalk.blue(`\u2192 Saved ${techs.length} tech entries to ${outPath}`));
  } else if (format === "markdown") {
    const relativeAssetsPath = assetsOutPath ? path.relative(outDirectory, assetsOutPath).replace(/\\/g, "/") : void 0;
    const mdContent = generateMarkdown(techs, relativeAssetsPath, availableLogos);
    const mdPath = outPath.endsWith(".json") ? outPath.replace(/\.json$/, ".md") : outPath;
    await fs.writeFile(mdPath, mdContent);
    console.log(chalk.blue(`\u2192 Saved markdown to ${mdPath}`));
  }
}
async function copyAssets(techs, dest, config) {
  const srcDir = path.resolve(__dirname, "../assets/logos");
  let lucideDir;
  try {
    lucideDir = path.join(path.dirname(require2.resolve("lucide-static/package.json")), "icons");
  } catch (e) {
    lucideDir = path.resolve(__dirname, "../node_modules/lucide-static/icons");
  }
  const copied = /* @__PURE__ */ new Set();
  let count = 0;
  for (const t of techs) {
    let srcFile = t.logo ? path.join(srcDir, t.logo) : null;
    let destFile = t.logo ? path.join(dest, t.logo) : null;
    let isDefault = false;
    if (!srcFile || !await fs.pathExists(srcFile)) {
      const defaultIconName = DEFAULT_CATEGORY_ICONS[t.type];
      if (defaultIconName) {
        const lucideFile = path.join(lucideDir, `${defaultIconName}.svg`);
        if (await fs.pathExists(lucideFile)) {
          srcFile = lucideFile;
          const newLogoPath = `defaults/${defaultIconName}.svg`;
          destFile = path.join(dest, newLogoPath);
          t.logo = newLogoPath;
          isDefault = true;
        }
      }
    }
    if (srcFile && destFile && await fs.pathExists(srcFile)) {
      await fs.ensureDir(path.dirname(destFile));
      let svgContent = await fs.readFile(srcFile, "utf8");
      let color;
      if (config.iconColors && config.iconColors[t.name]) {
        color = config.iconColors[t.name];
      } else if (config.colorMode === "white") {
        color = "#FFFFFF";
      } else if (config.colorMode === "black") {
        color = "#000000";
      } else if (config.colorMode === "custom" && config.customColor) {
        color = config.customColor;
      } else if (config.colorMode === "default" || !config.colorMode) {
        if (!isDefault) {
          const slug = path.basename(t.logo, ".svg");
          const brandHex = simple_icons_hex_default[slug];
          if (brandHex) {
            color = `#${brandHex}`;
          }
        }
      }
      if (color) {
        if (isDefault) {
          if (svgContent.includes("stroke=")) {
            svgContent = svgContent.replace(/stroke="[^"]*"/g, `stroke="${color}"`);
          } else {
            svgContent = svgContent.replace("<svg", `<svg stroke="${color}"`);
          }
        } else {
          if (svgContent.includes("fill=")) {
            svgContent = svgContent.replace(/fill="[^"]*"/g, `fill="${color}"`);
          } else {
            svgContent = svgContent.replace("<svg", `<svg fill="${color}"`);
          }
        }
      }
      await fs.writeFile(destFile, svgContent);
      copied.add(t.logo);
      if (!isDefault) count++;
    } else {
    }
  }
  if (count > 0) {
    console.log(chalk.blue(`\u2192 Copied ${count} logos to ${dest}`));
  }
  return copied;
}
function generateMarkdown(techs, assetsPath, availableLogos) {
  const grouped = {};
  for (const t of techs) {
    const type = t.type || "misc";
    if (!grouped[type]) grouped[type] = [];
    grouped[type].push(t);
  }
  let md = "# Tech Stack\n\n";
  const order = [
    "language",
    "frontend",
    "backend",
    "framework",
    "library",
    "database",
    "orm",
    "auth",
    "api",
    "cloud",
    "hosting",
    "ci",
    "devops",
    "container",
    "testing",
    "build",
    "tooling",
    "misc"
  ];
  const sortedKeys = Object.keys(grouped).sort((a, b) => {
    const idxA = order.indexOf(a);
    const idxB = order.indexOf(b);
    if (idxA === -1 && idxB === -1) return a.localeCompare(b);
    if (idxA === -1) return 1;
    if (idxB === -1) return -1;
    return idxA - idxB;
  });
  for (const type of sortedKeys) {
    const title = type.charAt(0).toUpperCase() + type.slice(1);
    md += `## ${title}

`;
    for (const t of grouped[type]) {
      if (assetsPath && t.logo && availableLogos?.has(t.logo)) {
        const logoUrl = `${assetsPath}/${t.logo}`;
        md += `- <img src="${logoUrl}" alt="${t.name}" width="24" height="24" /> **${t.name}**
`;
      } else {
        md += `- **${t.name}**
`;
      }
    }
    md += "\n";
  }
  return md;
}

export {
  writeOutput
};
