import pytest

from promrs import CollectorRegistry, Counter, Gauge, Histogram, generate_latest


def test_counter_positional_labels() -> None:
    registry = CollectorRegistry()
    c = Counter("pos_counter", "test", ["method", "endpoint"], registry=registry)
    c.labels("GET", "/api").inc()
    output = generate_latest(registry).decode()
    # Labels are sorted alphabetically in output
    assert 'pos_counter_total{endpoint="/api",method="GET"} 1.0' in output


def test_gauge_positional_labels() -> None:
    registry = CollectorRegistry()
    g = Gauge("pos_gauge", "test", ["host", "core"], registry=registry)
    g.labels("srv1", "0").set(45.0)
    output = generate_latest(registry).decode()
    assert 'pos_gauge{core="0",host="srv1"} 45.0' in output


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


def test_positional_and_keyword_mixed_raises() -> None:
    registry = CollectorRegistry()
    c = Counter("mix_counter", "test", ["method", "endpoint"], registry=registry)
    with pytest.raises(ValueError, match="Cannot use both"):
        c.labels("GET", endpoint="/api")


def test_positional_wrong_count_raises() -> None:
    registry = CollectorRegistry()
    c = Counter("wrong_count", "test", ["method", "endpoint"], registry=registry)
    with pytest.raises(ValueError, match="Expected 2"):
        c.labels("GET")


def test_keyword_labels_still_work() -> None:
    registry = CollectorRegistry()
    c = Counter("kw_counter", "test", ["method"], registry=registry)
    c.labels(method="POST").inc(3.0)
    output = generate_latest(registry).decode()
    assert 'kw_counter_total{method="POST"} 3.0' in output


def test_positional_and_keyword_same_result() -> None:
    """Positional and keyword labels should produce the same metric entry."""
    registry = CollectorRegistry()
    c = Counter("mixed_counter", "test", ["method", "endpoint"], registry=registry)
    c.labels("GET", "/api").inc()
    c.labels(method="GET", endpoint="/api").inc()
    output = generate_latest(registry).decode()
    # Both increments should go to the same metric
    assert 'mixed_counter_total{endpoint="/api",method="GET"} 2.0' in output
