#!/usr/bin/env node
/**
 * Sync version from package.json to tauri.conf.json and Cargo.toml.
 * Called automatically by npm's `version` lifecycle hook so that
 * `np` (or `npm version`) keeps all version files in sync.
 */

const fs = require('fs');
const path = require('path');

const root = path.resolve(__dirname, '..');
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const version = pkg.version;

if (!version) {
  console.error('No version found in package.json');
  process.exit(1);
}

// Update tauri.conf.json — targeted version-line replace so the file's existing
// formatting (e.g. inline short arrays) is preserved. A JSON.parse/stringify
// round-trip would reformat the whole file and produce noisy release diffs.
const tauriConfPath = path.join(root, 'src-tauri', 'tauri.conf.json');
let tauriConf = fs.readFileSync(tauriConfPath, 'utf8');
tauriConf = tauriConf.replace(/^(\s*"version":\s*)"[^"]*"/m, `$1"${version}"`);
// Sanity check: still valid JSON and the version actually took.
if (JSON.parse(tauriConf).version !== version) {
  console.error('Failed to set version in tauri.conf.json');
  process.exit(1);
}
fs.writeFileSync(tauriConfPath, tauriConf);

// Update Cargo.toml (first version = line under [package])
const cargoPath = path.join(root, 'src-tauri', 'Cargo.toml');
let cargo = fs.readFileSync(cargoPath, 'utf8');
const crateName = (cargo.match(/^name = "(.+)"$/m) || [])[1] || 'forwardemail-desktop';
cargo = cargo.replace(/^version = ".*"$/m, `version = "${version}"`);
fs.writeFileSync(cargoPath, cargo);

// Update Cargo.lock so the crate's own [[package]] entry stays in lockstep —
// otherwise `cargo build --locked` (CI desktop builds) fails on a version
// mismatch. Only touch this crate's entry, identified by its name.
const cargoLockPath = path.join(root, 'src-tauri', 'Cargo.lock');
if (fs.existsSync(cargoLockPath)) {
  let lock = fs.readFileSync(cargoLockPath, 'utf8');
  const lockRe = new RegExp(`(name = "${crateName}"\\nversion = )"[^"]*"`);
  if (lockRe.test(lock)) {
    lock = lock.replace(lockRe, `$1"${version}"`);
    fs.writeFileSync(cargoLockPath, lock);
  }
}

// Update Android tauri.properties (versionName + versionCode)
const tauriPropsPath = path.join(root, 'src-tauri', 'gen', 'android', 'app', 'tauri.properties');
if (fs.existsSync(tauriPropsPath)) {
  // versionCode must be an integer that increments with each release.
  // Derive it from semver: major*10000 + minor*100 + patch
  const [major, minor, patch] = version.split('.').map(Number);
  const versionCode = major * 10000 + minor * 100 + patch;
  const props = [
    '// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.',
    `tauri.android.versionName=${version}`,
    `tauri.android.versionCode=${versionCode}`,
    '',
  ].join('\n');
  fs.writeFileSync(tauriPropsPath, props);
  console.log(
    `Synced version ${version} → tauri.conf.json, Cargo.toml, Cargo.lock, tauri.properties (versionCode=${versionCode})`,
  );
} else {
  console.log(
    `Synced version ${version} → tauri.conf.json, Cargo.toml, Cargo.lock (tauri.properties not found, skipping)`,
  );
}
