"""Route third-party library logs (MSAL, Azure Identity, Azure AI SDK) through CLI_LOGGER.

These libraries emit through Python's stdlib `logging` module under their own
logger names (e.g. "msal", "azure.identity"). Without explicit handlers their
records either fall through to the root logger or are dropped, bypassing the
CLI's structured-log formatting, redaction, and --log-level control.

This module attaches a `StructuredEmitterHandler` to each routed logger, which
fans records into `CLI_LOGGER` via `emit_structured_log` while preserving the
original source-logger name in the "logger" field of each structured entry.
"""

import logging

from cli_logging.cli_logger import CLI_LOGGER, DIAGNOSTIC_RECORDS
from cli_logging.console_diagnostics import (
    emit_structured_log as _emit_structured_log,
)
from cli_logging.logging_utils import Operation

# Noisy at INFO (issue #204), so default to WARNING; --log-level debug opts in.
# Only parent loggers are listed — descendants reach us via propagate=True.
# test_descendant_propagation_routes_records_via_parent_handler locks that in.
THIRD_PARTY_LOGGERS = (
    "msal",
    "msal_extensions",
    "azure",
)

_LEVEL_NAME_BY_INT = {
    logging.DEBUG: "debug",
    logging.INFO: "info",
    logging.WARNING: "warning",
    logging.ERROR: "error",
    logging.CRITICAL: "error",
}

_HANDLER_ATTR = "_m365_eval_third_party_handler"


class StructuredEmitterHandler(logging.Handler):
    """Converts third-party LogRecords into the CLI's structured-log format."""

    def emit(self, record: logging.LogRecord) -> None:
        try:
            level_name = _LEVEL_NAME_BY_INT.get(record.levelno, "info")
            _emit_structured_log(
                level_name,
                record.getMessage(),
                operation=Operation.THIRD_PARTY,
                logger=CLI_LOGGER,
                diagnostic_records=DIAGNOSTIC_RECORDS,
                logger_name_override=record.name,
            )
        except Exception:
            self.handleError(record)


def _third_party_level(effective_log_level: str) -> int:
    """WARNING by default; DEBUG only when CLI is at --log-level debug."""
    if effective_log_level == "debug":
        return logging.DEBUG
    return logging.WARNING


def configure_third_party_logging(effective_log_level: str) -> None:
    """Attach the structured-emitter handler to each routed logger.

    Idempotent — re-running updates levels in place rather than stacking
    handlers. Also disables propagation on each routed logger so records do
    not leak through the root logger.
    """
    level_int = _third_party_level(effective_log_level)
    for name in THIRD_PARTY_LOGGERS:
        target = logging.getLogger(name)
        handler = getattr(target, _HANDLER_ATTR, None)
        if handler is None:
            handler = StructuredEmitterHandler()
            target.addHandler(handler)
            setattr(target, _HANDLER_ATTR, handler)
        handler.setLevel(level_int)
        target.setLevel(level_int)
        target.propagate = False
