"""Tests for the Knafeh Python bindings."""

import json

import pytest


def test_import() -> None:
    """Smoke test: the native module can be imported."""
    import knafeh
    from knafeh._native import TlsConfig

    assert knafeh is not None


def test_tls_config() -> None:
    """TlsConfig constructors work."""
    from knafeh import TlsConfig

    server_tls = TlsConfig.server("cert.pem", "key.pem")
    client_tls = TlsConfig.client("ca.pem")
    insecure = TlsConfig.client_insecure()

    assert server_tls is not None
    assert client_tls is not None
    assert insecure is not None


def test_service_handler() -> None:
    """ServiceHandler can register methods."""
    from knafeh._native import ServiceHandler

    handler = ServiceHandler("test_service")

    def echo(request: bytes) -> bytes:
        return request

    handler.add_unary_handler("echo", echo)


def test_server_builder() -> None:
    """Server can be constructed with the decorator API."""
    from knafeh import Server, TlsConfig

    tls = TlsConfig.server("cert.pem", "key.pem")
    server = Server("0.0.0.0:4433", tls=tls)

    @server.service("greeter")
    class Greeter:
        def say_hello(self, request: bytes) -> bytes:
            data = json.loads(request)
            return json.dumps({"message": f"Hello, {data['name']}!"}).encode()


def test_client_builder() -> None:
    """Client can be constructed."""
    from knafeh._native import RpcClient, TlsConfig

    tls = TlsConfig.client_insecure()
    client = RpcClient("localhost:4433", tls, 4)
    client.close()
