const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");

// Get package name and version from package.json
function getPackageInfo() {
  const packageJsonPath = path.resolve(__dirname, "../", "package.json");
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
  return { name: packageJson.name, version: packageJson.version };
}

// Check if a Git tag already exists
function tagExists(tagName) {
  try {
    const tags = execSync("git tag", { encoding: "utf-8" }).split("\n");
    return tags.includes(tagName);
  } catch (error) {
    console.error("❌ Error checking tags", error);
    return false;
  }
}

// Run a shell command
function execCommand(command) {
  try {
    execSync(command, { stdio: "inherit" });
  } catch (error) {
    console.error(`❌ Error running: ${command}`, error);
    process.exit(1);
  }
}

// Get latest version of a dependency from npm
function getLatestVersion(pkgName) {
  try {
    return execSync(`npm show ${pkgName} version`).toString().trim();
  } catch (error) {
    console.error(`❌ Error fetching latest version for ${pkgName}`, error);
    process.exit(1);
  }
}

// Update package.json dependency with latest version
function updatePackageJson(depName, latestVersion) {
  const packageJsonPath = path.resolve(__dirname, "../", "package.json");
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));

  if (packageJson.dependencies && packageJson.dependencies[depName]) {
    packageJson.dependencies[depName] = `^${latestVersion}`;
  } else {
    console.error(`❌ Dependency ${depName} not found in package.json`);
    process.exit(1);
  }

  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
  console.log(`✅ Updated ${depName} to version ^${latestVersion} in package.json`);
}

module.exports = {
  getPackageInfo,
  tagExists,
  execCommand,
  getLatestVersion,
  updatePackageJson
};
