screen-locker/screen_locker/_weekly_check.py
Krzysztof kuhy Rudnicki d9119a6582
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
Add manual (unverified) workout logging with evidence form
Adds a rate-limited manual-workout entry point (StatusWindow + locked
retry screen) for activities like table tennis that ADB/RunnerUp can't
verify, gated by a 2/7d + 5/30d budget and a detailed evidence form
rather than free text. Full credit toward the weekly minimum, debt
clearing, and commitment prompt, matching phone/RunnerUp verification.

Also stops tracking personal runtime state (workout_log.json,
sick_history.json, extra_benefits_state.json, scheduled_skips.json,
shutdown_base.json, early_bird_pending.json) in git — these are
regenerated locally and never belong in a public/private repo's
history.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AbPcvAvt1JhiRzEyPDE5dA
2026-07-05 20:08:52 +02:00

114 lines
3.6 KiB
Python

"""Weekly workout count and day-of-week mode detection for the screen locker.
On Tue/Wed/Thu (relaxed days) the lock is optional: the user can skip
without any penalty, or voluntarily import a Stronglift workout which
will count toward the weekly minimum.
On Fri/Sat/Sun/Mon (enforced days) the lock fires unless the user has
already logged at least WEEKLY_WORKOUT_MINIMUM verified workouts in the
current ISO week (Mon-Sun).
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import json
import logging
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from pathlib import Path
_logger = logging.getLogger(__name__)
WEEKLY_WORKOUT_MINIMUM: int = 4
# Python weekday(): Mon=0, Tue=1, Wed=2, Thu=3, Fri=4, Sat=5, Sun=6
_RELAXED_WEEKDAYS: frozenset[int] = frozenset({1, 2, 3}) # Tue, Wed, Thu
# Workout types that count toward the weekly minimum *and* earn the
# shutdown-time bonus (see screen_lock._try_adjust_shutdown_for_workout).
# Exported (no leading underscore) so screen_lock.py can share this single
# source of truth instead of duplicating the type check.
COUNTED_WORKOUT_TYPES: frozenset[str] = frozenset(
{"phone_verified", "runnerup_manual", "runnerup_verified", "manual_workout"},
)
def is_relaxed_day(*, today: datetime | None = None) -> bool:
"""Return True if today is a relaxed day (Tue, Wed, or Thu).
Args:
today: Override for the current local datetime (for testing).
Returns:
True when the current weekday is Tuesday, Wednesday, or Thursday.
"""
dt = today if today is not None else datetime.now(tz=timezone.utc).astimezone()
return dt.weekday() in _RELAXED_WEEKDAYS
def count_weekly_workouts(
log_file: Path,
*,
today: datetime | None = None,
) -> int:
"""Count phone-verified workouts logged in the current ISO week (Mon-Sun).
Args:
log_file: Path to ``workout_log.json``.
today: Override for the current local datetime (for testing).
Returns:
Number of ``phone_verified`` entries whose date falls within the
current ISO week, up to and including today.
"""
dt = today if today is not None else datetime.now(tz=timezone.utc).astimezone()
week_start = (dt - timedelta(days=dt.weekday())).date()
today_date = dt.date()
if not log_file.exists():
return 0
try:
with log_file.open() as f:
logs: dict[str, Any] = json.load(f)
except (OSError, json.JSONDecodeError):
_logger.warning("Could not read workout log for weekly count")
return 0
count = 0
for date_str, entry in logs.items():
try:
entry_date = (
datetime.strptime(date_str, "%Y-%m-%d")
.replace(tzinfo=timezone.utc)
.date()
)
except ValueError:
continue
if not (week_start <= entry_date <= today_date):
continue
if not isinstance(entry, dict):
continue
wtype = entry.get("workout_data", {}).get("type", "")
if wtype in COUNTED_WORKOUT_TYPES:
count += 1
return count
def has_weekly_minimum(
log_file: Path,
*,
today: datetime | None = None,
) -> bool:
"""Return True if the weekly workout minimum has already been reached.
Args:
log_file: Path to ``workout_log.json``.
today: Override for the current local datetime (for testing).
Returns:
True when ``count_weekly_workouts`` >= ``WEEKLY_WORKOUT_MINIMUM``.
"""
return count_weekly_workouts(log_file, today=today) >= WEEKLY_WORKOUT_MINIMUM