#!/usr/bin/env python3
"""Sync version across pyproject.toml, manifest.json, and server.json."""

import json
import re
import sys
import tomllib


def main():
    version = sys.argv[1] if len(sys.argv) > 1 else None

    with open("pyproject.toml", "rb") as f:
        version = version or tomllib.load(f)["project"]["version"]

    # pyproject.toml
    text = open("pyproject.toml").read()
    text = re.sub(r'version\s*=\s*"[^"]+"', f'version = "{version}"', text, count=1)
    open("pyproject.toml", "w").write(text)

    # manifest.json
    manifest = json.load(open("manifest.json"))
    manifest["version"] = version
    json.dump(manifest, open("manifest.json", "w"), indent=2)

    # server.json
    server = json.load(open("server.json"))
    server["version"] = version
    for pkg in server.get("packages", []):
        pkg["version"] = version
    json.dump(server, open("server.json", "w"), indent=2)

    print(f"Synced all version sources to v{version}")


if __name__ == "__main__":
    main()
