"""Sync the version across r_bridge/__init__.py, zensical.toml, and docs pages.

Usage:
    # Bump to a new version (updates __init__.py first, then propagates):
    python scripts/inject_version.py 0.7.0

    # Re-sync without changing the version (e.g. after a manual edit):
    python scripts/inject_version.py
"""

from __future__ import annotations

import re
import sys
from pathlib import Path

ROOT = Path(__file__).parent.parent
INIT = ROOT / "r_bridge" / "__init__.py"

# If a new version is given as an argument, write it into __init__.py first.
if len(sys.argv) > 1:
    new_version = sys.argv[1]
    if not re.fullmatch(r'\d+\.\d+\.\d+', new_version):
        sys.exit(f"inject_version: invalid version {new_version!r} — expected X.Y.Z")
    text = INIT.read_text(encoding="utf-8")
    updated = re.sub(
        r'^(__version__\s*=\s*["\'])([^"\']+)(["\'])',
        rf'\g<1>{new_version}\3',
        text,
        flags=re.MULTILINE,
    )
    INIT.write_text(updated, encoding="utf-8")
    print(f"inject_version: __init__.py → {new_version}")

# Read the version (either just written or pre-existing).
init_text = INIT.read_text(encoding="utf-8")
m = re.search(r'^__version__\s*=\s*["\']([^"\']+)["\']', init_text, re.MULTILINE)
if not m:
    sys.exit("inject_version: __version__ not found in r_bridge/__init__.py")
version = m.group(1)

# Propagate to other files.
updates = {
    ROOT / "zensical.toml": (
        r'(site_name\s*=\s*"r_bridge\s*)[\d.]+(")',
        rf'\g<1>{version}\2',
    ),
    ROOT / "docs" / "installation.md": (
        r'(Current version:\s*\*\*)[\d.]+(\*\*)',
        rf'\g<1>{version}\2',
    ),
}

for path, (pattern, replacement) in updates.items():
    text = path.read_text(encoding="utf-8")
    new = re.sub(pattern, replacement, text)
    if new != text:
        path.write_text(new, encoding="utf-8")
        print(f"inject_version: updated {path.name} → {version}")
    else:
        print(f"inject_version: {path.name} already at {version}")
