#!/usr/bin/env node
import fs from 'fs';
import path from 'path';

const repoRoot = process.cwd();

function readJson(p) {
  return JSON.parse(fs.readFileSync(p, 'utf8'));
}

function writeJson(p, obj) {
  fs.writeFileSync(p, JSON.stringify(obj, null, 2) + '\n', 'utf8');
}

function updateCargoTomlVersion(cargoTomlPath, version) {
  const input = fs.readFileSync(cargoTomlPath, 'utf8');

  // Replace only the [package] version line.
  const packageBlockStart = input.indexOf('[package]');
  if (packageBlockStart === -1) {
    throw new Error('Could not find [package] in Cargo.toml');
  }

  const packageBlockEnd = input.indexOf('\n[', packageBlockStart + 1);
  const blockEnd = packageBlockEnd === -1 ? input.length : packageBlockEnd;
  const pkgBlock = input.slice(packageBlockStart, blockEnd);

  const versionRe = /^version\s*=\s*"([^"]*)"/m;
  const m = pkgBlock.match(versionRe);
  if (!m) {
    throw new Error('Could not find version line in Cargo.toml [package] block');
  }

  const replaced = pkgBlock.replace(versionRe, `version = "${version}"`);

  const output = input.slice(0, packageBlockStart) + replaced + input.slice(blockEnd);
  fs.writeFileSync(cargoTomlPath, output, 'utf8');
}

try {
  const rootPkgPath = path.join(repoRoot, 'package.json');
  const tauriConfPath = path.join(repoRoot, 'src-tauri', 'tauri.conf.json');
  const cargoTomlPath = path.join(repoRoot, 'src-tauri', 'Cargo.toml');

  const rootPkg = readJson(rootPkgPath);
  if (!rootPkg.version) throw new Error('Root package.json has no version');

  const version = String(rootPkg.version);

  const tauriConf = readJson(tauriConfPath);
  tauriConf.version = version;
  writeJson(tauriConfPath, tauriConf);

  updateCargoTomlVersion(cargoTomlPath, version);

  console.log(`Synced Tauri version to ${version}`);
} catch (e) {
  console.error('sync-version failed:', e?.message || e);
  process.exit(1);
}
