import os
import re
import subprocess
from os.path import abspath, dirname, exists, join

from setuptools import find_packages, setup

setup_dir = dirname(abspath(__file__))
git_dir = join(setup_dir, ".git")
version_file = join(setup_dir, "version.py")
package_name = "go_utils"


def get_git_tag():
    try:
        git_tag = str(
            subprocess.check_output(
                ["git", "describe", "--exact-match", "--abbrev=0"],
                stderr=subprocess.STDOUT,
            )
        ).strip("'b\\n")
    except subprocess.CalledProcessError as exc_info:
        match = re.search(
            "fatal: no tag exactly matches '(?P<commit>[a-z0-9]+)'",
            str(exc_info.output),
        )
        if match:
            raise Exception(
                "Bailing: there is no git tag for the current commit, {commit}".format(
                    commit=match.group("commit")
                )
            )
        raise Exception(str(exc_info.output))

    return git_tag


# Automatically generate a version.py based on the git version
if exists(git_dir):
    proc = subprocess.run(
        ["git", "describe", "--exact-match", "--abbrev=0"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
    )
    # If there is no main branch, the commit count defaults to 0
    if proc.returncode:
        version_str = "0"
    else:
        version_str = proc.stdout.decode("utf-8")

    # Version number: <year>.<# commits on main>
    version = version_str.strip()
elif "go_utils-" in os.getcwd():
    version = os.getcwd().split("go_utils-")[1].strip()
else:
    version = "0"
if version != "0":
    # Create the version.py file
    with open(version_file, "w+") as fp:
        fp.write(f'# Autogenerated by setup.py\n__version__ = "{version}"')

if exists(version_file):
    with open(version_file, "r") as fp:
        exec(fp.read(), globals())
else:
    __version__ = "main"

with open(join(setup_dir, "README.md"), "r") as readme_file:
    long_description = readme_file.read()

setup(
    name=package_name,
    version=__version__,
    description="Utilities for interfacing with GLOBE Observer Data",
    long_description=long_description,
    long_description_content_type="text/markdown",
    author="IGES",
    maintainer="Matteo Kimura, Prachi Ingle",
    maintainer_email="mateus.sakata@gmail.com, prachi.ingle@utexas.edu",
    project_urls={
        "Source Code": "https://github.com/IGES-Geospatial/globe-observer-utils",
        "Documentation": "https://iges-geospatial.github.io/globe-observer-utils-docs/go_utils.html",
        "Bug Tracker": "https://github.com/IGES-Geospatial/globe-observer-utils/issues",
    },
    entry_points={
        "console_scripts": [
            "mhm-download=go_utils._cli:mhm_data_download",
            "lc-download=go_utils._cli:lc_data_download",
            "mhm-photo-download=go_utils._cli:mhm_photo_download",
            "lc-photo-download=go_utils._cli:lc_photo_download",
        ]
    },
    keywords="GlobeObserver GLOBE mosquito landcover",
    packages=find_packages(),
    include_package_data=True,
    zip_safe=True,
    setup_requires=["pytest-runner"],
    tests_require=["pytest"],
    install_requires=[
        "numpy>=1.19.0",
        "pandas>=1.1.5",
        "requests>=2.23.0",
        "arcgis==1.9.1",
        "seaborn>=0.11.1",
        "pytz>=2021.3",
        "timezonefinder>=5.2.0",
    ],
    python_requires=">=3.6",
    license="MIT License",
    classifiers=[
        "Intended Audience :: Education",
        "Operating System :: OS Independent",
        "License :: OSI Approved :: MIT License",
        "Topic :: Scientific/Engineering :: GIS",
        "Intended Audience :: Science/Research",
        "Programming Language :: Python :: 3",
    ],
)
