#!/usr/bin/env python3
from __future__ import annotations

import os
import setuptools_scm
from packaging.version import Version
from pathlib import Path

ROOT = Path(__file__).parent.parent.parent.absolute()


def get_version() -> tuple[str, tuple[int | str, ...]]:
    _version = setuptools_scm.get_version(root=ROOT)
    parsed_version = Version(_version)
    version_fields: tuple[int | str, ...] = parsed_version.release
    if parsed_version.epoch:
        version_fields = (f"{parsed_version.epoch}!", *version_fields)
    if parsed_version.pre is not None:
        version_fields += (f"{parsed_version.pre[0]}{parsed_version.pre[1]}",)

    if parsed_version.post is not None:
        version_fields += (f"post{parsed_version.post}",)

    if parsed_version.dev is not None:
        version_fields += (f"dev{parsed_version.dev}",)

    if parsed_version.local is not None:
        version_fields += (parsed_version.local,)

    return _version, version_fields


def write_version_file(
    filename: str, version: str, version_fields: tuple[int | str, ...]
) -> None:
    template = f"""# file generated by setuptools-scm
# don't change, don't track in version control

__all__ = ["__version__", "__version_tuple__", "version", "version_tuple"]

TYPE_CHECKING = False
if TYPE_CHECKING:
    from typing import Tuple
    from typing import Union

    VERSION_TUPLE = Tuple[Union[int, str], ...]
else:
    VERSION_TUPLE = object

version: str
__version__: str
__version_tuple__: VERSION_TUPLE
version_tuple: VERSION_TUPLE

__version__ = version = '{version}'
__version_tuple__ = version_tuple = {version_fields}
    """

    with open(filename, "w") as f:
        f.write(template)


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--write", help="Save version to this file")
    parser.add_argument(
        "--meson-dist",
        help="Output path is relative to MESON_DIST_ROOT",
        action="store_true",
    )
    args = parser.parse_args()

    version, version_tuple = get_version()

    if args.write:
        outfile = args.write
        if args.meson_dist:
            outfile = os.path.join(os.environ.get("MESON_DIST_ROOT", ""), outfile)

        # Print human readable output path
        relpath = os.path.relpath(outfile)
        if relpath.startswith("."):
            relpath = outfile
        write_version_file(relpath, version, version_tuple)
    else:
        print(version)
