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

// src/sync.ts
import fs from "fs";
import path from "path";
var INPUT_DIR = path.join(process.cwd(), "stacksync", "input");
var OUTPUT_DIR = path.join(process.cwd(), "stacksync", "output");
function toCamelCase(str) {
  return str.replace(/[^a-zA-Z0-9 ]/g, "").split(" ").map((word, index) => {
    if (index === 0) return word.toLowerCase();
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  }).join("");
}
async function sync(options = {}) {
  console.log("\u{1F680} Starting Sync...");
  if (options.color) {
    console.log(`\u{1F3A8} Color mode: ${options.color}`);
  }
  if (!fs.existsSync(INPUT_DIR)) {
    console.log(`Creating input directory at: ${INPUT_DIR}`);
    fs.mkdirSync(INPUT_DIR, { recursive: true });
    console.log('Please place your project folders inside "stacksync/input" and run this command again.');
    process.exit(0);
  }
  const entries = fs.readdirSync(INPUT_DIR, { withFileTypes: true });
  const projectDirs = entries.filter((dirent) => dirent.isDirectory());
  if (projectDirs.length === 0) {
    console.log('\u26A0\uFE0F  No project directories found in "stacksync/input".');
    return;
  }
  console.log(`Found ${projectDirs.length} projects to process.
`);
  const allProjects = [];
  const allTechs = [];
  for (const dir of projectDirs) {
    const projectPath = path.join(INPUT_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 (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: `https://raw.githubusercontent.com/benjamindotdev/stacksync/main/public/assets/logos/${tech.logo}`,
              relativePath: `public/assets/logos/${tech.logo}`,
              color
            });
          }
        });
        const uniqueTechs = Array.from(new Set(detectedTechs.map((t) => t.slug))).map((slug) => detectedTechs.find((t) => t.slug === slug));
        allTechs.push(...uniqueTechs);
        const outputFolderName = toCamelCase(dir.name);
        const projectOutputDir = path.join(OUTPUT_DIR, outputFolderName);
        if (!fs.existsSync(projectOutputDir)) {
          fs.mkdirSync(projectOutputDir, { recursive: true });
        }
        fs.writeFileSync(
          path.join(projectOutputDir, "stack.json"),
          JSON.stringify(uniqueTechs, null, 2)
        );
        const mdContent = generateMarkdown(uniqueTechs);
        fs.writeFileSync(path.join(projectOutputDir, "stack.md"), mdContent);
        allProjects.push({
          name: dir.name,
          techs: uniqueTechs
        });
        console.log(`\u2705 ${dir.name.padEnd(20)} -> ${outputFolderName}/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) {
    const assetsDir = path.join(process.cwd(), "assets", "logos");
    const uniqueAllTechs = Array.from(new Set(allTechs.map((t) => t.slug))).map((slug) => allTechs.find((t) => t.slug === slug));
    const techsForCopy = uniqueAllTechs.map((t) => ({
      ...t,
      logo: t.relativePath.replace("public/assets/logos/", "")
      // Restore "frameworks/react.svg"
    }));
    await copyAssets(techsForCopy, assetsDir, { colorMode: options.color });
    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
};
