import os
import requests

class TCClient:
    def __init__(self, server_url, token, build_type_id):
        self.server_url = server_url
        self.token = token
        self.build_type_id = build_type_id

    def post_build(self, new_version):
        request = {
            "buildType": {
                "id": self.build_type_id
            },
            "properties": {
                "property": [
                    {"name": "env.scriptVersion", "value": new_version}
                ]
            }
        }

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": f"Bearer {self.token}"
        }

        response = requests.post(f"{self.server_url}/app/rest/buildQueue", json=request, headers=headers)

        # Check if the response contains JSON content
        if response.status_code == 200 and response.headers['Content-Type'] == 'application/json':
            return response.json()
        else:
            response.raise_for_status()  # Raise an exception for non-successful responses

    def get_build_status(self, build_id):
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": f"Bearer {self.token}"
        }

        response = requests.get(f"{self.server_url}/app/rest/buildQueue/{build_id}", headers=headers)

        # Check if the response contains JSON content
        if response.status_code == 200 and response.headers['Content-Type'] == 'application/json':
            return response.json()
        else:
            response.raise_for_status()  # Raise an exception for non-successful responses

# Retrieve values from environment variables
your_tc_server = os.environ.get("TC_SERVER")
your_tc_token = os.environ.get("TC_TOKEN")
your_build_type_ids = os.environ.get("TC_BUILD_TYPE_IDS")

# Check if environment variables are set
if not all([your_tc_server, your_tc_token, your_build_type_ids]):
    raise ValueError("One or more TeamCity environment variables are not set")

# Get the value of NEW_VERSION from the environment
new_version = os.environ.get("NEW_VERSION")

# Convert the build_type_ids string to a list
build_type_ids_list = your_build_type_ids.split(',')

# Create TCClient instance for each build type ID
tc_clients = [TCClient(your_tc_server, your_tc_token, build_type_id) for build_type_id in build_type_ids_list]

# Trigger the build with the specified new_version for each TCClient instance
for tc_client in tc_clients:
    sample_build = tc_client.post_build(new_version)
    print("Status", tc_client.get_build_status(sample_build["id"]))
