from actions_logging.app_logging import logger
from teamcity_apis.constants import AUTOMATION_SMALL_MACHINES_BUILD_ID, headers, url
from common.common import raise_with_context
from github.env import write_github_summary
import requests


def trigger_teamcity_build(custom_parameters:dict, build_configuration_id:str = AUTOMATION_SMALL_MACHINES_BUILD_ID ) -> str:
    """Triggers a build in TeamCity with custom parameters and returns the build ID.

    Args:
        custom_parameters (dict): Custom parameters for the build.
        build_configuration_id (str): The ID of the build configuration.

    Returns:
        str: The build ID if successful, or None if an error occurs.
    """
    try:
        data = {
            "buildType": {"id": build_configuration_id},
            "properties": {"property": [{"name": k, "value": v }
                                    for k, v in custom_parameters.items()]}
        }
        response = requests.post(url, headers=headers, json=data,timeout=10) 
        response.raise_for_status()
        if response.status_code == 200:
                if (build_id := response.json().get('id')):
                    return build_id
                logger.error("Error processing JSON response. Here's the response:", response.json())
                write_github_summary(f"Error processing JSON response. Here's the response: job name: {build_configuration_id}")
                raise_with_context(e)
        else:
            raise_with_context(None, RuntimeError, f"Failed to trigger build. Status code: {response.status_code}, Response content: {response.json()}, the job we tried to trigger is: {build_configuration_id}")
    except Exception as e:
        raise_with_context(e)