"""Read-only queries on the agents directory (agents.db) for the CRM web layer; the web layer must not run SQL itself (contract K4).

Live (uncached) reads. Kept apart from agent_queries.py, whose function bodies are frozen by the Website split contract.
"""
from modules.classes import DatabaseConnectionManager


def list_active_agent_ids():
    """Return the ids of all active agents (is_active = 1), in the order the database returns them."""
    with DatabaseConnectionManager('agents') as conn:
        if conn is None:
            return []
        cursor = conn.cursor()
        cursor.execute("SELECT id FROM agents_v2 WHERE is_active = 1")
        return [row[0] for row in cursor.fetchall()]


def list_active_agent_rows_for_clients():
    """Return raw rows (id, first_name, last_name, access_level) of the active agents with id >= 101, ordered by last then first name.

    COALESCE(access_level, 'agent') is applied by the query; the caller shapes the rows.
    """
    with DatabaseConnectionManager("agents") as conn:
        return conn.cursor().execute(
            """
            SELECT id, first_name, last_name, COALESCE(access_level, 'agent')
            FROM agents_v2
            WHERE is_active = 1
              AND id >= 101
            ORDER BY last_name, first_name
            """
        ).fetchall()
