"""Teaching implementation: one process, SQLite storage, an injected clock."""
import sqlite3


class ReservationStore:
    """Replay a retained key; create a reservation when the key has expired."""

    def __init__(self, retention_hours):
        self.retention_hours = retention_hours
        self.db = sqlite3.connect(":memory:")
        self.db.execute("CREATE TABLE reservations (id INTEGER PRIMARY KEY)")
        self.db.execute(
            "CREATE TABLE retry_keys (key TEXT PRIMARY KEY, reservation_id INTEGER, expires REAL)"
        )

    # Implements: SW-REQ-241
    def reserve(self, key, now_hours):
        row = self.db.execute(
            "SELECT reservation_id FROM retry_keys WHERE key = ? AND expires > ?",
            (key, now_hours),
        ).fetchone()
        if row:
            return row[0]
        cursor = self.db.execute("INSERT INTO reservations DEFAULT VALUES")
        reservation_id = cursor.lastrowid
        self.db.execute(
            "INSERT OR REPLACE INTO retry_keys VALUES (?, ?, ?)",
            (key, reservation_id, now_hours + self.retention_hours),
        )
        self.db.commit()
        return reservation_id

    def count(self):
        return self.db.execute("SELECT COUNT(*) FROM reservations").fetchone()[0]

    def close(self):
        self.db.close()
