#!/usr/bin/env bash
# bump-versions.sh — Bump version in all 3 (or 4) sync points for a package
#
# Usage:
#   ./scripts/bump-versions.sh <repo_dir> <new_version>
#
# Example:
#   ./scripts/bump-versions.sh ../huje.sensememory.OC-python.src 0.1.3
#
# Updates:
#   1. pyproject.toml  → version = "X.Y.Z"
#   2. src/*/__init__.py → __version__ = "X.Y.Z"
#   3. clawhub/metadata.json → "version": "X.Y.Z"
#   4. clawhub/SKILL.md frontmatter → version: X.Y.Z (if present)

set -euo pipefail

REPO_DIR="${1:?Usage: bump-versions.sh <repo_dir> <new_version>}"
NEW_VERSION="${2:?Usage: bump-versions.sh <repo_dir> <new_version>}"

if [ ! -d "$REPO_DIR" ]; then
  echo "Error: $REPO_DIR not found"
  exit 1
fi

echo "Bumping $REPO_DIR to v$NEW_VERSION"

# 1. pyproject.toml
PYPROJECT="$REPO_DIR/pyproject.toml"
if [ -f "$PYPROJECT" ]; then
  sed -i '' "s/^version = \".*\"/version = \"$NEW_VERSION\"/" "$PYPROJECT"
  echo "  ✓ pyproject.toml"
else
  echo "  ⚠ No pyproject.toml"
fi

# 2. __init__.py (find the one with __version__)
INIT_FILE=$(grep -rl '__version__' "$REPO_DIR/src/" 2>/dev/null | head -1)
if [ -n "$INIT_FILE" ]; then
  sed -i '' "s/__version__ = \".*\"/__version__ = \"$NEW_VERSION\"/" "$INIT_FILE"
  echo "  ✓ $INIT_FILE"
else
  echo "  ⚠ No __init__.py with __version__"
fi

# 3. clawhub/metadata.json
METADATA="$REPO_DIR/clawhub/metadata.json"
if [ -f "$METADATA" ]; then
  python3 -c "
import json
with open('$METADATA', 'r') as f:
    data = json.load(f)
data['version'] = '$NEW_VERSION'
with open('$METADATA', 'w') as f:
    json.dump(data, f, indent=2)
    f.write('\n')
"
  echo "  ✓ clawhub/metadata.json"
else
  echo "  ⚠ No clawhub/metadata.json"
fi

# 4. clawhub/SKILL.md frontmatter (if version: line exists)
SKILL_MD="$REPO_DIR/clawhub/SKILL.md"
if [ -f "$SKILL_MD" ] && grep -q "^version:" "$SKILL_MD"; then
  sed -i '' "s/^version: .*/version: $NEW_VERSION/" "$SKILL_MD"
  echo "  ✓ clawhub/SKILL.md frontmatter"
fi

echo "Done — v$NEW_VERSION across all sync points"
