import os
import time
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_client_metrics_interceptor


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


def run():
    metrics = PrometheusMetrics(service_name="grpc-client-foo", version="43.1.9", env="prod")
    start_http_server(8001, registry=metrics.get_registry())
    print("Client metrics server started on port 8001")
    interceptor = create_client_metrics_interceptor(metrics)
    address = os.getenv("GRPC_SERVER", "localhost:50051")
    with grpc.insecure_channel(address) as base_channel:
        channel = grpc.intercept_channel(base_channel, interceptor)
        stub = echo_pb2_grpc.EchoServiceStub(channel)

        while True:
            print("--- Unary ---")
            response = stub.UnaryEcho(echo_pb2.EchoRequest(message="Hello"))
            print(f"Response: {response.message}")

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

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

            print("\n--- Bidi Streaming ---")
            for response in stub.BidirectionalStreamingEcho(generate_requests()):
                print(f"Bidi Recv: {response.message}")
            print("\nDone. Wait next send")
            time.sleep(300)


if __name__ == "__main__":
    run()
