"""
Script to stop a TeamCity build based on its build ID.

Usage:
    python stop_build.py <build_id>
"""

import os
import sys
import requests
from actions_logging.app_logging import logger

# Configure your TeamCity server and API key.
TEAMCITY_SERVER = os.getenv('TEAMCITY_SERVER', 'https://ci.safersoftware.net')
API_KEY = os.getenv('TEAMCITY_API_KEY')
if not API_KEY:
    logger.error("TEAMCITY_API_KEY environment variable is required")
    sys.exit(1)

# Headers required for TeamCity REST API calls.
headers = {
    'Accept': 'application/json',
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/xml'
}

def stop_teamcity_build(build_id):
    """
    Stops the TeamCity build with the given build ID.
    The cancellation comment is always "Canceled from Github" and no re-addition to the queue is requested.
    
    Args:
        build_id (str): The ID of the build to stop.

    Returns:
        bool: True if the build was successfully stopped; False otherwise.
    """
    url = f"{TEAMCITY_SERVER}/app/rest/builds/id:{build_id}"
    # Build cancel request in XML format with the required comment.
    data = '<buildCancelRequest comment="Canceled from Github" />'
    
    response = requests.post(url, headers=headers, data=data)
    
    if response.status_code == 200:
        logger.info(f"Successfully stopped build {build_id}.")
        return True
    elif response.status_code == 400:
        # Assuming 400 indicates the build is already completed.
        logger.info(f"Build {build_id} is already completed; no need to cancel.")
        return True
    else:
        logger.error(
            f"Failed to stop build {build_id}. "
            f"Status code: {response.status_code}, Response: {response.text}"
        )
        return False

def main():
    # Check if a build ID was provided; if not, exit with a success code.
    if len(sys.argv) != 2 or not sys.argv[1].strip():
        logger.info("No build ID provided. Job was not created.")
        sys.exit(0)

    build_id = sys.argv[1].strip()
    success = stop_teamcity_build(build_id)
    sys.exit(0 if success else 1)

if __name__ == '__main__':
    main()
