"""Tests for logging configuration behaviour."""

import logging
from pathlib import Path

import structlog

from dotpromptz.logging import configure_logging


def _cleanup_structlog_handlers() -> None:
    """Remove handlers created by configure_logging during tests."""
    root = logging.getLogger()
    for handler in list(root.handlers):
        if isinstance(handler.formatter, structlog.stdlib.ProcessorFormatter):
            root.removeHandler(handler)
            handler.close()


def test_configure_logging_closes_previous_file_handler(tmp_path: Path) -> None:
    """Old file handlers are detached and their streams are closed."""
    _cleanup_structlog_handlers()
    root = logging.getLogger()
    stale_handler = logging.FileHandler(tmp_path / 'stale.log', encoding='utf-8')
    root.addHandler(stale_handler)
    stale_stream = stale_handler.stream
    assert stale_stream is not None
    assert not stale_stream.closed

    configure_logging(level='INFO', log_dir=tmp_path)

    assert stale_handler not in root.handlers
    assert stale_stream.closed


def test_configure_logging_reconfigure_does_not_accumulate_handlers(tmp_path: Path) -> None:
    """Reconfiguring logging keeps a stable handler count."""
    _cleanup_structlog_handlers()
    root = logging.getLogger()

    configure_logging(level='INFO', log_dir=tmp_path)
    first_handlers = [
        handler for handler in root.handlers if isinstance(handler.formatter, structlog.stdlib.ProcessorFormatter)
    ]
    assert len(first_handlers) == 2

    configure_logging(level='DEBUG', log_dir=tmp_path)
    second_handlers = [
        handler for handler in root.handlers if isinstance(handler.formatter, structlog.stdlib.ProcessorFormatter)
    ]
    assert len(second_handlers) == 2
    assert all(handler not in second_handlers for handler in first_handlers)

