#!/usr/bin/env bun
/**
 * Bump the version of all @shade/* packages in lockstep.
 *
 * Usage:
 *   bun run scripts/bump-version.ts 1.1.0
 */
import { readFileSync, writeFileSync, readdirSync, statSync } from 'fs';
import { join } from 'path';

const ROOT = join(import.meta.dir, '..');
const PACKAGES_DIR = join(ROOT, 'packages');

const newVersion = process.argv[2];
if (!newVersion || !/^\d+\.\d+\.\d+(?:-[a-z0-9.]+)?$/.test(newVersion)) {
  console.error('Usage: bun run scripts/bump-version.ts <version>');
  console.error('Example: bun run scripts/bump-version.ts 1.1.0');
  process.exit(1);
}

const packages = readdirSync(PACKAGES_DIR).filter((name) => {
  return statSync(join(PACKAGES_DIR, name)).isDirectory();
});

let updated = 0;
for (const pkg of packages) {
  const pkgPath = join(PACKAGES_DIR, pkg, 'package.json');
  try {
    const pkgJson = JSON.parse(readFileSync(pkgPath, 'utf-8'));
    pkgJson.version = newVersion;
    writeFileSync(pkgPath, JSON.stringify(pkgJson, null, 2) + '\n');
    console.log(`  ${pkgJson.name} → ${newVersion}`);
    updated++;
  } catch (err) {
    console.error(`  ✗ ${pkg}: ${(err as Error).message}`);
  }
}

console.log(`\nUpdated ${updated} packages to ${newVersion}`);
console.log(`Next: git commit -am "chore: bump to ${newVersion}" && git tag v${newVersion} && git push --tags`);
