from __future__ import annotations

import logging
import os

LOGGER_NAME = "iac"


class _IACContextFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        record.iac_run_id = os.environ.get("IAC_MODULE_RUN_ID", "")
        record.iac_step_name = os.environ.get("IAC_MODULE_STEP_NAME", "")
        record.iac_module_ref = os.environ.get("IAC_MODULE_REF", "")
        return True


def configure_logging(level: str | None = None) -> logging.Logger:
    logger = logging.getLogger(LOGGER_NAME)
    lvl = (level or os.environ.get("IAC_LOG_LEVEL", "INFO")).upper()
    logger.setLevel(getattr(logging, lvl, logging.INFO))
    logger.propagate = False

    if not logger.handlers:
        handler = logging.StreamHandler()
        fmt = (
            "%(asctime)s %(levelname)s "
            "[run=%(iac_run_id)s step=%(iac_step_name)s ref=%(iac_module_ref)s] "
            "%(message)s"
        )
        handler.setFormatter(logging.Formatter(fmt))
        handler.addFilter(_IACContextFilter())
        logger.addHandler(handler)
    return logger


logger = configure_logging()
