| 248 | |
| 249 | |
| 250 | def get_or_create_practice_session( |
| 251 | session: Session, collection_id: uuid.UUID, user_id: uuid.UUID |
| 252 | ) -> PracticeSession: |
| 253 | existing_session = _get_uncompleted_session(session, collection_id, user_id) |
| 254 | if existing_session: |
| 255 | if existing_session.cards_practiced == 0: |
| 256 | session.delete(existing_session) |
| 257 | session.commit() |
| 258 | else: |
| 259 | return existing_session |
| 260 | |
| 261 | cards = _get_collection_cards(session, collection_id) |
| 262 | if not cards: |
| 263 | raise EmptyCollectionError( |
| 264 | "Cannot create practice session for empty collection" |
| 265 | ) |
| 266 | |
| 267 | practice_session = PracticeSession( |
| 268 | collection_id=collection_id, |
| 269 | user_id=user_id, |
| 270 | total_cards=len(cards), |
| 271 | ) |
| 272 | session.add(practice_session) |
| 273 | session.flush() |
| 274 | |
| 275 | _create_practice_cards(session, practice_session, cards) |
| 276 | |
| 277 | session.commit() |
| 278 | session.refresh(practice_session) |
| 279 | return practice_session |
| 280 | |
| 281 | |
| 282 | def get_practice_cards( |