import time
import httpx

url_root = "http://127.0.0.1:8000/"
url_health = "http://127.0.0.1:8000/health"

def test_latency(url, label):
    # Use httpx.Client() to reuse TCP connection (connection pool)
    with httpx.Client() as client:
        # Warmup connection
        try:
            client.get(url)
        except Exception as e:
            print(f"Failed to connect: {e}")
            return

        latencies = []
        for _ in range(5):
            start = time.perf_counter()
            client.get(url)
            end = time.perf_counter()
            latencies.append((end - start) * 1000)
        
        avg_latency = sum(latencies) / len(latencies)
        print(f"{label} average latency over 5 requests (connection reused): {avg_latency:.2f} ms")
        for idx, lat in enumerate(latencies):
            print(f"  Request {idx + 1}: {lat:.2f} ms")

if __name__ == "__main__":
    test_latency(url_root, "Root Endpoint (/)")
    test_latency(url_health, "Health Endpoint (/health)")
    test_latency("http://127.0.0.1:8000/db-test", "DB Test Endpoint (/db-test)")
