"""Read-only queries on `platform_logs` for the CRM (leads panel and inbox sync); the web layer must not run SQL itself (contract K4).

Owner of the table and of every write: `InvestmentWebsite/services/platform_logger.py`. The CRM only reads. The database file is
resolved on every call through `storage_paths.platform_logs_db_path()`. SQL, ordering and connection handling are exactly those the
CRM used before the move.
"""
import sqlite3

from modules.core import storage_paths


def list_platform_log_rows():
    """All platform log rows (id, created_at, log_type, path, status, payload), newest id first, as sqlite3.Row; `[]` when the database
    file does not exist. Opens its own connection; a missing table raises sqlite3.OperationalError."""
    db_path = storage_paths.platform_logs_db_path()
    if not db_path.exists():
        return []

    with sqlite3.connect(str(db_path)) as conn:
        conn.row_factory = sqlite3.Row
        rows = conn.execute(
            """
            SELECT id, created_at, log_type, path, status, payload
            FROM platform_logs
            ORDER BY id DESC
            """
        ).fetchall()
    return rows


def list_lead_log_rows_after(conn, last_platform_log_id):
    """Lead log rows (id, created_at, payload) with id > `last_platform_log_id`, oldest first, read on the caller's connection
    (the inbox sync runs it in the same transaction in which it writes `lead_inbox`)."""
    return conn.execute(
        """
        SELECT id, created_at, payload
        FROM platform_logs
        WHERE id > ? AND log_type = 'leads'
        ORDER BY id ASC
        """,
        (last_platform_log_id,),
    ).fetchall()
