"""Version identifiers for concerns pertinent to the Viv compiler."""

__all__ = ["__version__", "__grammar_version__", "__schema_version__"]

import json
from typing import Final
from importlib import resources
from importlib.metadata import version, PackageNotFoundError


def _read_compiler_version() -> str:
    """Return the current compiler version.

    Note: If the package is being run directly from source, a dummy version is returned.

    Returns:
        The current compiler version.
    """
    try:
        return version("viv-compiler")
    except PackageNotFoundError:
        # If the compiler is being run directly from source, return a dummy version
        return "0.0.0+local"


def _read_grammar_version() -> str:
    """Return the current grammar version stored in the grammar file.

    Returns:
        The current grammar version.

    Raises:
        RuntimeError: There is no version number in the grammar file.
    """
    text = resources.files("viv_compiler.grammar").joinpath("viv.peg").read_text(encoding="utf-8")
    for line in text.splitlines():
        if line.startswith("// VERSION:"):
            return line.split(":", 1)[1].strip()
    raise RuntimeError("Grammar version not found") from None


def _read_schema_version() -> str:
    """Return the current schema version stored in the canonical compiler schema file.

    Returns:
        The current schema version.

    Raises:
        RuntimeError: There is no version number in the schema file.
    """
    text = resources.files("viv_compiler.schemas").joinpath("compiler.schema.json").read_text(encoding="utf-8")
    try:
        return json.loads(text)["version"]
    except KeyError:
        raise RuntimeError("Schema version not found") from None


# Version for the Viv compiler
__version__: Final[str] = _read_compiler_version()

# Version for the Viv DSL grammar (editor plugins assume compatibility)
__grammar_version__: Final[str] = _read_grammar_version()

# Version for the schema for compiled content bundles (runtimes enforce compatibility)
__schema_version__: Final[str] = _read_schema_version()
