"""End-to-end retry safety tests through Logger -> Engine -> HttpTransport."""

from __future__ import annotations

import pathlib
import sys
import unittest
from unittest import mock


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 import VedaTrace
from vedatrace.config import RetryConfig, VedaTraceConfig


class TestRetryEndToEnd(unittest.TestCase):
    def test_logger_info_never_raises_and_reports_once_per_failed_emit(self) -> None:
        urlopen_calls = 0
        on_error_calls: list[Exception] = []

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

        def always_fail_urlopen(req, timeout):  # type: ignore[no-untyped-def]
            nonlocal urlopen_calls
            _ = req
            _ = timeout
            urlopen_calls += 1
            raise RuntimeError("network down")

        config = VedaTraceConfig(
            api_key="test-key",
            service="orders",
            console_enabled=False,
            retry=RetryConfig(max_retries=2, retry_delay_seconds=0.0),
            on_error=on_error,
        )
        logger = VedaTrace(
            api_key="ignored-key",
            service="ignored-service",
            config=config,
        )

        with mock.patch(
            "vedatrace.transports.http.urlrequest.urlopen",
            new=always_fail_urlopen,
        ):
            logger.info("x")
            self.assertEqual(urlopen_calls, 3)
            self.assertEqual(len(on_error_calls), 1)
            self.assertIsInstance(on_error_calls[0], RuntimeError)

            logger.info("x-again")
            self.assertEqual(urlopen_calls, 6)
            self.assertEqual(len(on_error_calls), 2)
            self.assertIsInstance(on_error_calls[1], RuntimeError)


if __name__ == "__main__":
    unittest.main()
