"""Project version and build metadata.

The version is read from pyproject.toml (single source of truth). Build-time
metadata (git commit, build timestamp) is injected via environment variables
set in the Dockerfile so ``/api/health`` can report what's actually running.
"""

from __future__ import annotations

import os
import re
from functools import lru_cache
from pathlib import Path

_HERE = Path(__file__).resolve()
_PYPROJECT = _HERE.parent.parent.parent / "pyproject.toml"
_VERSION_RE = re.compile(r'^version\s*=\s*"([^"]+)"', re.MULTILINE)


@lru_cache(maxsize=1)
def get_version() -> str:
    """Return the project version from pyproject.toml."""
    try:
        text = _PYPROJECT.read_text(encoding="utf-8")
        match = _VERSION_RE.search(text)
        if match:
            return match.group(1)
    except OSError:
        pass
    return "unknown"


def get_build_info() -> dict[str, str]:
    """Return build metadata from environment variables.

    Populated by the Dockerfile at image build time:
      - AGENTEVAL_BUILD_COMMIT: short git SHA
      - AGENTEVAL_BUILD_TIME: ISO-8601 build timestamp
    """
    return {
        "version": get_version(),
        "commit": os.environ.get("AGENTEVAL_BUILD_COMMIT", "unknown"),
        "built_at": os.environ.get("AGENTEVAL_BUILD_TIME", "unknown"),
    }
