import subprocess
import sys
from pathlib import Path

import semver
from loguru import logger
from semver.version import Version

logger.remove()
logger.add(sys.stdout, level="INFO")


def bashcmd(cmds: list) -> str:
    try:
        logger.debug(f"running: {' '.join(cmds)}")
        return subprocess.run(cmds, check=True, capture_output=True, text=True).stdout.strip("\n")
    except:
        logger.warning(f"Error executing the following bash command: {' '.join(cmds)}.")
        raise


def get_highest_existing_git_version_tag() -> str:
    """Get highest versions from git tags depending on bump level"""
    try:
        git_tags = bashcmd(["git", "tag", "-l"]).split()
        semver_compat_tags = list(filter(Version.is_valid, git_tags))
        highest_git_version_tag = max(semver_compat_tags, key=semver.version.Version.parse)
        logger.info(f"Highest git version tag: {highest_git_version_tag}")
        return highest_git_version_tag
    except:
        logger.warning("Error getting git version tags")
        raise


def auto_bump_version() -> bool:
    active = Path(".autoversion").is_file()
    logger.debug(f"Automated version bump is set to '{active}'")
    return active


def main() -> None:
    poetry_project_version = bashcmd(["poetry", "version", "-s"])

    logger.info(f"Poetry project version: {poetry_project_version}")

    highest_git_version_tag = get_highest_existing_git_version_tag()

    comparison_result = semver.compare(poetry_project_version, highest_git_version_tag)

    if comparison_result in (-1, 0):
        logger.warning("Poetry version must be greater than git tag version.")
        if auto_bump_version():
            logger.info(bashcmd(["poetry", "version", highest_git_version_tag]))
            sys.exit(0)
        sys.exit(1)
    else:
        logger.info(f"All good: {poetry_project_version} > {highest_git_version_tag}")


if __name__ == "__main__":
    main()
