#!/usr/bin/env node

/**
 * 版本管理脚本 - 同步更新 Cargo.toml 和 package.json 的版本号
 */

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

function updateCargoToml(newVersion) {
  const cargoPath = path.join(__dirname, '..', 'Cargo.toml');
  let content = fs.readFileSync(cargoPath, 'utf8');
  
  content = content.replace(
    /^version = ".*"$/m,
    `version = "${newVersion}"`
  );
  
  fs.writeFileSync(cargoPath, content);
  console.log(`✅ Updated Cargo.toml to version ${newVersion}`);
}

function updatePackageJson(newVersion) {
  const packagePath = path.join(__dirname, '..', 'package.json');
  const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
  
  pkg.version = newVersion;
  
  fs.writeFileSync(packagePath, JSON.stringify(pkg, null, 2) + '\n');
  console.log(`✅ Updated package.json to version ${newVersion}`);
}

function validateVersion(version) {
  const semverRegex = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
  return semverRegex.test(version);
}

function getCurrentVersion() {
  const packagePath = path.join(__dirname, '..', 'package.json');
  const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
  return pkg.version;
}

function bumpVersion(type) {
  const currentVersion = getCurrentVersion();
  const [major, minor, patch] = currentVersion.split('.').map(Number);
  
  switch (type) {
    case 'major':
      return `${major + 1}.0.0`;
    case 'minor':
      return `${major}.${minor + 1}.0`;
    case 'patch':
      return `${major}.${minor}.${patch + 1}`;
    default:
      throw new Error(`Invalid bump type: ${type}. Use 'major', 'minor', or 'patch'`);
  }
}

function createGitTag(version) {
  try {
    execSync(`git add Cargo.toml package.json`);
    execSync(`git commit -m "chore: bump version to ${version}"`);
    execSync(`git tag -a v${version} -m "Release version ${version}"`);
    console.log(`✅ Created git tag v${version}`);
    console.log(`💡 Push with: git push origin main --tags`);
  } catch (error) {
    console.error('❌ Failed to create git tag:', error.message);
  }
}

function main() {
  const args = process.argv.slice(2);
  
  if (args.length === 0) {
    console.log(`
📦 Version Management Script

Usage:
  node scripts/bump-version.js <version|type> [--tag]

Examples:
  node scripts/bump-version.js 1.2.3        # Set specific version
  node scripts/bump-version.js patch        # Bump patch version
  node scripts/bump-version.js minor        # Bump minor version  
  node scripts/bump-version.js major        # Bump major version
  node scripts/bump-version.js patch --tag  # Bump and create git tag

Current version: ${getCurrentVersion()}
`);
    process.exit(0);
  }
  
  const versionArg = args[0];
  const shouldTag = args.includes('--tag');
  
  let newVersion;
  
  if (validateVersion(versionArg)) {
    // 用户提供了具体版本号
    newVersion = versionArg;
  } else if (['major', 'minor', 'patch'].includes(versionArg)) {
    // 用户提供了版本类型
    newVersion = bumpVersion(versionArg);
  } else {
    console.error(`❌ Invalid version or bump type: ${versionArg}`);
    process.exit(1);
  }
  
  console.log(`🚀 Updating version from ${getCurrentVersion()} to ${newVersion}`);
  
  try {
    updateCargoToml(newVersion);
    updatePackageJson(newVersion);
    
    if (shouldTag) {
      createGitTag(newVersion);
    }
    
    console.log(`\n🎉 Successfully updated version to ${newVersion}`);
    
    if (!shouldTag) {
      console.log(`💡 To create a git tag, run: node scripts/bump-version.js ${newVersion} --tag`);
    }
    
  } catch (error) {
    console.error('❌ Failed to update version:', error.message);
    process.exit(1);
  }
}

if (require.main === module) {
  main();
}

module.exports = { updateCargoToml, updatePackageJson, validateVersion, bumpVersion };