# Code generated by sqlc. DO NOT EDIT.
# versions:
#   sqlc v1.29.0
# source: advance_stuck_workflows.sql
import dataclasses

import sqlalchemy
import sqlalchemy.ext.asyncio

from . import models


ADVANCE_STUCK_WORKFLOWS = """-- name: advance_stuck_workflows \\:exec
  WITH stuck_workflows AS (
      -- Find workflow runs that are stuck in RUNNING state with no recent heartbeat
      SELECT wr.id AS workflow_run_id
      FROM hyrex_workflow_run wr
      WHERE wr.status = 'RUNNING'\\:\\:workflow_run_status
        AND wr.last_heartbeat < NOW() - INTERVAL '5 minutes'  -- No heartbeat in 5 minutes
      LIMIT 100  -- Process in batches to avoid long-running transactions
  ),
  updated_statuses AS (
      -- First update workflow status based on current task states
      SELECT set_workflow_run_status_based_on_task_runs(sw.workflow_run_id)
      FROM stuck_workflows sw
  ),
  advanced AS (
      -- Then try to advance any workflows still in RUNNING state
      SELECT advance_workflow_run(sw.workflow_run_id)
      FROM stuck_workflows sw
      JOIN hyrex_workflow_run wr ON wr.id = sw.workflow_run_id
      WHERE wr.status = 'RUNNING'\\:\\:workflow_run_status
  )
  SELECT COUNT(*) FROM stuck_workflows
"""


@dataclasses.dataclass()
class advance_stuck_workflowsParams:

    pass

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

    def advance_stuck_workflows(self, arg: advance_stuck_workflowsParams) -> None:
        self._conn.execute(sqlalchemy.text(ADVANCE_STUCK_WORKFLOWS))


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

    async def advance_stuck_workflows(self, arg: advance_stuck_workflowsParams) -> None:
        await self._conn.execute(sqlalchemy.text(ADVANCE_STUCK_WORKFLOWS))
