from pathlib import Path
from invoke import task
import xml.etree.ElementTree as ET


@task
def release(c, version):
    """"""
    if version not in ["minor", "major", "patch"]:
        print("Version can be either major, minor or patch.")
        return

    ns = {"maven": "http://maven.apache.org/POM/4.0.0"}
    tree = ET.ElementTree(ET.fromstring(Path("pom.xml").read_text()))
    version_node = tree.find("./maven:version", ns)
    __version__ = version_node.text
    __version_info__ = tuple((int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".")))
    _major, _minor, _patch = __version_info__

    if version == "patch":
        _patch = _patch + 1
    elif version == "minor":
        _minor = _minor + 1
        _patch = 0
    elif version == "major":
        _major = _major + 1
        _minor = 0
        _patch = 0

    c.run(f"git checkout -b release-{_major}.{_minor}.{_patch} dev")
    #     This pollutes the xml file, we'll just use sed
    #     version_node.text = f"{_major}.{_minor}.{_patch}"
    #     tree.write("pom.xml", ns)
    c.run(f"sed -i '0,/<version>{__version__}/ s/<version>{__version__}/<version>{_major}.{_minor}.{_patch}/g' pom.xml")
    print(f"Update the readme for version {_major}.{_minor}.{_patch}.")
    input("Press enter when ready.")
    c.run(f"git add -u")
    c.run(f'git commit -m "Update changelog version {_major}.{_minor}.{_patch}"')
    c.run(f"git push --set-upstream origin release-{_major}.{_minor}.{_patch}")
    c.run(f"git checkout main")
    c.run(f"git merge --no-ff release-{_major}.{_minor}.{_patch}")
    c.run(f'git tag -a {_major}.{_minor}.{_patch} -m "Release {_major}.{_minor}.{_patch}"')
    c.run(f"git push")
    c.run(f"git checkout dev")
    c.run(f"git merge --no-ff release-{_major}.{_minor}.{_patch}")
    c.run(f"git push")
    c.run(f"git branch -d release-{_major}.{_minor}.{_patch}")
    c.run(f"git push origin --tags")