from uuid import UUID from sqlalchemy import func, select from app.common.base_repository import BaseRepository from app.modules.sessions.models import SwingSession class SwingReportRepository(BaseRepository[SwingSession]): model = SwingSession async def get_for_update(self, session_id: UUID) -> SwingSession | None: """The live session row, locked until the request commits, so concurrent posts for one session serialize.""" result = await self.session.execute( select(SwingSession).where(SwingSession.id == session_id, SwingSession.deleted_at.is_(None)) .with_for_update()) return result.scalars().first() async def next_queued(self) -> SwingSession | None: """The oldest queued session no other worker holds, locked until this worker commits.""" return await self.session.scalar( select(SwingSession).where(SwingSession.queued_payload.is_not(None), SwingSession.deleted_at.is_(None)) .order_by(SwingSession.created_at, SwingSession.id).limit(1).with_for_update(skip_locked=True)) async def queued_first_reports(self, owner_id: UUID, except_id: UUID) -> int: """Queued sessions that will each use one analysis from the plan once they are built.""" return await self.session.scalar(select(func.count()).where( SwingSession.owner_id == owner_id, SwingSession.queued_payload.is_not(None), SwingSession.analyzed_at.is_(None), SwingSession.deleted_at.is_(None), SwingSession.id != except_id)) or 0 async def previous_report(self, session: SwingSession, practice_type: str | None) -> SwingSession | None: """The same player's latest earlier report for the same drill (their own reps only).""" return await self.session.scalar(select(SwingSession).where( SwingSession.owner_id == session.owner_id, SwingSession.is_self.is_(True), SwingSession.mode == session.mode, SwingSession.report.is_not(None), SwingSession.deleted_at.is_(None), SwingSession.created_at < session.created_at, SwingSession.measurement_payload["context"]["practice_type"].astext == practice_type, ).order_by(SwingSession.created_at.desc()).limit(1))