const fs = require("fs")
const path = require("path")
const readline = require("readline")

// Get command-line arguments
const args = process.argv.slice(2)
const partIndex = args.findIndex(arg => arg === "-p" || arg === "--part")
const part =
  partIndex !== -1 && args[partIndex + 1] ?
    args[partIndex + 1].toLowerCase() :
    null

const packagePath = path.resolve(process.cwd(), "package.json")

try {
  // Read package.json file
  const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf8"))

  // Check if "version" field exists
  if (!packageJson.version) {
    throw new Error(
      'El archivo package.json no contiene una propiedad "version".'
    )
  }

  const [major, minor, patch] = packageJson.version.split(".").map(Number)

  // Function to update version
  const updateVersion = part => {
    let newVersion
    switch (part) {
      case "major":
        newVersion = `${major + 1}.0.0`
        break
      case "minor":
        newVersion = `${major}.${minor + 1}.0`
        break
      case "patch":
        newVersion = `${major}.${minor}.${patch + 1}`
        break
      default:
        console.error("Opción no válida. Usa: major, minor o patch.")
        process.exit(1)
    }

    // Update package.json
    packageJson.version = newVersion
    fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2), "utf8")

    console.log(`Versión actualizada: ${packageJson.version} -> ${newVersion}`)
  }

  if (part) {
    // If flag is provided, update immediately
    updateVersion(part)
  } else {
    // Otherwise, ask the user interactively
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    })

    rl.question(
      "¿Qué parte de la versión deseas incrementar? (major, minor, patch): ",
      answer => {
        updateVersion(answer.toLowerCase())
        rl.close()
      }
    )
  }
} catch (error) {
  console.error(`Error: ${error.message}`)
  process.exit(1)
}
