"""H1: POST /v1/sessions/{id}/swing-report.""" import copy import json import uuid from datetime import UTC, datetime from decimal import Decimal from pathlib import Path import pytest from ai_coach.swing_report import build_report from app.core.database import get_session_factory from app.core.dependencies import Db from app.modules.billing.entitlement import FREE_WEEKLY_LIMIT from app.modules.sessions.models import SwingSession from app.modules.swing_reports.controller import get_swing_report_service from app.modules.swing_reports.service import SwingReportService from app.modules.uploads.models import Upload from tests import factories PAYLOAD = { "schema_version": "1.0", "analysis_id": "analysis_001", "analysis_revision": 1, "swing_id": "swing_001", "status": "completed", "athlete": {"athlete_id": "player_001", "batting_hand": "right", "lead_foot": "left", "age_years": None, "height_cm": None}, "context": {"sport": "baseball", "practice_type": "tee"}, "measurement_definitions_version": "1.0", "events": { "stride_start": {"video_time_s": 1.0, "capture_time_s": 1.0, "status": "available", "source": "manual_review"}, "front_foot_down": {"video_time_s": 1.2, "capture_time_s": 1.2, "status": "available", "source": "manual_review"}, "contact": {"video_time_s": None, "capture_time_s": None, "status": "unavailable", "source": None, "reasons": ["contact_not_verified"]}, }, "measurements": [ {"metric_id": "hip_shoulder_separation_at_foot_down", "group": "stride", "value": 3, "unit": "deg", "event_id": "front_foot_down", "reference": "signed_horizontal_shoulder_minus_hip_heading", "status": "available", "confidence": None, "uses_interpolated_input": False, "reasons": [], "benchmark": None}, {"metric_id": "stride_relative_length", "group": "stride", "value": 24, "unit": "cm", "start_event_id": "stride_start", "end_event_id": "front_foot_down", "reference": "lead_ankle_displacement_relative_to_rear_ankle", "status": "limited", "confidence": None, "uses_interpolated_input": False, "reasons": ["scale_is_model_estimated"], "benchmark": None}, {"metric_id": "hip_shoulder_separation_at_contact", "group": "contact_follow_through", "value": None, "unit": "deg", "event_id": "contact", "reference": "signed_horizontal_shoulder_minus_hip_heading", "status": "unavailable", "confidence": None, "uses_interpolated_input": False, "reasons": ["contact_not_verified"], "benchmark": None}, ], } ATHLETE = {"name": "Test Hitter", "age": 20, "height_cm": 180, "weight_kg": 80, "bats": "R", "throws": "R", "level": "college"} def payload(**changes) -> dict: p = copy.deepcopy(PAYLOAD) p.update(changes) return p async def make_account() -> tuple[uuid.UUID, dict]: account = await factories.make_account(level=None, bats=None) return account["id"], account["headers"] async def make_session(owner_id: uuid.UUID, *, mode: str = "h", athlete: dict | None = None, **values) -> uuid.UUID: async with get_session_factory()() as db: upload = Upload(owner_id=owner_id, kind="video", object_key=f"v/{uuid.uuid4().hex}.mp4", content_type="video/mp4", size_bytes=1000, attached_at=datetime.now(UTC)) db.add(upload) await db.flush() session = SwingSession(owner_id=owner_id, is_self=True, athlete=athlete or ATHLETE, mode=mode, video_upload_id=upload.id, duration_sec=Decimal("3.5"), fps=30, marks={}, **values) db.add(session) await db.commit() return session.id async def load_session(session_id: uuid.UUID) -> SwingSession: async with get_session_factory()() as db: return await db.get(SwingSession, session_id) def url(session_id) -> str: return f"/v1/sessions/{session_id}/swing-report?queue=false" @pytest.fixture def builds(app): """Counts report builds (real builder underneath).""" calls: list[dict] = [] def counting(payload, athlete, **kw): calls.append({"payload": payload, "athlete": athlete}) return build_report(payload, athlete, **kw) def service(db: Db) -> SwingReportService: return SwingReportService(db, builder=counting) app.dependency_overrides[get_swing_report_service] = service yield calls app.dependency_overrides.pop(get_swing_report_service, None) async def test_report_success_and_saved(client): owner, headers = await make_account() sid = await make_session(owner) response = await client.post(url(sid), json=PAYLOAD, headers={**headers, "X-Request-Id": "req_test"}) assert response.status_code == 200, response.text report = response.json() # Stride length is an estimate, so it counts toward the score and marks it tentative. assert report["overall_score"] == 78 and report["overall_score_is_tentative"] is True assert [g["group"] for g in report["groups"]] == ["balance_load", "stride", "power_move", "contact_follow_through"] assert report["focus_area"]["drill"]["drill_id"] == "hit_13" assert report["measurements"][0]["benchmark"]["benchmark_id"] == ( "obp-contract-v1.hip_shoulder_separation_at_foot_down.right.college") assert report["meta"]["text_source"] == "rules" and report["meta"]["request_id"] == "req_test" assert set(report) == {"schema_version", "analysis_id", "analysis_revision", "overall_score", "overall_score_is_tentative", "overview", "groups", "focus_area", "measurements", "data_quality", "meta"} row = await load_session(sid) assert row.report == report and row.measurement_payload == PAYLOAD assert (row.analysis_id, row.analysis_revision, row.overall_score) == ("analysis_001", 1, 78) assert row.analyzed_at is not None async def test_same_revision_returns_stored_report_without_rebuild(client, builds): owner, headers = await make_account() sid = await make_session(owner) first = await client.post(url(sid), json=PAYLOAD, headers=headers) second = await client.post(url(sid), json=PAYLOAD, headers=headers) assert first.status_code == second.status_code == 200 assert first.json() == second.json() assert len(builds) == 1 async def test_higher_revision_rebuilds_and_replaces(client, builds): owner, headers = await make_account() sid = await make_session(owner) assert (await client.post(url(sid), json=PAYLOAD, headers=headers)).status_code == 200 analyzed_at = (await load_session(sid)).analyzed_at newer = payload(analysis_revision=2) newer["measurements"][0]["value"] = -15 response = await client.post(url(sid), json=newer, headers=headers) assert response.status_code == 200 assert response.json()["analysis_revision"] == 2 and response.json()["overall_score"] == 100 row = await load_session(sid) assert row.analysis_revision == 2 and row.overall_score == 100 and row.measurement_payload == newer assert row.analyzed_at == analyzed_at # the first analysis time is kept (plan usage window) assert len(builds) == 2 async def test_v11_report_revision_updates_exact_source_marks(client): owner, headers = await make_account() sid = await make_session(owner) p = json.loads((Path(__file__).resolve().parents[3] / "docs/motion-coach-payload-v1.1.example.json").read_text()) first = await client.post(url(sid), json=p, headers=headers) assert first.status_code == 200, first.text assert all(group["score"] is not None for group in first.json()["groups"]) row = await load_session(sid) assert row.marks == {"stride_start_frame": 3, "stride_end_frame": 10, "contact_frame": 20, "contact_offset": 0, "contact_source": "manual"} p["analysis_revision"] = 2 p["events"]["contact"].update(source_frame_index=21, video_time_s=0.7, capture_time_s=0.7) p["events"]["follow_through"].update(source_frame_index=24, video_time_s=0.8, capture_time_s=0.8) revised = await client.post(url(sid), json=p, headers=headers) assert revised.status_code == 200, revised.text row = await load_session(sid) assert row.marks["contact_frame"] == 21 and row.measurement_payload == p assert row.report == revised.json() and row.analysis_revision == 2 async def test_legacy_report_preserves_marks_without_guessing_frames_from_times(client): owner, headers = await make_account() sid = await make_session(owner) original = {"contact_frame": 75, "contact_offset": 0, "contact_source": "manual"} async with get_session_factory()() as db: row = await db.get(SwingSession, sid) row.marks = original await db.commit() response = await client.post(url(sid), json=PAYLOAD, headers=headers) assert response.status_code == 200, response.text assert (await load_session(sid)).marks == original async def test_lower_revision_is_stale(client): owner, headers = await make_account() sid = await make_session(owner) assert (await client.post(url(sid), json=payload(analysis_revision=3), headers=headers)).status_code == 200 response = await client.post(url(sid), json=payload(analysis_revision=2), headers=headers) assert response.status_code == 409 assert response.json()["error"]["code"] == "STALE_REVISION" async def test_other_analysis_id_is_a_mismatch(client): owner, headers = await make_account() sid = await make_session(owner) assert (await client.post(url(sid), json=PAYLOAD, headers=headers)).status_code == 200 response = await client.post(url(sid), json=payload(analysis_id="analysis_002"), headers=headers) assert response.status_code == 409 assert response.json()["error"]["code"] == "ANALYSIS_MISMATCH" async def test_invalid_payload(client): owner, headers = await make_account() sid = await make_session(owner) bad = payload() bad["measurements"][1]["reasons"] = [] bad["events"]["front_foot_down"]["video_time_s"] = 0.5 response = await client.post(url(sid), json=bad, headers=headers) assert response.status_code == 422 error = response.json()["error"] assert error["code"] == "INVALID_PAYLOAD" assert error["message"] == "The payload does not follow swing analysis contract 1.0 or 1.1." assert error["fields"] == { "measurements[1].reasons": "A limited result needs at least one reason code.", "events.stride_start.video_time_s": "Must be before front_foot_down.", } assert (await load_session(sid)).report is None @pytest.mark.parametrize("body", [[1, 2], "text", {"schema_version": "2.0"}]) async def test_non_contract_bodies(client, body): owner, headers = await make_account() sid = await make_session(owner) response = await client.post(url(sid), json=body, headers=headers) assert response.status_code == 422 assert response.json()["error"]["code"] == "INVALID_PAYLOAD" async def test_pitching_session_needs_the_pitch_report(client): owner, headers = await make_account() sid = await make_session(owner, mode="p") response = await client.post(url(sid), json=PAYLOAD, headers=headers) assert response.status_code == 422 assert response.json()["error"]["code"] == "MODE_NOT_SUPPORTED" async def test_unauthenticated(client): owner, _ = await make_account() sid = await make_session(owner) response = await client.post(url(sid), json=PAYLOAD) assert response.status_code == 401 assert response.json()["error"]["code"] == "UNAUTHENTICATED" async def test_other_owner_forbidden(client): owner, _ = await make_account() _, other_headers = await make_account() sid = await make_session(owner) response = await client.post(url(sid), json=PAYLOAD, headers=other_headers) assert response.status_code == 403 assert response.json()["error"]["code"] == "FORBIDDEN" async def test_unknown_and_deleted_sessions_not_found(client): owner, headers = await make_account() response = await client.post(url(uuid.uuid4()), json=PAYLOAD, headers=headers) assert response.status_code == 404 and response.json()["error"]["code"] == "NOT_FOUND" sid = await make_session(owner, deleted_at=datetime.now(UTC)) response = await client.post(url(sid), json=PAYLOAD, headers=headers) assert response.status_code == 404 async def test_plan_limit_on_first_analysis_only(client): owner, headers = await make_account() for _ in range(FREE_WEEKLY_LIMIT): await make_session(owner, analyzed_at=datetime.now(UTC), report={"overall_score": 50}, analysis_id=uuid.uuid4().hex, analysis_revision=1) sid = await make_session(owner) response = await client.post(url(sid), json=PAYLOAD, headers=headers) assert response.status_code == 402 assert response.json()["error"]["code"] == "PLAN_LIMIT" assert (await load_session(sid)).report is None async def test_rebuild_allowed_at_plan_limit(client): owner, headers = await make_account() sid = await make_session(owner) assert (await client.post(url(sid), json=PAYLOAD, headers=headers)).status_code == 200 for _ in range(FREE_WEEKLY_LIMIT - 1): await make_session(owner, analyzed_at=datetime.now(UTC), report={"overall_score": 50}, analysis_id=uuid.uuid4().hex, analysis_revision=1) response = await client.post(url(sid), json=payload(analysis_revision=2), headers=headers) assert response.status_code == 200 async def test_too_large(client): owner, headers = await make_account() sid = await make_session(owner) big = payload(padding="x" * 300_000) response = await client.post(url(sid), json=big, headers=headers) assert response.status_code == 413 assert response.json()["error"]["code"] == "TOO_LARGE" async def test_athlete_context_from_session(client, builds): owner, headers = await make_account() sid = await make_session(owner, athlete={**ATHLETE, "bats": "L", "level": None}) p = payload() p["athlete"].update(batting_hand=None, lead_foot="right") response = await client.post(url(sid), json=p, headers=headers) assert response.status_code == 200 report = response.json() # no left-handed high-school population: falls back to college assert report["measurements"][0]["benchmark"]["benchmark_id"].endswith(".left.college") codes = {n["code"] for n in report["data_quality"]} assert {"level_assumed", "population_fallback"} <= codes athlete = builds[0]["athlete"] assert (athlete.batting_hand, athlete.level, athlete.height_cm) == ("left", None, 180.0) async def test_payload_batting_hand_wins(client): owner, headers = await make_account() sid = await make_session(owner, athlete={**ATHLETE, "bats": "L"}) response = await client.post(url(sid), json=PAYLOAD, headers=headers) assert response.json()["measurements"][0]["benchmark"]["benchmark_id"].endswith(".right.college") assert "batting_hand_conflict" in {n["code"] for n in response.json()["data_quality"]} assert response.json()["focus_area"]["kind"] == "general" async def test_missing_gemini_key_is_an_error_not_a_template_report(client, monkeypatch): from ai_coach.config import get_settings as get_coach_settings from app.core.config import get_settings monkeypatch.setattr(get_settings(), "env", "dev") monkeypatch.setattr(get_coach_settings(), "google_api_key", None) owner, headers = await make_account() sid = await make_session(owner) response = await client.post(url(sid), json=PAYLOAD, headers=headers) assert response.status_code == 503 assert response.json()["error"]["code"] == "COACH_NOT_CONFIGURED" row = await load_session(sid) assert row.report is None and row.analyzed_at is None # nothing saved, nothing counted toward the plan def test_production_refuses_to_start_without_gemini_key(monkeypatch): import pytest from ai_coach.config import get_settings as get_coach_settings from app.core.config import get_settings from app.main import create_app monkeypatch.setattr(get_settings(), "env", "prod") monkeypatch.setattr(get_coach_settings(), "google_api_key", None) with pytest.raises(RuntimeError, match="GOOGLE_API_KEY"): create_app()