// src/output.ts
import fs from "fs-extra";
import path from "path";
import chalk from "chalk";
async function writeOutput(outPath, techs, config, format = "json") {
  const outDirectory = path.dirname(outPath);
  await fs.ensureDir(outDirectory);
  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 mdContent = generateMarkdown(techs);
    const mdPath = outPath.endsWith(".json") ? outPath.replace(/\.json$/, ".md") : outPath;
    await fs.writeFile(mdPath, mdContent);
    console.log(chalk.blue(`\u2192 Saved markdown to ${mdPath}`));
  }
}
function generateMarkdown(techs) {
  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]) {
      md += `- **${t.name}**
`;
    }
    md += "\n";
  }
  return md;
}

export {
  writeOutput
};
