import json
import logging

from core.logging import configure_logging, get_logger, bind_request_context, clear_request_context


def test_structlog_json_includes_request_and_user_id(capsys):
    # Configure JSON logging at INFO level
    configure_logging(json_logs=True, log_level="INFO")
    logger = get_logger("test_logger")

    # Bind context and emit a log
    bind_request_context(request_id="req-1234", user_id="user-42")
    logger.info("test_event", extra_field="value")
    clear_request_context()

    captured = capsys.readouterr().out.strip()
    assert captured, "No log output captured"

    # One line of JSON
    log_obj = json.loads(captured)
    assert log_obj.get("event") == "test_event"
    assert log_obj.get("request_id") == "req-1234"
    assert log_obj.get("user_id") == "user-42"
    assert log_obj.get("level") in {"info", "INFO"}


def test_stdlib_logging_also_goes_through_structlog(capsys):
    configure_logging(json_logs=True, log_level="INFO")

    logger = logging.getLogger("stdlib_logger")
    logger.info("hello from stdlib")

    captured = capsys.readouterr().out.strip()
    assert captured, "No log output captured for stdlib logger"

    log_obj = json.loads(captured)
    assert log_obj.get("event") == "hello from stdlib"
    assert log_obj.get("level") in {"info", "INFO"}

