import {
  copyAssets,
  generateMarkdown
} from "./chunk-ZH22D4SN.mjs";
import {
  simple_icons_hex_default
} from "./chunk-EH2SEQZP.mjs";
import {
  techMap
} from "./chunk-LSUI3VI4.mjs";

// src/sync.ts
import fs from "fs";
import path from "path";
var BASE_DIR = path.join(process.cwd(), "stacksync");
var SKIPPED_TECHS = [
  "react-dom"
];
async function sync(options = {}) {
  console.log("\u{1F680} Starting Sync...");
  if (options.color) {
    console.log(`\u{1F3A8} Color mode: ${options.color}`);
  }
  if (!fs.existsSync(BASE_DIR)) {
    console.log(`Creating stacksync directory at: ${BASE_DIR}`);
    fs.mkdirSync(BASE_DIR, { recursive: true });
    console.log('Please place your project folders inside "stacksync/" and run this command again.');
    process.exit(0);
  }
  const entries = fs.readdirSync(BASE_DIR, { withFileTypes: true });
  const projectDirs = entries.filter((dirent) => dirent.isDirectory() && dirent.name !== "input" && dirent.name !== "output");
  if (projectDirs.length === 0) {
    console.log('\u26A0\uFE0F  No project directories found in "stacksync/".');
    return;
  }
  console.log(`Found ${projectDirs.length} projects to process.
`);
  const allProjects = [];
  const allTechs = [];
  for (const dir of projectDirs) {
    const projectPath = path.join(BASE_DIR, dir.name);
    const packageJsonPath = path.join(projectPath, "package.json");
    if (fs.existsSync(packageJsonPath)) {
      try {
        const content = fs.readFileSync(packageJsonPath, "utf-8");
        const pkg = JSON.parse(content);
        const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
        const detectedTechs = [];
        Object.keys(allDeps).forEach((dep) => {
          if (SKIPPED_TECHS.includes(dep)) return;
          if (techMap[dep]) {
            const tech = techMap[dep];
            let color = null;
            if (options.color === "white") color = "#FFFFFF";
            else if (options.color === "black") color = "#000000";
            else if (options.color && options.color.startsWith("#")) color = options.color;
            else {
              const depSlug = dep.toLowerCase();
              const nameSlug = tech.name.toLowerCase();
              const nameSlugNoSpaces = tech.name.toLowerCase().replace(/\s+/g, "");
              const hex = simple_icons_hex_default[depSlug] || simple_icons_hex_default[nameSlug] || simple_icons_hex_default[nameSlugNoSpaces];
              if (hex) color = `#${hex}`;
            }
            detectedTechs.push({
              name: tech.name,
              slug: dep,
              logo: tech.logo,
              // Raw path for resolution
              color
            });
          }
        });
        let uniqueTechs = Array.from(new Set(detectedTechs.map((t) => t.slug))).map((slug) => detectedTechs.find((t) => t.slug === slug));
        const seenLogos = /* @__PURE__ */ new Set();
        uniqueTechs = uniqueTechs.filter((t) => {
          if (seenLogos.has(t.logo)) {
            return false;
          }
          seenLogos.add(t.logo);
          return true;
        });
        const assetsDir = path.join(process.cwd(), "public", "assets", "logos");
        if (options.copyAssets !== false) {
          await copyAssets(uniqueTechs, assetsDir, { colorMode: options.color });
        }
        const techsWithUrls = uniqueTechs.map((t) => ({
          ...t,
          logo: `https://raw.githubusercontent.com/benjamindotdev/stacksync/main/public/assets/logos/${t.logo}`,
          relativePath: `./public/assets/logos/${t.logo}`
        }));
        allTechs.push(...techsWithUrls);
        fs.writeFileSync(
          path.join(projectPath, "stack.json"),
          JSON.stringify(techsWithUrls, null, 2)
        );
        const mdContent = generateMarkdown(techsWithUrls);
        fs.writeFileSync(path.join(projectPath, "stack.md"), mdContent);
        allProjects.push({
          name: dir.name,
          techs: techsWithUrls
        });
        console.log(`\u2705 ${dir.name.padEnd(20)} -> stack.json (${uniqueTechs.length} techs)`);
      } catch (err) {
        console.error(`\u274C Error processing ${dir.name}:`, err.message);
      }
    } else {
      console.warn(`\u26A0\uFE0F  Skipping "${dir.name}": No package.json found.`);
    }
  }
  if (allProjects.length > 0) {
    updateRootReadme(allProjects);
  }
  console.log("\n\u2728 Sync complete.");
}
function updateRootReadme(projects) {
  const readmePath = path.join(process.cwd(), "README.md");
  if (!fs.existsSync(readmePath)) {
    console.log("\u26A0\uFE0F  No root README.md found to update.");
    return;
  }
  let readmeContent = fs.readFileSync(readmePath, "utf-8");
  const startMarker = "<!-- STACKSYNC_START -->";
  const endMarker = "<!-- STACKSYNC_END -->";
  let newSection = `${startMarker}
## My Projects

`;
  for (const p of projects) {
    newSection += `### ${p.name}
`;
    newSection += `<p>
`;
    for (const t of p.techs) {
      const src = t.relativePath || t.logo;
      newSection += `  <img src="${src}" alt="${t.name}" height="25" style="margin-right: 10px;" />
`;
    }
    newSection += `</p>

`;
  }
  newSection += `${endMarker}`;
  if (readmeContent.includes(startMarker) && readmeContent.includes(endMarker)) {
    const regex = new RegExp(`${startMarker}[\\s\\S]*?${endMarker}`);
    readmeContent = readmeContent.replace(regex, newSection);
    console.log(`\u{1F4DD} Updated root README.md with ${projects.length} projects.`);
  } else {
    readmeContent += `

${newSection}`;
    console.log(`\u{1F4DD} Appended projects to root README.md.`);
  }
  fs.writeFileSync(readmePath, readmeContent);
}

export {
  sync
};
