#!/usr/bin/env node
// bump-version.mjs — Update version across all manifest files
// Usage: npm run bump -- 2.2.0
//    or: node scripts/bump-version.mjs 2.2.0

import { readFileSync, writeFileSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const newVersion = process.argv[2];

if (!newVersion || !/^\d+\.\d+\.\d+$/.test(newVersion)) {
  console.error('Usage: npm run bump -- <semver>');
  console.error('Example: npm run bump -- 2.2.0');
  process.exit(1);
}

// Read current version from package.json
const pkgPath = resolve(ROOT, 'package.json');
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
const oldVersion = pkg.version;

if (oldVersion === newVersion) {
  console.log(`Already at version ${newVersion}`);
  process.exit(0);
}

// Files that contain the version string
const targets = [
  { file: 'package.json', find: `"version": "${oldVersion}"`, replace: `"version": "${newVersion}"` },
  { file: '.claude-plugin/plugin.json', find: `"version": "${oldVersion}"`, replace: `"version": "${newVersion}"` },
  { file: 'README.md', find: `version-${oldVersion}-blue`, replace: `version-${newVersion}-blue` },
];

let updated = 0;

for (const { file, find, replace } of targets) {
  const filePath = resolve(ROOT, file);
  try {
    const content = readFileSync(filePath, 'utf8');
    if (content.includes(find)) {
      writeFileSync(filePath, content.replace(find, replace));
      console.log(`  Updated ${file}`);
      updated++;
    } else {
      console.warn(`  WARNING: ${file} does not contain "${find}"`);
    }
  } catch (err) {
    console.error(`  ERROR: Could not update ${file}: ${err.message}`);
    process.exit(1);
  }
}

console.log(`\nVersion bumped: ${oldVersion} → ${newVersion} (${updated} files updated)`);
console.log(`\nRemember to add a Version History entry in README.md`);
