from __future__ import annotations

import pytest

from src.services.signoz_client import SignOzClient


@pytest.mark.asyncio
async def test_get_logs_uses_live_signoz_v2_table(monkeypatch) -> None:
    client = SignOzClient()
    queries: list[str] = []

    async def fake_query(query: str) -> list[dict]:
        queries.append(query)
        return [
            {
                "timestamp": 1,
                "severity_text": "ERROR",
                "body": "boom",
                "resources": {"service.name": "ollama"},
                "attributes": {"container.name": "ollama"},
                "trace_id": "trace-1",
                "span_id": "span-1",
            }
        ]

    monkeypatch.setattr(client, "_query_clickhouse", fake_query)

    logs = await client.get_logs(
        service_name="ollama",
        severity="ERROR",
        search_text="HostErrorLogFlood",
        time_window_minutes=5,
        limit=3,
    )

    assert logs[0]["service"] == "ollama"
    assert "FROM signoz_logs.distributed_logs_v2" in queries[0]
    assert "resources_string['service.name'] = 'ollama'" in queries[0]
    assert "attributes_string AS attributes" in queries[0]


@pytest.mark.asyncio
async def test_error_logs_summary_uses_live_signoz_v2_table(monkeypatch) -> None:
    client = SignOzClient()
    queries: list[str] = []

    async def fake_query(query: str) -> list[dict]:
        queries.append(query)
        return [{"severity_text": "ERROR", "count": 2, "sample_message": "boom"}]

    monkeypatch.setattr(client, "_query_clickhouse", fake_query)

    summary = await client.get_error_logs_summary(
        service_name="ollama",
        time_window_minutes=5,
    )

    assert summary["total_errors"] == 2
    assert "FROM signoz_logs.distributed_logs_v2" in queries[0]
    assert "resources_string['service.name'] = 'ollama'" in queries[0]
