"""H1: validate the ML payload, build the swing or pitch report with the ai_coach library and save both on the session. Hitting sessions (mode "h") take swing contract 1.0/1.1; pitching sessions (mode "p") take pitch-1.1. Pitch-1.1 coaching uses only structured ML evidence. Revision rules: the same analysis_id and revision returns the stored report (no rebuild, no model call); a lower revision is refused (STALE_REVISION); a higher one rebuilds and replaces; another analysis_id is refused (ANALYSIS_MISMATCH). Only the first report of a session counts toward the plan. An obsolete pitch-1.1 report is rebuilt from the same saved measurements to remove legacy visual coaching. With queue=True (the endpoints' default) the same checks run in the request, but the build is left to the report worker (queue.py): the payload is stored on the session, the request returns at once and the owner is notified when the report is saved. """ import asyncio import logging from collections.abc import Callable from dataclasses import dataclass from datetime import UTC, datetime from typing import Any from uuid import UUID from ai_coach.config import get_settings as get_coach_settings from ai_coach.pitch_report import build_pitch_report, validate_pitch_payload from ai_coach.swing_report import AthleteContext, InvalidPayload, PreviousSession, build_report, validate_payload from sqlalchemy.ext.asyncio import AsyncSession from app.common.consent import analysis_consent_blocked from app.common.notify import notify from app.core.config import get_settings from app.core.errors import Conflict, Forbidden, NotFound, PlanLimitReached, ServiceUnavailable, Unprocessable from app.integrations.pitching_reports import obsolete_pitch_coaching from app.integrations.push import PushClient from app.modules.accounts.models import Account from app.modules.billing.entitlement import EntitlementService from app.modules.sessions.models import SwingSession from app.modules.swing_reports.repository import SwingReportRepository LEVELS = ("youth", "high_school", "college", "adult") HANDS = {"R": "right", "L": "left"} ReportBuilder = Callable[..., dict] log = logging.getLogger(__name__) def athlete_context(snapshot: dict | None) -> AthleteContext: """Session athlete snapshot -> library context. Switch hitters (S) have no fixed side; the payload says which.""" snapshot = snapshot or {} level = snapshot.get("level") height = snapshot.get("height_cm") try: height_cm = float(height) if height is not None else None except (TypeError, ValueError): height_cm = None return AthleteContext(batting_hand=HANDS.get(snapshot.get("bats")), # type: ignore[arg-type] throwing_hand=HANDS.get(snapshot.get("throws")), # type: ignore[arg-type] level=level if level in LEVELS else None, height_cm=height_cm) def ensure_coach_configured() -> None: """The coaching text must come from Gemini: a missing key is a configuration error, never a silent fallback. Tests (ENV=test) are exempt so they never call the model. """ if get_settings().env != "test" and not get_coach_settings().llm_enabled: raise ServiceUnavailable("The AI coach is not configured. Please try again later.", code="COACH_NOT_CONFIGURED") def swing_marks(events: Any) -> dict: """Hitting events -> the session marks the app draws on the clip.""" marks: dict = {} for event_name, mark_name in (("stride_start", "stride_start_frame"), ("front_foot_down", "stride_end_frame"), ("contact", "contact_frame")): event = getattr(events, event_name) if event.status != "unavailable" and event.source_frame_index is not None: marks[mark_name] = event.source_frame_index if event_name == "contact": marks["contact_offset"] = 0 marks["contact_source"] = "manual" if event.source == "manual_review" else "detected" return marks def pitch_marks(events: Any) -> dict: """Pitching events -> session marks (peak_knee_height_frame, foot_plant_frame, ball_release_frame).""" marks: dict = {} if hasattr(events, "release"): # Null overwrites an earlier mark when a reviewed revision removes it. return {f"{name}_frame": getattr(events, name).source_frame_index for name in ("leg_lift", "foot_strike", "release")} for event_name in ("peak_knee_height", "foot_plant", "ball_release"): event = getattr(events, event_name) if event is not None and event.status != "unavailable" and event.source_frame_index is not None: marks[f"{event_name}_frame"] = event.source_frame_index return marks @dataclass(frozen=True) class ReportKind: mode: str # session mode this report is for validate: Callable[[Any], tuple[Any, dict[str, str]]] contract: str # named in the INVALID_PAYLOAD message mode_message: str marks: Callable[[Any], dict] SWING = ReportKind(mode="h", validate=validate_payload, contract="swing analysis contract 1.0 or 1.1", mode_message="Swing reports are for hitting sessions.", marks=swing_marks) PITCH = ReportKind(mode="p", validate=validate_pitch_payload, contract="pitch analysis contract pitch-1.1", mode_message="Pitch reports are for pitching sessions.", marks=pitch_marks) class SwingReportService: def __init__(self, db: AsyncSession, builder: ReportBuilder | None = None, pitch_builder: ReportBuilder | None = None): self.db = db self.sessions = SwingReportRepository(db) self.entitlements = EntitlementService(db) self.builder = builder or build_report self.pitch_builder = pitch_builder or build_pitch_report async def create(self, account: Account, session_id: UUID, payload: Any, request_id: str | None, *, queue: bool = False) -> dict | None: """The report, or None when it was queued (queue=True and a build is needed).""" return await self._create(SWING, self.builder, account, session_id, payload, request_id, queue) async def create_pitch(self, account: Account, session_id: UUID, payload: Any, request_id: str | None, *, queue: bool = False) -> dict | None: return await self._create(PITCH, self.pitch_builder, account, session_id, payload, request_id, queue) async def build_next_queued(self, push: PushClient | None) -> bool: """Worker step: build the oldest queued report, save it and tell the owner. False when nothing is queued. The row stays locked for the whole build, so a crash leaves the session queued for the next worker. """ session = await self.sessions.next_queued() if session is None: return False kind, builder = (PITCH, self.pitch_builder) if session.mode == "p" else (SWING, self.builder) payload, noun = session.queued_payload, "pitch" if session.mode == "p" else "swing" try: parsed, problems = kind.validate(payload) if parsed is None: raise InvalidPayload(problems) report = await asyncio.to_thread(builder, payload, athlete_context(session.athlete), request_id=f"queue-{session.id}", **await self._history(session, payload)) except Exception: # Failed builds leave the queue, so one bad payload cannot block it; the app posts again to retry. log.exception("queued report for session %s failed", session.id) await self.sessions.update(session, queued_payload=None, report_error="REPORT_FAILED") outcome, title, body = "failed", f"We couldn't finish your {noun} report", "Open the app to try again." else: await self._save(session, kind, parsed, payload, report) outcome, title, body = "ready", f"Your {noun} report is ready", "Tap to see your score and focus." await notify(self.db, push, session.owner_id, kind="result", title=title, body=body, target={"session_id": session.id, "mode": session.mode, "outcome": outcome}, event_key=f"report:{session.id}:{(payload or {}).get('analysis_revision')}:{outcome}") return True async def retry_pitch_coaching(self, account: Account, session_id: UUID, request_id: str | None, *, refresh: bool = False) -> dict: """Retry unavailable/obsolete text without rerunning ML or consuming another analysis.""" session = await self.sessions.get_for_update(session_id) if session is None: raise NotFound("We couldn't find that session.") if session.owner_id != account.id: raise Forbidden() if session.mode != "p": raise Unprocessable("Pitch coaching is for pitching sessions.", code="MODE_NOT_SUPPORTED") if not session.report or not session.measurement_payload: raise Conflict("Complete the motion analysis first.", code="REPORT_NOT_READY") if session.measurement_payload.get("schema_version") != "pitch-1.1": raise Unprocessable("This saved report does not support coaching retry.", code="MODE_NOT_SUPPORTED") if ((session.report.get("coaching") or {}).get("status") == "generated" and not refresh and not obsolete_pitch_coaching(session.report)): return session.report if await analysis_consent_blocked(self.db, account.id, get_settings().require_analysis_consent): raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED") ensure_coach_configured() try: report = await asyncio.to_thread(self.pitch_builder, session.measurement_payload, athlete_context(session.athlete), request_id=request_id) except InvalidPayload as exc: raise Unprocessable(str(exc), code="INVALID_PAYLOAD", fields=exc.problems) from exc await self.sessions.update(session, report=report) return report async def _create(self, kind: ReportKind, builder: ReportBuilder, account: Account, session_id: UUID, payload: Any, request_id: str | None, queue: bool = False) -> dict | None: session = await self.sessions.get_for_update(session_id) if session is None: raise NotFound("We couldn't find that session.") if session.owner_id != account.id: raise Forbidden() if session.mode != kind.mode: raise Unprocessable(kind.mode_message, code="MODE_NOT_SUPPORTED") # Validation is cheap and runs first, so a broken payload never reaches the plan check or the model. parsed, problems = kind.validate(payload) if parsed is None: raise Unprocessable(f"The payload does not follow {kind.contract}.", code="INVALID_PAYLOAD", fields=problems) evidence_pitch = kind.mode == "p" and parsed.schema_version == "pitch-1.1" if evidence_pitch and parsed.pitch_id != str(session_id): raise Unprocessable("The pitch ID must match this session.", code="PITCH_ID_MISMATCH") if session.report is not None: if session.analysis_id != parsed.analysis_id: raise Conflict("This session already has a report for a different analysis.", code="ANALYSIS_MISMATCH") if parsed.analysis_revision == session.analysis_revision: if evidence_pitch and session.measurement_payload != payload: raise Conflict("This revision already has a different payload.", code="REVISION_PAYLOAD_MISMATCH") if not evidence_pitch or not obsolete_pitch_coaching(session.report): return session.report if parsed.analysis_revision < (session.analysis_revision or 0): raise Conflict("A newer revision of this analysis has already been reported.", code="STALE_REVISION") if await analysis_consent_blocked(self.db, account.id, get_settings().require_analysis_consent): raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED") ensure_coach_configured() if session.analyzed_at is None: entitlement = await self.entitlements.get(account.id) # Queued first reports have not been counted yet, so they are reserved here. # shortcut: two posts for different sessions at the same instant can each take the last analysis; # lock the account row here if the limit must be exact. waiting = await self.sessions.queued_first_reports(account.id, session.id) if queue else 0 if entitlement.left is not None and entitlement.left - waiting <= 0: raise PlanLimitReached() if queue: await self.sessions.update(session, queued_payload=payload, report_error=None) return None try: report = await asyncio.to_thread(builder, payload, athlete_context(session.athlete), request_id=request_id, **await self._history(session, payload)) except InvalidPayload as exc: # defensive: the builder re-validates raise Unprocessable(str(exc), code="INVALID_PAYLOAD", fields=exc.problems) from exc await self._save(session, kind, parsed, payload, report) return report async def _history(self, session: SwingSession, payload: Any) -> dict: """Builder arguments for "since last time" wording: the player's previous hitting report for the same drill. Only for the account's own reps: a rep recorded for someone else does not say reliably who the athlete is. """ if session.mode != "h" or not session.is_self: return {} practice_type = ((payload or {}).get("context") or {}).get("practice_type") previous = await self.sessions.previous_report(session, practice_type) if previous is None: return {} return {"previous": PreviousSession(report=previous.report, days_ago=(session.created_at - previous.created_at).days)} async def _save(self, session: SwingSession, kind: ReportKind, parsed: Any, payload: Any, report: dict) -> None: marks = {**(session.marks or {}), **kind.marks(parsed.events)} if kind.mode == "p" and parsed.schema_version == "pitch-1.1": for key in ("contact_frame", "contact_offset", "contact_source", "stride_start_frame", "stride_end_frame", "peak_knee_height_frame", "foot_plant_frame", "ball_release_frame"): marks.pop(key, None) await self.sessions.update( session, measurement_payload=payload, report=report, analysis_id=parsed.analysis_id, analysis_revision=parsed.analysis_revision, marks=marks, analyzed_at=session.analyzed_at or datetime.now(UTC), queued_payload=None, report_error=None)