# Code generated by sqlc. DO NOT EDIT.
# versions:
#   sqlc v1.29.0
# source: aggregate_dequeue_latency_by_minute.sql
import dataclasses
from typing import Any, AsyncIterator, Iterator

import sqlalchemy
import sqlalchemy.ext.asyncio

from . import models


AGGREGATE_DEQUEUE_LATENCY_BY_MINUTE = """-- name: aggregate_dequeue_latency_by_minute \\:many
WITH metric_data AS (
  -- Extract the dequeueLatencyMs JSON array from the stats column
  SELECT 
    id AS executor_id,
    jsonb_array_elements(
      (stats->>'dequeueLatencyMs')\\:\\:jsonb
    ) AS latency_entry
  FROM hyrex_executor
  WHERE 
    stats IS NOT NULL 
    AND stats->>'dequeueLatencyMs' IS NOT NULL
),
parsed_metrics AS (
  -- Parse the minute timestamp and average value from each entry
  SELECT 
    executor_id,
    to_timestamp((latency_entry->>'minute')\\:\\:bigint / 1000) AS minute_timestamp,
    (latency_entry->>'average')\\:\\:numeric AS avg_latency
  FROM metric_data
)
SELECT 
  minute_timestamp,
  AVG(avg_latency)\\:\\:float8 AS avg_dequeue_latency_ms
FROM parsed_metrics
GROUP BY minute_timestamp
ORDER BY minute_timestamp DESC
"""


@dataclasses.dataclass()
class AggregateDequeueLatencyByMinuteParams:

    pass

@dataclasses.dataclass()
class AggregateDequeueLatencyByMinuteRow:
    minute_timestamp: Any
    avg_dequeue_latency_ms: float


class Querier:
    def __init__(self, conn: sqlalchemy.engine.Connection):
        self._conn = conn

    def aggregate_dequeue_latency_by_minute(self, arg: AggregateDequeueLatencyByMinuteParams) -> Iterator[AggregateDequeueLatencyByMinuteRow]:
        result = self._conn.execute(sqlalchemy.text(AGGREGATE_DEQUEUE_LATENCY_BY_MINUTE))
        for row in result:
            yield AggregateDequeueLatencyByMinuteRow(
                minute_timestamp=row[0],
                avg_dequeue_latency_ms=row[1],
            )


class AsyncQuerier:
    def __init__(self, conn: sqlalchemy.ext.asyncio.AsyncConnection):
        self._conn = conn

    async def aggregate_dequeue_latency_by_minute(self, arg: AggregateDequeueLatencyByMinuteParams) -> AsyncIterator[AggregateDequeueLatencyByMinuteRow]:
        result = await self._conn.stream(sqlalchemy.text(AGGREGATE_DEQUEUE_LATENCY_BY_MINUTE))
        async for row in result:
            yield AggregateDequeueLatencyByMinuteRow(
                minute_timestamp=row[0],
                avg_dequeue_latency_ms=row[1],
            )
