#!/usr/bin/env python3
"""Write ``blumkin/_build_metadata.py`` before ``uv build``.

Reads optional environment variables and regenerates
:mod:`blumkin._build_metadata` so installs without a ``.git`` directory still
expose an accurate commit via ``blumkin --version``:

* ``BLUMKIN_EMBED_VERSION`` — package version string (for example ``0.2.0``).
* ``BLUMKIN_EMBED_COMMIT`` — full or short git SHA (first 12 hex chars kept).

If a variable is unset or empty, the corresponding field is written as an
empty string and :mod:`blumkin.version` falls back as usual.
"""

from __future__ import annotations

import os
import shutil
import sys
from pathlib import Path


def _ensure_uv() -> None:
    """Re-exec under ``uv run`` if not already in the managed environment."""
    if os.environ.get("UV_ACTIVE") or "/.venv/" in (sys.executable or ""):
        return
    uv = shutil.which("uv")
    if uv:
        os.execv(uv, [uv, "run", sys.argv[0], *sys.argv[1:]])


def _normalize_embedded_commit(raw: str) -> str:
    token = raw.strip()
    if not token:
        return ""
    if len(token) > 12:
        return token[:12]
    return token


def _write_metadata_file(repo_root: Path, version: str, commit: str) -> None:
    path = repo_root / "src" / "blumkin" / "_build_metadata.py"
    if version or commit:
        body = f'''"""Autogenerated by scripts/embed_build_metadata — do not hand-edit."""

from __future__ import annotations

EMBEDDED_COMMIT: str = {commit!r}
EMBEDDED_VERSION: str = {version!r}
'''
    else:
        body = '''"""Optional release-time stamps baked into wheels or sdists.

``scripts/embed_build_metadata`` overwrites this file before packaging so
``blumkin --version`` still reports a commit when ``.git`` is absent (for
example after ``pipx install`` from PyPI). Empty strings mean "unset" and
:mod:`blumkin.version` falls back to env, then ``git``, then ``unknown``.
"""

from __future__ import annotations

EMBEDDED_COMMIT: str = ""
EMBEDDED_VERSION: str = ""
'''
    path.write_text(body, encoding="utf-8")


def main() -> None:
    repo_root = Path(__file__).resolve().parent.parent
    version = os.environ.get("BLUMKIN_EMBED_VERSION", "").strip()
    commit_raw = os.environ.get("BLUMKIN_EMBED_COMMIT", "").strip()
    commit = _normalize_embedded_commit(commit_raw)
    _write_metadata_file(repo_root, version, commit)


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