import { writeFileSync } from "node:fs";
import { resolve } from "node:path";

import { bumpVersion, validateVersion } from "./bump-version-logic";

const PACKAGE_JSON_PATH = resolve(import.meta.dir, "..", "package.json");

async function main() {
  const args = process.argv.slice(2);
  if (args.length === 0) {
    console.error("Usage: bun run bump-version.ts <patch|minor|major|set> [version]");
    process.exit(1);
  }

  const command = args[0];
  if (command !== "patch" && command !== "minor" && command !== "major" && command !== "set") {
    console.error(`Unknown command: ${command}. Expected patch, minor, major, or set`);
    process.exit(1);
  }

  if (command === "set" && args.length < 2) {
    console.error("Usage: bun run bump-version.ts set <version>");
    process.exit(1);
  }

  const packageJson = (await Bun.file(PACKAGE_JSON_PATH).json()) as { version: string };
  const currentVersion = packageJson.version;

  if (typeof currentVersion !== "string") {
    console.error("package.json does not have a valid version field");
    process.exit(1);
  }

  validateVersion(currentVersion);

  const targetVersion = command === "set" ? args[1] : undefined;
  const nextVersion = bumpVersion(currentVersion, command, targetVersion);

  packageJson.version = nextVersion;
  writeFileSync(PACKAGE_JSON_PATH, JSON.stringify(packageJson, null, 2) + "\n");

  console.log(`${currentVersion} -> ${nextVersion}`);
}

void main();
