import os
import requests
import logging
import re
import sys

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(asctime)s - %(message)s")

git_token = os.getenv('GLOBAL_CICD_GIT_TOKEN')
git_headers = {
    'Accept': 'application/vnd.github.v3+json',
    'Authorization': f'token {git_token}',
    'Content-Type': 'application/json',
}
api_url = "https://api.github.com/repos"


def get_latest_tag_with_env(repo, next_url=""):
    try:
        git_url = f"{api_url}/{repo}/tags?per_page=100"
        if next_url:
            git_url = next_url
        response = requests.get(git_url, headers=git_headers)
        if response.status_code == 200:
            tags = [tag['name'] for tag in response.json()]
            for tag in tags:
                if re.match(rf'^v\d+{taf_suffix}$', tag):
                    env_tags.append(tag)
            logging.info(f"environment tags: {env_tags}")
            if response.links:
                if response.links.get("next"):
                    if response.links["next"].get("url"):
                        next_page = response.links["next"]["url"]
                        get_latest_tag_with_env(repo, next_url=next_page)
        else:
            logging.error(f"Failed to fetch tags from GitHub API: {response.status_code}")
    except Exception as e:
        logging.error(f"Error occurred while fetching tags: {e}")


if __name__ == '__main__':
    if len(sys.argv) != 2:
        logging.error("Usage: python calculate_env_version.py <repository_name>")
        exit(1)
    taf_suffix = "-ENV_VARS"
    repo_name = sys.argv[1]
    logging.info(f"Repository name: {repo_name}")
    env_tags = []
    get_latest_tag_with_env(repo_name)
    if env_tags:
        latest_tag = max(env_tags, key=lambda x: int(re.search(rf'^v(\d+){taf_suffix}$', x).group(1)))
        latest_version = int(re.search(rf'^v(\d+){taf_suffix}$', latest_tag).group(1))
    else:
        latest_version = 0

    new_version = latest_version + 1
    new_env_version = f"v{new_version}{taf_suffix}"
    os.environ["NEW_ENV_VERSION"] = new_env_version
    os.system(f'echo "NEW_ENV_VERSION={new_env_version}" >> $GITHUB_ENV')
    logging.info(f"New environment version: {new_env_version}")

