"""Basic tests for stdiobus Python SDK."""

import json
import os
import tempfile
import pytest

from stdiobus import (
    StdioBus,
    AsyncStdioBus,
    BusState,
    BackendMode,
    StdioBusError,
    InvalidArgumentError,
)


class TestImports:
    """Test that all exports are available."""
    
    def test_main_classes(self):
        from stdiobus import StdioBus, AsyncStdioBus
        assert StdioBus is not None
        assert AsyncStdioBus is not None
    
    def test_types(self):
        from stdiobus import BusState, BackendMode, BusStats
        assert BusState.RUNNING == 2
        assert BackendMode.AUTO == "auto"
    
    def test_errors(self):
        from stdiobus import (
            StdioBusError,
            InvalidArgumentError,
            TimeoutError,
            TransportError,
        )
        assert issubclass(InvalidArgumentError, StdioBusError)


class TestBusState:
    """Test BusState enum."""
    
    def test_values(self):
        assert BusState.CREATED == 0
        assert BusState.STARTING == 1
        assert BusState.RUNNING == 2
        assert BusState.STOPPING == 3
        assert BusState.STOPPED == 4


class TestBackendMode:
    """Test BackendMode enum."""
    
    def test_values(self):
        assert BackendMode.AUTO == "auto"
        assert BackendMode.NATIVE == "native"
        assert BackendMode.DOCKER == "docker"


class TestStdioBusCreation:
    """Test StdioBus instance creation."""
    
    def test_requires_config_path(self):
        with pytest.raises(InvalidArgumentError):
            StdioBus(config_path="")
    
    def test_native_not_available(self):
        """Test that native backend raises appropriate error when not built."""
        with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
            json.dump({"pools": []}, f)
            config_path = f.name
        
        try:
            with pytest.raises(InvalidArgumentError, match="Native backend not available"):
                StdioBus(config_path=config_path, backend="native")
        finally:
            os.unlink(config_path)


class TestErrors:
    """Test error classes."""
    
    def test_error_code(self):
        from stdiobus.errors import ErrorCode, InvalidArgumentError
        
        err = InvalidArgumentError("test message")
        assert err.code == ErrorCode.INVALID_ARGUMENT
        assert err.message == "test message"
    
    def test_error_to_dict(self):
        from stdiobus.errors import TimeoutError
        
        err = TimeoutError("request timed out", details={"method": "test"})
        d = err.to_dict()
        
        assert d["code"] == 3
        assert d["message"] == "request timed out"
        assert d["details"] == {"method": "test"}
    
    def test_error_from_code(self):
        from stdiobus.errors import error_from_code, TimeoutError
        
        err = error_from_code(3, "timeout")
        assert isinstance(err, TimeoutError)
