from dataclasses import dataclass, field
from datetime import datetime, timedelta
import httpx
from maur.grafana.schemas import Alert
from maur.grafana.settings import LokiSettings


def to_nanotimestamp(value: datetime) -> int:
    return int(value.timestamp() * 1e9)

@dataclass
class LokiClient:

    settings: LokiSettings = field(default_factory=LokiSettings.from_env)

    async def logs_for_alert(self, alert: Alert) -> list[str]:

        label_filter = " ".join(f'{label}="{value}"' for label, value in alert.labels.items())

        start_timestamp = to_nanotimestamp(alert.starts_at - timedelta(minutes=1))
        end_timestamp = to_nanotimestamp(alert.starts_at + timedelta(minutes=1))

        async with httpx.AsyncClient(base_url=self.settings.loki_url.encoded_string()) as client:

            res = await client.get("/loki/api/v1/query_range", params={
                "query": f'{{{label_filter}}} |= "Traceback"',
                "start": start_timestamp,
                "end": end_timestamp,
                "limit": 100,
            })
            res.raise_for_status()

        lines = []
        for stream in res.json()["data"]["result"]:
            for _, line in stream["values"]:
                lines.append(line)
        return lines
