#!/bin/bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT_DIR"

TAURI_CONF="src-tauri/tauri.conf.json"
PKG_JSON="package.json"
CARGO_TOML="src-tauri/Cargo.toml"

if [ ! -f "$TAURI_CONF" ] || [ ! -f "$PKG_JSON" ] || [ ! -f "$CARGO_TOML" ]; then
  echo "[version-bump] required files are missing"
  exit 1
fi

CURRENT_VERSION="$(node -e "const fs=require('fs');const j=JSON.parse(fs.readFileSync('$TAURI_CONF','utf8'));process.stdout.write(String(j.version||''));")"

if ! echo "$CURRENT_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then
  echo "[version-bump] invalid version format in $TAURI_CONF: $CURRENT_VERSION"
  exit 1
fi

IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_VERSION"
NEW_VERSION="${MAJOR}.${MINOR}.$((PATCH + 1))"

echo "[version-bump] $CURRENT_VERSION -> $NEW_VERSION"

node -e "
const fs = require('fs');
const files = ['$PKG_JSON', '$TAURI_CONF'];
for (const file of files) {
  const json = JSON.parse(fs.readFileSync(file, 'utf8'));
  json.version = '$NEW_VERSION';
  fs.writeFileSync(file, JSON.stringify(json, null, 2) + '\n');
}
"

awk -v new_ver="$NEW_VERSION" '
BEGIN { in_package=0; done=0 }
/^\[package\]/ { in_package=1; print; next }
/^\[/ {
  if ($0 != "[package]") in_package=0
}
{
  if (in_package && !done && $1 == "version") {
    sub(/"[^"]+"/, "\"" new_ver "\"")
    done=1
  }
  print
}
' "$CARGO_TOML" > "$CARGO_TOML.tmp"
mv "$CARGO_TOML.tmp" "$CARGO_TOML"

echo "[version-bump] updated package.json / tauri.conf.json / Cargo.toml"
