"""Tests for Phase 1 safety utilities."""

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.safe import safe_call


class TestSafeCall(unittest.TestCase):
    def test_returns_result_when_function_succeeds(self) -> None:
        self.assertEqual(safe_call(lambda: "ok"), "ok")

    def test_returns_default_when_function_raises(self) -> None:
        result = safe_call(
            lambda: (_ for _ in ()).throw(ValueError("boom")),
            default="fallback",
        )
        self.assertEqual(result, "fallback")

    def test_calls_on_error_when_function_raises(self) -> None:
        captured: list[Exception] = []

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

        result = safe_call(
            lambda: (_ for _ in ()).throw(RuntimeError("fail")),
            on_error=on_error,
            default=None,
        )

        self.assertIsNone(result)
        self.assertEqual(len(captured), 1)
        self.assertIsInstance(captured[0], RuntimeError)
        self.assertEqual(str(captured[0]), "fail")

    def test_does_not_raise_if_on_error_raises(self) -> None:
        def raising_on_error(exc: Exception) -> None:
            raise RuntimeError("callback failed")

        result = safe_call(
            lambda: (_ for _ in ()).throw(ValueError("boom")),
            on_error=raising_on_error,
            default="safe-default",
        )
        self.assertEqual(result, "safe-default")
