# Builtins
import datetime
from setuptools import setup
from setuptools.config.setupcfg import read_configuration
import subprocess
import toml

# External packages
import yaml
from setuptools_scm import get_version

# Set release version by hand
releaseVersion = "2022.12"

# Read dependencies from setup.cfg + pyproject.toml and create conda environment file
envFile = "acme.yml"
setupOpts = read_configuration("setup.cfg")["options"]
tomlPkgs = toml.load("pyproject.toml")["build-system"]["requires"]
allPkgs = setupOpts["install_requires"] + setupOpts["extras_require"]["dev"] + tomlPkgs
pipPkgs = ["dask-jobqueue", "sphinx_automodapi"]
for k in range(len(pipPkgs)):
    pkg = pipPkgs[k]
    pipPkgs[k] = allPkgs.pop([allPkgs.index(dep) for dep in allPkgs if pkg in dep][0])
pyVer = setupOpts
allPkgs += ["python " + str(setupOpts["python_requires"]), "pip", {"pip" : pipPkgs}]
ymlDict = {"name" : "acme",
           "channels" : ["defaults", "conda-forge"],
           "dependencies" : allPkgs}
msg = "# This file was auto-generated by setup.py on {}. \n" +\
    "# Do not edit, all of your changes will be overwritten. \n"
msg = msg.format(datetime.datetime.now().strftime("%d/%m/%Y at %H:%M:%S"))
with open(envFile, 'w') as ymlFile:
    ymlFile.write(msg)
    yaml.dump(ymlDict, ymlFile, default_flow_style=False)

# If code has not been obtained via `git` or we're inside the main branch,
# use the hard-coded `releaseVersion` as version. Otherwise keep the local `tag.devx`
# scheme for TestPyPI uploads
proc = subprocess.run("git branch --show-current", shell=True, capture_output=True, text=True)
if proc.returncode !=0 or proc.stdout.strip() == "main":
    version = releaseVersion
    versionKws = {"use_scm_version" : False, "version" : version}
else:
    version = get_version(root='.', relative_to=__file__, local_scheme="no-local-version")
    versionKws = {"use_scm_version" : {"local_scheme": "no-local-version"}}

# Update citation file
citationFile = "CITATION.cff"
with open(citationFile) as ymlFile:
    ymlObj = yaml.safe_load(ymlFile)
ymlObj["version"] = version
ymlObj["date-released"] = datetime.datetime.now().strftime("%Y-%m-%d")
with open(citationFile, "w") as ymlFile:
    yaml.dump(ymlObj, ymlFile)

# Run setup (note: identical arguments supplied in setup.cfg will take precedence)
setup(
    setup_requires=['setuptools_scm'],
    **versionKws
)
