import asyncio
import os
from github.env import get_required_env_var, write_github_summary, exit_on_error_and_write_summary
from github.markdown import convert_to_markdown_table
from actions_logging.app_logging import logger

# release app imports
from release_app.models import MsData
from release_app.promote import deploy_services

async def main():
    """
    This function is the main entry point for the ECS_Restart process.
    It retrieves the environment name and services to be deployed from environment variables,
    constructs a list of service data objects, and then calls the deploy_services function to
    deploy the services to the specified environment.
    The images are tagged with the environment name version, and thus we are not updating
    the code that is running on the service, and only redeploying the same code on the given ser
    """
    try:
        logger.info("Starting the ECS_Restart process")
        env_name = get_required_env_var("ENV_NAME")
        logger.info(f"ENV_NAME var from environment:{env_name}")
        services = os.getenv("SERVICES", '')
        logger.info(f"SERVICES var from environment:{services}")
        service_list = [s.strip() for s in services.split(',')]
        logger.info(f"Parsed services: {service_list}")
        env_name_version = "production" if env_name.startswith('production-') else env_name
        logger.info(f"Environment name as 'version to deploy': {env_name_version}")
        services_to_deploy = [
            MsData(
                name=ms_name,
                version=env_name_version,
                env_vars_version='',
                type='backend'
            )
            for ms_name in service_list
        ]

        logger.info(f"Deploying services: {services_to_deploy} to {env_name} environment")
        status, details = await deploy_services(services_to_deploy, env_name, short_region="", ignore_errors=True)

        logger.info(details)

        write_github_summary(f"# Deployment status: {status.value}")
        write_github_summary(convert_to_markdown_table(details))
        if status.value == "FAILED":
            exit_on_error_and_write_summary("ECS restart failed")
    except Exception as e:
        exit_on_error_and_write_summary(f"Error during ECS restart: {e}")

if __name__ == "__main__":
    asyncio.run(main())