import os

from actions_logging.app_logging import logger
from github.env import (exit_on_error_and_write_summary, write_github_env,
                        write_github_output)
from terragrunt.tg_common import sanitize_work_dir
from terragrunt.slack import set_slack_status, prepend_message_with_inputs
from terragrunt.plan_diff_and_summarize import build_plan_summary
from terragrunt.drift_detection import check_apply_for_drift
from terragrunt.constants import APPLY

def main():
    """
    Main function to check for drift after apply and set Slack notification details.

    Gets environment variables, checks for drift, sets GitHub environment and output variables,
    and sets Slack notification title and status.
    """
    try:
        tool = os.getenv('TOOL')
        work_dir = sanitize_work_dir(os.getenv('WORK_DIR'))
        exec_mode = os.getenv('EXECUTION_MODE', APPLY)
        plan_version = os.getenv('PLAN_VERSION', '')
        env_name = os.getenv('ENV_NAME')

        logger.warning("Checking if apply differs from plan")
        drift = None
        if exec_mode != APPLY:
            raise ValueError("post-apply drift detection for execution modes other than APPLY is not implemented")

        drift = check_apply_for_drift(work_dir, tool)


        slack_title = "No changes expected from running plan after apply. We are good"
        formatted_plan_summary = prepend_message_with_inputs("No drift detected", work_dir, env_name, plan_version, exec_mode)
        if drift:
            slack_title = f"Post-apply drift detected, please review expected changes"
            plan_summary = build_plan_summary(work_dir, tool, drift)
            formatted_plan_summary = prepend_message_with_inputs(plan_summary, work_dir, env_name, plan_version, exec_mode)

        logger.warning(slack_title)
        logger.info(formatted_plan_summary)

        write_github_env(formatted_plan_summary, 'PLAN_SUMMARY')
        write_github_output(formatted_plan_summary, 'PLAN_SUMMARY')
        write_github_env(slack_title, 'SLACK_TITLE')
        set_slack_status(exec_mode, drift)
    except Exception as e:
        exit_on_error_and_write_summary(f"Error occurred during drift check after apply: {e}")

if __name__ == "__main__":
    main()
