"""Reader for moodtracker's own SQLite file (the mood.alogins.net source DB).

moodtracker's schema (see /home/alvis/moodtracker/app.py):

    CREATE TABLE entries (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        ts TEXT NOT NULL,
        mood INTEGER NOT NULL,
        tags TEXT NOT NULL,      -- JSON array, e.g. '["sad","tired"]'
        note TEXT,
        affirmation TEXT
    )

We open it read-only (URI mode=ro) so this archiver can never corrupt or lock
the live app's database.
"""
import sqlite3


def connect_source(path):
    """Read-only connection to the moodtracker SQLite file."""
    conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
    conn.row_factory = sqlite3.Row
    return conn


def fetch_entries_since(source_conn, since_id=0, limit=100000):
    """Entries with id > since_id, oldest first."""
    rows = source_conn.execute(
        """SELECT id, ts, mood, tags, note, affirmation
           FROM entries WHERE id > ? ORDER BY id ASC LIMIT ?""",
        (since_id, limit),
    ).fetchall()
    return [dict(r) for r in rows]
