"""Vérifie le format des lignes de log produites par
`logging_config._JsonFormatter` — ce que `routes/process.py` et
`pipeline_registry.py` utilisent pour journaliser l'input/l'output de
chaque appel NLP et le déroulement de l'entraînement au démarrage."""

import json
import logging

from intent_service.logging_config import _JsonFormatter


def _make_record(**extra: object) -> logging.LogRecord:
    record = logging.LogRecord(
        name="intent_service.routes.process",
        level=logging.INFO,
        pathname=__file__,
        lineno=1,
        msg="tech-step NLP process",
        args=(),
        exc_info=None,
    )
    for key, value in extra.items():
        setattr(record, key, value)
    return record


def test_formats_a_record_as_json_with_timestamp_level_and_message():
    record = _make_record()
    payload = json.loads(_JsonFormatter().format(record))
    assert payload["message"] == "tech-step NLP process"
    assert payload["level"] == "info"
    assert "timestamp" in payload


def test_merges_extra_fields_into_the_top_level_payload():
    record = _make_record(
        locale="fr",
        text="faire fondre le beurre",
        entities=[{"uid": "melt", "start": 0, "end": 12}],
        intent="melt",
        score=0.93,
    )
    payload = json.loads(_JsonFormatter().format(record))
    assert payload["locale"] == "fr"
    assert payload["text"] == "faire fondre le beurre"
    assert payload["entities"] == [{"uid": "melt", "start": 0, "end": 12}]
    assert payload["intent"] == "melt"
    assert payload["score"] == 0.93


def test_preserves_accented_characters_literally_not_escaped():
    # `ensure_ascii=False` — un `docker logs` humain doit pouvoir lire
    # directement "poêle", pas "poêle".
    record = _make_record(text="Dans une poêle chaude")
    line = _JsonFormatter().format(record)
    assert "poêle" in line
    assert "\\u00ea" not in line
