#!/usr/bin/env python3
"""Write version string from pyproject.toml into src/kgsteward/_version.py.

Usage: run this in repository root before packaging (e.g. in CI, or as part
of `uv build` / `uv publish` steps).
"""
import sys
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
PYPROJECT = ROOT / "pyproject.toml"
OUT = ROOT / "src" / "kgsteward" / "_version.py"

if not PYPROJECT.exists():
    print("pyproject.toml not found at", PYPROJECT, file=sys.stderr)
    sys.exit(1)

text = PYPROJECT.read_text(encoding="utf-8")
version = None

# Try tomllib (Python 3.11+)
try:
    import tomllib
    data = tomllib.loads(text)
    if isinstance(data, dict) and "project" in data and "version" in data["project"]:
        version = str(data["project"]["version"]).strip()
    elif "tool" in data and "poetry" in data["tool"] and "version" in data["tool"]["poetry"]:
        version = str(data["tool"]["poetry"]["version"]).strip()
except Exception:
    pass

if not version:
    m = re.search(r"^\s*version\s*=\s*[\"']([^\"']+)[\"']", text, re.MULTILINE)
    if m:
        version = m.group(1).strip()

if not version:
    print("Could not determine version from pyproject.toml", file=sys.stderr)
    sys.exit(2)

OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(f'__version__ = "{version}"\n', encoding="utf-8")
print("Wrote version", version, "to", OUT)
