"""Synchronize version from pyproject.toml to Godot addon files.

Reads the version string from pyproject.toml (single source of truth)
and patches plugin.cfg and godotiq_server.gd to match.

Usage:
    python scripts/sync_version.py
"""

from __future__ import annotations

import re
from pathlib import Path


def read_version(pyproject_path: Path) -> str:
    """Read the version string from pyproject.toml."""
    try:
        import tomllib

        data = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
        return data["project"]["version"]
    except ImportError:
        pass

    # Regex fallback for Python 3.10
    text = pyproject_path.read_text(encoding="utf-8")
    m = re.search(r'^version\s*=\s*"([^"]+)"', text, re.MULTILINE)
    if not m:
        raise ValueError("Could not find version in pyproject.toml")
    return m.group(1)


def update_plugin_cfg(cfg_path: Path, version: str) -> bool | None:
    """Replace the version= line in plugin.cfg.

    Returns True if modified, False if already correct, None if pattern not found.
    """
    text = cfg_path.read_text(encoding="utf-8")
    new_text, count = re.subn(
        r'^version="[^"]*"',
        f'version="{version}"',
        text,
        flags=re.MULTILINE,
    )
    if count == 0:
        return None
    if new_text == text:
        return False
    cfg_path.write_text(new_text, encoding="utf-8")
    return True


def update_server_gd(gd_path: Path, version: str) -> bool | None:
    """Replace the ADDON_VERSION const in godotiq_server.gd.

    Returns True if modified, False if already correct, None if pattern not found.
    """
    text = gd_path.read_text(encoding="utf-8")
    new_text, count = re.subn(
        r'^const ADDON_VERSION := "[^"]*"',
        f'const ADDON_VERSION := "{version}"',
        text,
        flags=re.MULTILINE,
    )
    if count == 0:
        return None
    if new_text == text:
        return False
    gd_path.write_text(new_text, encoding="utf-8")
    return True


def _report_update(name: str, result: bool | None, version: str, old_version: str | None = None) -> None:
    """Print status for a file update."""
    if result is True:
        if old_version:
            print(f"Updated {name}: {old_version} -> {version}")
        else:
            print(f"Updated {name} -> {version}")
    elif result is False:
        print(f"{name} already at {version}")
    else:
        print(f"WARNING: version pattern not found in {name}")


def _extract_current(text: str, pattern: str) -> str | None:
    """Extract the current version from file text using a regex pattern."""
    m = re.search(pattern, text, re.MULTILINE)
    return m.group(1) if m else None


def sync_all(project_root: Path) -> None:
    """Read version from pyproject.toml and sync to addon files."""
    version = read_version(project_root / "pyproject.toml")
    print(f"Reading version from pyproject.toml: {version}")

    cfg_path = project_root / "godot-addon" / "addons" / "godotiq" / "plugin.cfg"
    if cfg_path.exists():
        old = _extract_current(cfg_path.read_text(encoding="utf-8"), r'^version="([^"]*)"')
        result = update_plugin_cfg(cfg_path, version)
        _report_update("plugin.cfg", result, version, old)
    else:
        print(f"WARNING: {cfg_path} not found, skipping")

    gd_path = project_root / "godot-addon" / "addons" / "godotiq" / "godotiq_server.gd"
    if gd_path.exists():
        old = _extract_current(gd_path.read_text(encoding="utf-8"), r'^const ADDON_VERSION := "([^"]*)"')
        result = update_server_gd(gd_path, version)
        _report_update("godotiq_server.gd", result, version, old)
    else:
        print(f"WARNING: {gd_path} not found, skipping")


def main() -> None:
    """Entry point for version sync script."""
    project_root = Path(__file__).resolve().parent.parent
    sync_all(project_root)


if __name__ == "__main__":
    main()
