"""Shared helpers for agent session management."""

from __future__ import annotations


async def mark_stale_sessions_timeout(db) -> int:
    """Mark agent_sessions stuck in 'running' for over 1 hour as 'timeout'."""
    cursor = await db.execute(
        "UPDATE agent_sessions"
        " SET status = 'timeout',"
        "     ended_at = COALESCE(ended_at, CURRENT_TIMESTAMP),"
        "     duration_seconds = ROUND(EXTRACT(EPOCH FROM (COALESCE(ended_at, CURRENT_TIMESTAMP) - started_at))::numeric, 2),"
        "     updated_at = CURRENT_TIMESTAMP"
        " WHERE status = 'running' AND created_at < NOW() - INTERVAL '1 hour'",
    )
    await db.commit()
    return cursor.rowcount
