import io
import os
import re
from datetime import date as _date

from setuptools import find_packages
from setuptools import setup


def read(filename):
    filename = os.path.join(os.path.dirname(__file__), filename)
    text_type = type(u"")
    with io.open(filename, mode="r", encoding='utf-8') as fd:
        return re.sub(text_type(r':[a-z]+:`~?(.*?)`'), text_type(r'``\1``'), fd.read())


def get_version():
    """
    Get version with same-day increment support.
    Format: YYYY.MM.DD or YYYY.MM.DD.N for same-day republishes.
    
    Tracks last published version in .last_version file to auto-increment.
    PEP 440 normalizes this to YYYY.M.DD format in wheel names.
    """
    # Get base version from CI or use today's date
    base = os.getenv('PACKAGE_VERSION') or _date.today().strftime('%Y.%m.%d')
    
    # Check if we're republishing on the same day
    last_version_file = os.path.join(os.path.dirname(__file__), '.last_version')
    if os.path.exists(last_version_file):
        try:
            with open(last_version_file, 'r') as f:
                last = f.read().strip()
            
            # If last version starts with today's date, increment patch
            if last.startswith(base):
                parts = last.split('.')
                # Extract patch number (last component)
                if len(parts) > 3:
                    # Already has patch number
                    try:
                        patch = int(parts[-1]) + 1
                        return f"{base}.{patch}"
                    except ValueError:
                        pass
                # First same-day republish
                return f"{base}.1"
        except Exception:
            pass
    
    return base


# Get version with increment support
_version = get_version()


setup(
    name="bpp-anubis",
    version=_version,
    url="https://gitlab.com/blueprintprep/bpp-qa/utilities/anubis",
    license='MIT',

    author="matthew bahloul",
    author_email="matthew.bahloul@blueprintprep.com",

    description="Run behave tests in parallel",
    long_description=read("README.rst"),

    packages=find_packages(exclude=('tests',)),

    install_requires=[
        'behave>=1.2.6',
    ],

    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.10',
    ],

    entry_points={
            'console_scripts': [
                'anubis = anubis.__main__:main',
            ],
        }
)
