import logging
import time
from concurrent import futures
import grpc
from prometheus_client import start_http_server

import echo_pb2
import echo_pb2_grpc

from fast_telemetry.core import PrometheusMetrics
from fast_telemetry.integrations.grpc import create_server_metrics_interceptor


class EchoService(echo_pb2_grpc.EchoServiceServicer):
    def UnaryEcho(self, request, context):
        time.sleep(0.1)
        return echo_pb2.EchoReply(message=f"Unary: {request.message}")

    def ServerStreamingEcho(self, request, context):
        for i in range(5):
            time.sleep(0.1)
            yield echo_pb2.EchoReply(message=f"Stream {i}: {request.message}")

    def ClientStreamingEcho(self, request_iterator, context):
        messages = []
        for request in request_iterator:
            messages.append(request.message)

        return echo_pb2.EchoReply(message=f"Received {len(messages)} messages: {', '.join(messages)}")

    def BidirectionalStreamingEcho(self, request_iterator, context):
        for request in request_iterator:
            yield echo_pb2.EchoReply(message=f"Bidi: {request.message}")


def serve():
    metrics = PrometheusMetrics(service_name="grpc-server-foo", version="19.0.2", env="prod")
    start_http_server(8000, registry=metrics.get_registry())
    print("Metrics server started on port 8000")

    interceptor = create_server_metrics_interceptor(metrics)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=[interceptor])

    echo_pb2_grpc.add_EchoServiceServicer_to_server(EchoService(), server)
    listen_addr = "[::]:50051"
    server.add_insecure_port(listen_addr)

    print(f"Starting gRPC server on {listen_addr}")
    server.start()
    server.wait_for_termination()


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    serve()
