#
# Copyright © 2023 Ernst Strüngmann Institute (ESI) for Neuroscience
# in Cooperation with Max Planck Society
#
# SPDX-License-Identifier: BSD-3-Clause
#

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

# External packages
import yaml

# Manually set release version
releaseVersion = "2023.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 = ["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])
condaMap = {"msgpack" : "msgpack-python"}
for pipName, condaName in condaMap.items():
    depIdx = [allPkgs.index(dep) for dep in allPkgs if pipName in dep][0]
    depName = allPkgs[depIdx]
    allPkgs[depIdx] = depName.replace(pipName, condaName)
pyVer = setupOpts
allPkgs += ["python " + str(setupOpts["python_requires"]), "pip", {"pip" : pipPkgs}]
ymlDict = {"name" : "acme",
           "channels" : ["defaults", "conda-forge"],
           "dependencies" : allPkgs}
header = "#\n" +\
    "# Copyright © {} Ernst Strüngmann Institute (ESI) for Neuroscience " +\
    "# in Cooperation with Max Planck Society\n#\n" +\
    "# SPDX-License-Identifier: CC0-1.0\n#\n" +\
    "# This file was auto-generated by setup.py on {}. \n" +\
    "# Do not edit, all of your changes will be overwritten. \n"
header = header.format(datetime.datetime.now().strftime("%Y"),
                       datetime.datetime.now().strftime("%d/%m/%Y at %H:%M:%S"))
with open(envFile, "w", encoding="utf8") as ymlFile:
    ymlFile.write(header)
    yaml.dump(ymlDict, ymlFile, default_flow_style=False)

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

# Run setup (note: identical arguments supplied in setup.cfg will take precedence)
setup(version=releaseVersion)
