import asyncio
import os

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.aio import create_client_metrics_interceptor



async def generate_requests():
    for i in range(3):
        yield echo_pb2.EchoRequest(message=f"Stream Msg {i}")
        await asyncio.sleep(0.1)


async def run():
    metrics = PrometheusMetrics(service_name="async-client-grpc-foo", version="91.1.2", env="dev")
    start_http_server(8001, registry=metrics.get_registry())
    print("Client metrics server started on port 8001")
    interceptors = create_client_metrics_interceptor(metrics)
    address = os.getenv("GRPC_ASYNC_SERVER", "localhost:50051")
    async with grpc.aio.insecure_channel(address, interceptors=(*interceptors,)) as channel:
        stub = echo_pb2_grpc.EchoServiceStub(channel)
        while True:
            print("--- Unary ---")
            response = await stub.UnaryEcho(echo_pb2.EchoRequest(message="Hello"))
            print(f"Response: {response.message}")

            print("\n--- Server Streaming ---")
            async for response in stub.ServerStreamingEcho(echo_pb2.EchoRequest(message="StreamMe")):
                print(f"Received: {response.message}")

            print("\n--- Client Streaming ---")
            response = await stub.ClientStreamingEcho(generate_requests())
            print(f"Summary: {response.message}")

            print("\n--- Bidi Streaming ---")
            async for response in stub.BidirectionalStreamingEcho(generate_requests()):
                print(f"Bidi Recv: {response.message}")

            print("\nDone. Wait next send")
            await asyncio.sleep(300)


if __name__ == "__main__":
    asyncio.run(run())
