from fastapi.testclient import TestClient

from govcrawler.api import app
from govcrawler.observability import (
    ARTICLES_NEW,
    BROWSER_LAUNCHES,
    HTTP_BLOCK_TOTAL,
    record_browser_launch,
    record_fetch,
)


def _counter_value(metric, **labels) -> float:
    return metric.labels(**labels)._value.get()


def test_record_fetch_ready_increments_articles_new():
    before = _counter_value(ARTICLES_NEW, site_id="gdqy", column_id="szfwj")
    record_fetch(
        site_id="gdqy", column_id="szfwj", strategy="httpx",
        outcome="ready", duration_ms=120, http_status=200,
    )
    after = _counter_value(ARTICLES_NEW, site_id="gdqy", column_id="szfwj")
    assert after == before + 1


def test_record_fetch_412_increments_block_counter():
    before = _counter_value(HTTP_BLOCK_TOTAL, site_id="gdqy", status="412")
    record_fetch(
        site_id="gdqy", column_id="szfwj", strategy="httpx",
        outcome="challenge", duration_ms=50, http_status=412,
    )
    after = _counter_value(HTTP_BLOCK_TOTAL, site_id="gdqy", status="412")
    assert after == before + 1


def test_record_browser_launch():
    before = _counter_value(BROWSER_LAUNCHES, site_id="www.gdqy.gov.cn")
    record_browser_launch("www.gdqy.gov.cn")
    after = _counter_value(BROWSER_LAUNCHES, site_id="www.gdqy.gov.cn")
    assert after == before + 1


def test_metrics_endpoint_serves_text():
    # ensure at least one datapoint exists
    record_fetch(
        site_id="gdqy", column_id="szfwj", strategy="httpx",
        outcome="ready", duration_ms=100, http_status=200,
    )
    r = TestClient(app).get("/metrics")
    assert r.status_code == 200
    assert "text/plain" in r.headers["content-type"]
    body = r.text
    assert "govcrawler_fetch_total" in body
    assert "govcrawler_fetch_duration_seconds" in body
    assert "govcrawler_articles_new_total" in body


def test_metrics_endpoint_includes_http_block_counter():
    record_fetch(
        site_id="gdqy", column_id="szfwj", strategy="httpx",
        outcome="failed", duration_ms=30, http_status=403,
    )
    body = TestClient(app).get("/metrics").text
    assert 'govcrawler_http_block_total{site_id="gdqy",status="403"}' in body
