"""Tests for Logger flush/close behavior with batching."""

from __future__ import annotations

import pathlib
import sys
import unittest


ROOT = pathlib.Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))

from vedatrace._engine import Engine
from vedatrace.config import BatchingConfig, VedaTraceConfig
from vedatrace.logger import Logger
from vedatrace.models import LogRecord


class RecordingTransport:
    def __init__(self) -> None:
        self.batches: list[list[LogRecord]] = []
        self.close_calls = 0

    def emit(self, records: list[LogRecord]) -> None:
        self.batches.append(list(records))

    def close(self) -> None:
        self.close_calls += 1


class TestLoggerFlushClose(unittest.TestCase):
    def test_flush_sends_pending_batch_record(self) -> None:
        transport = RecordingTransport()
        config = VedaTraceConfig(
            api_key="k",
            service="s",
            batching=BatchingConfig(
                enabled=True,
                batch_size=3,
                flush_interval_seconds=0.0,
            ),
            transports=[transport],
        )
        engine = Engine(config)
        logger = Logger(config, engine)

        logger.info("pending")
        self.assertEqual(len(transport.batches), 0)

        logger.flush()

        self.assertEqual(len(transport.batches), 1)
        self.assertEqual(len(transport.batches[0]), 1)
        self.assertEqual(transport.batches[0][0].message, "pending")

    def test_close_flushes_pending_batch_record_then_closes_transport(self) -> None:
        transport = RecordingTransport()
        config = VedaTraceConfig(
            api_key="k",
            service="s",
            batching=BatchingConfig(
                enabled=True,
                batch_size=3,
                flush_interval_seconds=0.0,
            ),
            transports=[transport],
        )
        engine = Engine(config)
        logger = Logger(config, engine)

        logger.info("pending-on-close")
        self.assertEqual(len(transport.batches), 0)

        logger.close()

        self.assertEqual(len(transport.batches), 1)
        self.assertEqual(len(transport.batches[0]), 1)
        self.assertEqual(transport.batches[0][0].message, "pending-on-close")
        self.assertEqual(transport.close_calls, 1)
