"""Tests for uvicorn access log enrichment to structured fields."""

from __future__ import annotations

import logging

from maybankforme.common.utils import _UvicornAccessEnricher


def make_record(name: str, msg: str) -> logging.LogRecord:
    return logging.LogRecord(
        name=name,
        level=logging.INFO,
        pathname=__file__,
        lineno=0,
        msg=msg,
        args=(),
        exc_info=None,
    )


def test_access_enricher_parses_message() -> None:
    enricher = _UvicornAccessEnricher()
    rec = make_record(
        "uvicorn.access",
        '127.0.0.1:50468 - "GET /health HTTP/1.1" 200',
    )
    assert enricher.filter(rec) is True

    assert rec.client_addr == "127.0.0.1:50468"  # type: ignore[attr-defined]
    assert rec.method == "GET"  # type: ignore[attr-defined]
    assert rec.path == "/health"  # type: ignore[attr-defined]
    assert rec.http_version == "1.1"  # type: ignore[attr-defined]
    assert rec.status_code == 200  # type: ignore[attr-defined]
    assert rec.request_line == "GET /health HTTP/1.1"  # type: ignore[attr-defined]
    assert rec.log_type == "http_access"  # type: ignore[attr-defined]


def test_access_enricher_ignores_other_loggers() -> None:
    enricher = _UvicornAccessEnricher()
    rec = make_record("uvicorn", "some message")
    assert enricher.filter(rec) is True
    assert not hasattr(rec, "client_addr")
