"""Tests for engine threshold-based batching behavior."""

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.models import LogLevel, LogRecord


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

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

    def close(self) -> None:
        return None


def _make_record(message: str) -> LogRecord:
    return LogRecord.create(
        level=LogLevel.INFO,
        message=message,
        service="orders",
        timestamp="2026-02-19T17:42:47.957694Z",
        metadata={},
    )


class TestBatchingEngineThreshold(unittest.TestCase):
    def test_disabled_batching_emits_immediately(self) -> None:
        transport = RecordingTransport()
        config = VedaTraceConfig(
            api_key="k",
            service="s",
            batching=BatchingConfig(enabled=False, batch_size=3),
            transports=[transport],
        )
        engine = Engine(config)

        engine.emit(_make_record("one"))

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

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

        engine.emit(_make_record("one"))
        engine.emit(_make_record("two"))
        self.assertEqual(len(transport.batches), 0)

        engine.emit(_make_record("three"))

        self.assertEqual(len(transport.batches), 1)
        self.assertEqual([r.message for r in transport.batches[0]], ["one", "two", "three"])

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

        engine.emit(_make_record("one"))
        engine.emit(_make_record("two"))
        self.assertEqual(len(transport.batches), 0)

        engine.flush()

        self.assertEqual(len(transport.batches), 1)
        self.assertEqual([r.message for r in transport.batches[0]], ["one", "two"])
