"""Checks that a tag release is valid to continue. This saves time"""
import argparse
from pathlib import Path
import yaml


def can_to_int(v) -> bool:
    try:
        int(v)
        return True
    except:
        return False


def verifyTag(tag: str):
    """Tag must be a sematic version with only 3 parts"""
    v = tag.split('.')

    msg = f"ERROR: {tag}  must be sematic version major.minor.patch"
    assert len(v) == 3, msg 

    for item in v:
        assert can_to_int(item), f"ERROR: {item} in tag: {tag}, is not valid"


def verifyGitlab(tag: str, gitlab_version: str):
    version_parts = gitlab_version.split(".")
    version_parts.pop() # to remove the build id
    gitlab_no_build_id = ".".join(version_parts)
    assert tag == gitlab_no_build_id, f"Tag, {tag}, does not match the version in the gitlab file: {gitlab_version}"


def verifyChangelog(tag: str, changelog_file: Path):
    msg = "The first line in the changelog must be: # major.minor.path and match the current tag"
    assert changelog_file.read_text().startswith(f"# {tag}"), msg


def verifyYaml(tag: str, yaml_file: str):
    with open(yaml_file, 'r') as file:
        req = yaml.safe_load(file)

    if tag not in req["requirements"]:
        raise ValueError(
            "the requirements file must contain a frozen version with the same version as the tag. refer to readme on how to do this")


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Write the latest.json file')

    requiredNamed = parser.add_argument_group('Required named arguments')
    requiredNamed.add_argument("--tag", required=True)
    requiredNamed.add_argument("--changelog", required=True)
    requiredNamed.add_argument("--gitlab-version", required=True)
    requiredNamed.add_argument("--yaml", required=True)
    args = parser.parse_args()

    verifyTag(args.tag)
    verifyGitlab(args.tag, args.gitlab_version)
    verifyChangelog(args.tag, Path(args.changelog))
    verifyYaml(args.tag, Path(args.yaml))
