// src/add.ts
import fs from "fs-extra";
import path from "path";
import chalk from "chalk";
var BASE_DIR = path.join(process.cwd(), "public", "stackscan");
async function add(sourcePath) {
  let absoluteSourcePath = path.resolve(sourcePath);
  if (!fs.existsSync(absoluteSourcePath)) {
    console.error(chalk.red(`\u274C Path not found: ${sourcePath}`));
    process.exit(1);
  }
  if (fs.statSync(absoluteSourcePath).isDirectory()) {
    absoluteSourcePath = path.join(absoluteSourcePath, "package.json");
    if (!fs.existsSync(absoluteSourcePath)) {
      console.error(chalk.red(`\u274C No package.json found in directory: ${sourcePath}`));
      process.exit(1);
    }
  }
  try {
    const content = fs.readFileSync(absoluteSourcePath, "utf-8");
    const pkg = JSON.parse(content);
    if (!pkg.name) {
      console.error(chalk.red(`\u274C No "name" field found in ${sourcePath}`));
      process.exit(1);
    }
    const baseFolderName = pkg.name.replace(/^@/, "").replace(/\//g, "-");
    let folderName = baseFolderName;
    let targetDir = path.join(BASE_DIR, folderName);
    let counter = 1;
    while (fs.existsSync(targetDir)) {
      folderName = `${baseFolderName}-${counter}`;
      targetDir = path.join(BASE_DIR, folderName);
      counter++;
    }
    const targetFile = path.join(targetDir, "package.json");
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }
    fs.copyFileSync(absoluteSourcePath, targetFile);
    console.log(chalk.green(`\u2705 Added project "${pkg.name}" to public/stackscan/${folderName}`));
  } catch (error) {
    console.error(chalk.red(`\u274C Error processing ${sourcePath}:`), error);
    process.exit(1);
  }
}

export {
  add
};
