"""Tests for Phase 3 engine transport wiring."""

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 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(records)

    def close(self) -> None:
        return None


class FailingTransport:
    def emit(self, records: list[LogRecord]) -> None:
        raise RuntimeError("transport emit failed")

    def close(self) -> None:
        return None


class TestEngineTransports(unittest.TestCase):
    def test_emit_forwards_single_record_batch_to_transport(self) -> None:
        transport = RecordingTransport()
        config = VedaTraceConfig(
            api_key="test-key",
            service="orders",
            transports=[transport],
        )
        engine = Engine(config)
        record = LogRecord.create(
            level=LogLevel.INFO,
            message="hello",
            service="orders",
        )

        engine.emit(record)

        self.assertEqual(len(engine._test_records), 1)
        self.assertEqual(len(transport.batches), 1)
        self.assertEqual(len(transport.batches[0]), 1)
        self.assertIs(transport.batches[0][0], record)

    def test_transport_emit_failure_is_swallowed_and_reports_on_error(self) -> None:
        seen: list[Exception] = []

        def on_error(exc: Exception) -> None:
            seen.append(exc)

        config = VedaTraceConfig(
            api_key="test-key",
            service="orders",
            transports=[FailingTransport()],
            on_error=on_error,
        )
        engine = Engine(config)
        record = LogRecord.create(
            level=LogLevel.ERROR,
            message="failed",
            service="orders",
        )

        engine.emit(record)

        self.assertEqual(len(engine._test_records), 1)
        self.assertEqual(len(seen), 1)
        self.assertIsInstance(seen[0], RuntimeError)
