import io
import os
import re
import datetime
"""
This is setup.py to be used from bitbake recipe.
If package is downloaded from git, the version is taken from the latest tag.
"""

VERSION_FILE_CONTENT = \
"""# file generated by setup.py
# don't change, don't track in version control
TYPE_CHECKING = False
if TYPE_CHECKING:
    from typing import Tuple, Union
    VERSION_TUPLE = Tuple[Union[int, str], ...]
else:
    VERSION_TUPLE = object

version: str
__version__: str
__version_tuple__: VERSION_TUPLE
version_tuple: VERSION_TUPLE\n\n"""


version_file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'src/mq4hemc/_version.py'))
tag = os.popen('git describe --abbrev=7 --dirty --always').read().strip()
if tag:
    dirty = False
    out_of_tag = False
    date = 'Undefined'
    if '-dirty' in tag:
        tag = tag.replace('-dirty', '')
        dirty = True
        # Get the current date
        date = datetime.datetime.now().strftime('%Y%m%d')
    if '-g' in tag:
        tag = tag.replace('-g', '+g')
        out_of_tag = True
    if '-' in tag:
        tag = tag.replace('-', '.dev')
        out_of_tag = True
    tag_list = tag.split('.')
    # Convert the tag to a version tuple
    tag_tuple = []
    for i in range(len(tag_list)):
        try:
            tag_tuple.append(int(tag_list[i]))
        except ValueError:
            break

    if dirty or out_of_tag:
        length = len(tag_tuple)
        if length > 0:
            tag_tuple[length - 1] += 1

        offset = '0'
        match = re.search(r'\.dev(.*)\+', tag)
        if match:
            offset = match.group(1)
        tag_tuple.append('dev' + offset)

        head_sha = os.popen('git rev-parse --short=7 HEAD').read().strip()
        if dirty:
            tag_tuple.append('g' + head_sha + '.d' + date)
        else:
            tag_tuple.append('g' + head_sha)
    # Write the text to the file
    with open(version_file, 'w') as f:
        f.write(VERSION_FILE_CONTENT)
        tag_str = '.'.join(str(x) for x in tag_tuple)
        tag_str = tag_str.replace('.g', '+g')
        f.write(f"__version__ = version = '{tag_str}'\n")
        tuple_str = str(tag_tuple).replace('[', '(').replace(']', ')')
        f.write(f"__version_tuple__ = version_tuple = {tuple_str}\n")

version="0.0.1"
if os.path.isfile(version_file):
    with io.open(version_file, "rt", encoding="utf8") as f:
        match = re.search(r"__version__ = version = '(.*)'", f.read())
        if match:
            version = match.group(1)

from setuptools import setup
setup(
    version=version,
)
