from promrs import CollectorRegistry, Histogram, generate_latest


def test_histogram_observe() -> None:
    registry = CollectorRegistry()
    h = Histogram(
        "request_duration_seconds",
        "Request duration",
        ["method"],
        registry=registry,
        buckets=[0.01, 0.05, 0.1, 0.5, 1.0, 5.0],
    )
    h.labels(method="GET").observe(0.042)
    output = generate_latest(registry).decode()
    assert "request_duration_seconds" in output
    assert 'method="GET"' in output


def test_histogram_bucket_counts() -> None:
    registry = CollectorRegistry()
    h = Histogram("latency", "Latency", ["op"], registry=registry, buckets=[0.1, 0.5, 1.0])
    h.labels(op="read").observe(0.05)
    h.labels(op="read").observe(0.3)
    h.labels(op="read").observe(0.8)
    output = generate_latest(registry).decode()
    # OpenMetrics sorts labels alphabetically: le comes before op
    assert 'latency_bucket{le="0.1",op="read"} 1' in output
    assert 'latency_bucket{le="0.5",op="read"} 2' in output
    assert 'latency_bucket{le="1.0",op="read"} 3' in output
    assert 'latency_bucket{le="+Inf",op="read"} 3' in output


def test_histogram_sum_and_count() -> None:
    registry = CollectorRegistry()
    h = Histogram("duration", "Duration", ["stage"], registry=registry, buckets=[1.0, 5.0])
    h.labels(stage="init").observe(2.0)
    h.labels(stage="init").observe(3.0)
    output = generate_latest(registry).decode()
    assert 'duration_sum{stage="init"} 5.0' in output
    assert 'duration_count{stage="init"} 2' in output


def test_histogram_default_buckets() -> None:
    registry = CollectorRegistry()
    h = Histogram("default_hist", "Test default buckets", ["k"], registry=registry)
    h.labels(k="v").observe(0.042)
    output = generate_latest(registry).decode()
    assert 'default_hist_bucket{le="0.005",k="v"} 0' in output
    assert 'default_hist_bucket{le="10.0",k="v"} 1' in output
    assert 'default_hist_bucket{le="+Inf",k="v"} 1' in output


def test_histogram_multiple_label_values() -> None:
    registry = CollectorRegistry()
    h = Histogram("req", "req", ["method"], registry=registry, buckets=[1.0])
    h.labels(method="GET").observe(0.5)
    h.labels(method="POST").observe(0.5)
    output = generate_latest(registry).decode()
    assert 'req_bucket{le="1.0",method="GET"} 1' in output
    assert 'req_bucket{le="1.0",method="POST"} 1' in output
