"""
Kiểm thử cấu hình logging tập trung (sự cố 05/10/2026).

Bối cảnh: ứng dụng chưa từng cấu hình logging -> chỉ WARNING+ lọt ra stderr qua handler dự phòng
`logging.lastResort` (không giờ, không mức, không tên module); mọi INFO (captcha đồng thuận, đồng bộ
thành công...) bị nuốt. Khi đồng bộ chạy tốt, `docker logs` gần như trống -> không thể truy vết.
"""

import io
import logging
import re

import pytest

from app.core.logging_config import DSCONS_HANDLER_NAME, configure_logging


@pytest.fixture
def stream():
    buf = io.StringIO()
    root = logging.getLogger()
    saved_handlers, saved_level = list(root.handlers), root.level
    saved_levels = {n: logging.getLogger(n).level for n in ("app", "dscons", "httpx")}
    yield buf
    for h in list(root.handlers):
        if h not in saved_handlers:
            root.removeHandler(h)
    root.setLevel(saved_level)
    for n, lvl in saved_levels.items():
        logging.getLogger(n).setLevel(lvl)


def test_app_info_logs_are_emitted(stream):
    configure_logging(stream=stream)
    logging.getLogger("app.modules.invoices.infrastructure.adapters.gdt.gdt_auth").info(
        "Giải mã Captcha thành công [EX85BV]"
    )
    logging.getLogger("dscons.app").info("Khởi động DSCons")
    out = stream.getvalue()
    assert "Giải mã Captcha thành công [EX85BV]" in out
    assert "Khởi động DSCons" in out


def test_format_has_vn_time_level_and_logger_name(stream):
    configure_logging(stream=stream)
    logging.getLogger("app.modules.invoices.application.invoice_processing.auto_sync_scheduler").warning("x")
    line = stream.getvalue().strip().splitlines()[-1]
    assert re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \(GMT\+7\) WARNING ", line), line
    assert "[app.modules.invoices.application.invoice_processing.auto_sync_scheduler]" in line


def test_idempotent_across_reloads(stream):
    # uvicorn --reload import lại app.main trong tiến trình mới; gọi nhiều lần không được nhân đôi dòng log
    configure_logging(stream=stream)
    configure_logging(stream=stream)
    root = logging.getLogger()
    assert sum(1 for h in root.handlers if h.get_name() == DSCONS_HANDLER_NAME) == 1
    logging.getLogger("app.x").info("một lần")
    assert stream.getvalue().count("một lần") == 1


def test_third_party_info_noise_is_suppressed(stream):
    configure_logging(stream=stream)
    logging.getLogger("httpx").info("HTTP Request: POST https://openrouter.ai ...")
    logging.getLogger("httpx").warning("cảnh báo thật")
    out = stream.getvalue()
    assert "HTTP Request" not in out
    assert "cảnh báo thật" in out


def test_log_level_env_override(stream, monkeypatch):
    monkeypatch.setenv("DSCONS_LOG_LEVEL", "WARNING")
    configure_logging(stream=stream)
    logging.getLogger("app.y").info("ẩn")
    logging.getLogger("app.y").warning("hiện")
    out = stream.getvalue()
    assert "ẩn" not in out and "hiện" in out
