"""Unit tests for :mod:`mgf.common.observability.text_formatter`."""

from __future__ import annotations

import logging
from typing import Any

import pytest

from mgf.common.observability.redaction import REDACTED_PLACEHOLDER, Redactor
from mgf.common.observability.text_formatter import TextFormatter


def _make_record(
    *,
    name: str = "mgf.test",
    level: int = logging.INFO,
    msg: str = "hello",
    extra: dict[str, Any] | None = None,
    exc_info: object = None,
) -> logging.LogRecord:
    record = logging.LogRecord(
        name=name,
        level=level,
        pathname="test.py",
        lineno=42,
        msg=msg,
        args=None,
        exc_info=exc_info,  # type: ignore[arg-type]
        func="test_func",
    )
    if extra:
        for k, v in extra.items():
            setattr(record, k, v)
    return record


@pytest.fixture(autouse=True)
def _no_color(monkeypatch: pytest.MonkeyPatch) -> None:
    """Force colour off so assertions are simple. Tests for the colour
    branch live below in their own ``test_*_with_color`` fixtures."""
    monkeypatch.setenv("NO_COLOR", "1")


def test_basic_format_includes_level_logger_message() -> None:
    fmt = TextFormatter(redactor=Redactor.default())
    record = _make_record(msg="started", level=logging.INFO)
    out = fmt.format(record)
    assert "INFO" in out
    assert "mgf.test" in out
    assert "started" in out


def test_extras_appended_as_key_value_pairs() -> None:
    fmt = TextFormatter(redactor=Redactor.default())
    record = _make_record(extra={"vm_name": "prod-1"})
    out = fmt.format(record)
    assert "vm_name" in out
    assert "prod-1" in out


def test_redaction_runs_on_extras_in_text() -> None:
    fmt = TextFormatter(redactor=Redactor.default())
    record = _make_record(extra={"password": "secret"})
    out = fmt.format(record)
    assert REDACTED_PLACEHOLDER in out
    assert "secret" not in out


def test_exc_info_is_appended_below_main_line() -> None:
    fmt = TextFormatter(redactor=Redactor.default())
    try:
        raise ValueError("bad")
    except ValueError:
        import sys

        record = _make_record(level=logging.ERROR, msg="err", exc_info=sys.exc_info())
    out = fmt.format(record)
    assert "ValueError" in out
    assert "bad" in out
    # Multi-line — main line + traceback.
    assert "\n" in out
