"""Tests for backend protocol and BenchflowBackend.

Covers:
    - BenchflowBackend satisfies Backend protocol (runtime_checkable)
    - BenchflowBackend.setup() is idempotent
    - TrialResult dataclass
"""

from __future__ import annotations

from types import SimpleNamespace

from clawbench.backend import Backend, TrialResult, BenchflowBackend


class TestBackendProtocol:
    def test_benchflow_backend_satisfies_protocol(self):
        """BenchflowBackend is recognized as a Backend implementation."""
        backend = BenchflowBackend()
        assert isinstance(backend, Backend)

    def test_protocol_has_required_methods(self):
        """Backend protocol exposes the expected methods."""
        assert hasattr(Backend, "setup")
        assert hasattr(Backend, "cleanup")
        assert hasattr(Backend, "run_trial")
        assert hasattr(Backend, "run_trial_async")


class TestBenchflowBackendSetup:
    def test_setup_idempotent(self):
        """Calling setup() twice doesn't re-init SDK."""
        backend = BenchflowBackend()
        backend._sdk = SimpleNamespace()
        backend.setup()
        assert isinstance(backend._sdk, SimpleNamespace)

    def test_cleanup_noop(self):
        """cleanup() runs without error."""
        BenchflowBackend().cleanup()


class TestTrialResult:
    def test_defaults(self):
        """TrialResult has sensible defaults."""
        result = TrialResult(score=0.5)
        assert result.score == 0.5
        assert result.side_info == {}
        assert result.trial_dir is None

    def test_with_all_fields(self):
        """TrialResult stores all fields."""
        from pathlib import Path

        result = TrialResult(
            score=1.0,
            side_info={"Feedback": {"Status": "completed"}},
            trial_dir=Path("/tmp/trial-123"),
        )
        assert result.score == 1.0
        assert result.side_info["Feedback"]["Status"] == "completed"
        assert result.trial_dir == Path("/tmp/trial-123")
