"""End to end against the real Gemini model: upload, session, queued swing report, worker, notification, and a second swing that is compared with the first. Costs about one cent. Off by default: RUN_LIVE_COACH=1 TEST_DATABASE_NAME=app_test_rt .venv/bin/python -m pytest tests/integration/test_live_coach.py -s """ import copy import os import re from datetime import UTC, datetime, timedelta from pathlib import Path import pytest from ai_coach.config import get_settings as get_coach_settings from pydantic import SecretStr from tests.factories import create_session, make_account, set_session from tests.integration.test_report_queue import workers_done from tests.integration.test_swing_reports import PAYLOAD pytestmark = pytest.mark.skipif(not os.environ.get("RUN_LIVE_COACH"), reason="set RUN_LIVE_COACH=1 (calls Gemini)") @pytest.fixture def live_coach(monkeypatch, tmp_path): """The coach as production runs it, with the key and model from backend/.env.""" env = dict(line.split("=", 1) for line in (Path(__file__).parents[2] / ".env").read_text().splitlines() if "=" in line and not line.lstrip().startswith("#")) settings = get_coach_settings() monkeypatch.setattr(settings, "google_api_key", SecretStr(env["GOOGLE_API_KEY"].strip().strip("\"'"))) monkeypatch.setattr(settings, "model", env.get("COACH_MODEL", settings.model).strip()) monkeypatch.setattr(settings, "cache_path", tmp_path / "cache.sqlite3") monkeypatch.setattr(settings, "log_dir", tmp_path / "logs") return settings def all_text(report: dict) -> list[str]: focus = report["focus_area"] out = [report["overview"]["headline"], focus["coach_message"]] out += [g["summary"] for g in report["groups"] if g["rating"] != "not_rated"] for m in report["measurements"]: out += [m["result_text"] or "", m["coach_tip"] or ""] return [t for t in out if t] async def queued_report(client, headers, payload) -> dict: session = await create_session(client, headers) # real presigned uploads, then POST /v1/sessions sid = session["id"] posted = await client.post(f"/v1/sessions/{sid}/swing-report", json=payload, headers=headers) assert posted.status_code == 202 and posted.json() == {"session_id": sid, "status": "queued"}, posted.text await workers_done() detail = (await client.get(f"/v1/sessions/{sid}", headers=headers)).json()["session"] assert detail["status"] == "done" and detail["report_error"] is None, detail return detail async def test_swing_report_end_to_end_on_the_real_model(client, live_coach): account = await make_account() headers = account["headers"] first = await queued_report(client, headers, PAYLOAD) report = first["report"] meta = report["meta"] print("\nFIRST", meta["text_source"], meta["model"], meta["text_rejections"], *all_text(report), sep="\n ") assert meta["text_source"] in ("llm", "mixed") and meta["model"] == live_coach.model == "gemini-3.8-flash", meta assert not any(re.search(r"\d", t) for t in all_text(report)) notes = (await client.get("/v1/notifications", headers=headers)).json()["items"] assert [(n["kind"], n["title"], n["target"]["session_id"]) for n in notes] == [ ("result", "Your swing report is ready", first["id"])] # The same player, the same drill, a week later, with the off-target result now in the typical range. await set_session(first["id"], created_at=datetime.now(UTC) - timedelta(days=8)) improved = copy.deepcopy(PAYLOAD) improved.update(analysis_id="analysis_002", swing_id="swing_002") improved["measurements"][0]["value"] = -15 second = await queued_report(client, headers, improved) report = second["report"] meta = report["meta"] print("\nSECOND", meta["text_source"], meta["model"], meta["text_rejections"], *all_text(report), sep="\n ") assert meta["text_source"] in ("llm", "mixed") and meta["model"] == "gemini-3.8-flash", meta assert not any(re.search(r"\d", t) for t in all_text(report)) assert report["overall_score"] > first["report"]["overall_score"] assert re.search(r"last week|last time|last session|earlier|previous", " ".join(all_text(report)).lower()), ( "the second report should mention the earlier session") assert len((await client.get("/v1/notifications", headers=headers)).json()["items"]) == 2