#!/usr/bin/env python3
"""
Sync version from pyproject.toml to npm/package.json.

Run this before releasing to ensure versions stay in sync:
    python scripts/sync_version.py
"""

import json
import re
from pathlib import Path


def main():
    root = Path(__file__).parent.parent

    # Read version from pyproject.toml
    pyproject_path = root / "pyproject.toml"
    pyproject_content = pyproject_path.read_text()

    match = re.search(r'^version\s*=\s*"(.+)"', pyproject_content, re.MULTILINE)
    if not match:
        print("Error: Could not find version in pyproject.toml")
        return 1

    version = match.group(1)

    # Update npm/package.json
    npm_package_path = root / "npm" / "package.json"
    if not npm_package_path.exists():
        print(f"Error: {npm_package_path} not found")
        return 1

    pkg = json.loads(npm_package_path.read_text())
    old_version = pkg.get("version", "unknown")
    pkg["version"] = version
    npm_package_path.write_text(json.dumps(pkg, indent=2) + "\n")

    print(f"Synced version: {old_version} -> {version}")
    return 0


if __name__ == "__main__":
    exit(main())
