"""Shared workout-credit logic: save + shutdown bonus. Extracted from ``screen_lock.py`` so both the locked-screen flow (``ScreenLocker.unlock_screen``) and the voluntary ``StatusWindow`` "Log Manual Workout" path apply the identical reward — the drift between those two paths having different behavior once caused a real shutdown-bonus miss (see ``project-lock-disabled-pending-manual-log`` memory). """ from __future__ import annotations from dataclasses import dataclass from datetime import date import logging from typing import TYPE_CHECKING import earned_time from screen_locker import _credit_notify from screen_locker._constants import SHUTDOWN_BASE_FILE from screen_locker._credit_slot import CreditSlot, credit_slot, locked_shutdown_state from screen_locker._day import today_str from screen_locker._earned import extra_minutes from screen_locker._rest_day import is_rest_day from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES, count_weekly_workouts if TYPE_CHECKING: from pathlib import Path _logger = logging.getLogger(__name__) # The shutdown reward for a day's workouts, from the shared registry # (``earned_time.WORKOUT``): the first counted workout pushes shutdown later by # FIRST_WORKOUT_BONUS_MINUTES, every further one by EXTRA_WORKOUT_BONUS_MINUTES. # Those are the pre-ladder fields; from earned_time's ladder (2026-10-10) the # live paths ask the day-aware _earned.first_minutes / extra_minutes instead. # The live credit paths below and the daily base reset (``_shutdown_base``) # both derive from the registry, so a day's earned time can be recomputed # from the log instead of being lost when the credit landed before the reset. FIRST_WORKOUT_BONUS_MINUTES = earned_time.WORKOUT.shutdown_minutes EXTRA_WORKOUT_BONUS_MINUTES = earned_time.WORKOUT.extra_shutdown_minutes def earned_shutdown_bonus_minutes(credit_count: int) -> int: """Return the shutdown minutes a day with *credit_count* workouts earned.""" return earned_time.WORKOUT.shutdown_for(credit_count) @dataclass(frozen=True) class WorkoutCreditResult: """Outcome of :meth:`WorkoutCreditMixin._apply_workout_credit`.""" shutdown_adjusted: bool extra_bonus_delta: int weekly_count: int already_counted_today: bool class WorkoutCreditMixin: """Save a workout entry and apply its shutdown/extra-bonus reward. Requires ``self.workout_data``, ``self.log_file``, and the ``LogMixin``/ ``ShutdownMixin`` methods it calls into. """ workout_data: dict[str, str] log_file: Path def _try_adjust_shutdown_for_workout(self) -> bool: """Try to adjust shutdown time later for actual workouts.""" workout_type = self.workout_data.get("type", "") if workout_type not in COUNTED_WORKOUT_TYPES: return False adjusted = self._adjust_shutdown_time_later() if adjusted: _logger.info("Shutdown time moved later as workout reward") return adjusted def _apply_credit_for_written_entry( self, prior_entries: list[dict] ) -> WorkoutCreditResult: """Apply the shutdown reward for an already-written ``workout_data``. Shared by :meth:`_apply_workout_credit` (the live locked-screen, Status-Window, and Check-Phone paths, which always write under today) and the manual-sync ingestion path (:func:`screen_locker._manual_sync.ingest_manual_records`, via its ``on_ingested`` callback — which writes under the entry's own date, today or back-dated). ``prior_entries`` must be that entry's day's entries *before* it, so "first counted workout of the day" is evaluated relative to the entry's own date; the shutdown adjustment itself always lands on the current shutdown config, since there's only ever one "tonight" to push regardless of which day earned it. Rewards: * first counted workout of the day → base **+2h** (cap 23:00); * an additional same-day counted workout (verified OR manual) → **+1h** (cap midnight) — manual workouts stack exactly like verified ones; the manual-workout rate budget is the only limiter. """ weekly_count = count_weekly_workouts(self.log_file) # Slot-based, exactly like the daily reset (credit_key): the two # StrongLifts ingestion paths of ONE session share a slot, so the # second copy earns nothing. Deciding on "any counted type before # it" instead paid one session +2h and then +1h (2026-10-09). slot = credit_slot(prior_entries, self.workout_data) if slot is CreditSlot.OCCUPIED: _logger.warning( "Workout %s (%s) shares its credit slot with an entry already " "credited today — no shutdown time; the daily " "reset counts the two as one workout too", self.workout_data.get("type", ""), self.workout_data.get("source", ""), ) return WorkoutCreditResult( shutdown_adjusted=False, extra_bonus_delta=0, weekly_count=weekly_count, already_counted_today=True, ) first_counted_today = slot is CreditSlot.FIRST shutdown_adjusted = False extra_bonus_delta = 0 day = date.fromisoformat(today_str()) # A rest day already paid the first unit (the daily reset counts it): # the first real workout on it earns nothing, a second one what a # further unit earns -- the reset's own max(credits, 1) rule. rest_paid = first_counted_today and is_rest_day(day) if rest_paid: _logger.info("Rest day: its first-unit bonus is already in tonight's time") extra = extra_minutes(earned_time.WORKOUT, day) # Same lock as the daily reset and the flat-bonus pass: all three # read-add-write the shutdown config and the grace lift. with locked_shutdown_state(SHUTDOWN_BASE_FILE): before = self._read_shutdown_config() if first_counted_today and not rest_paid: shutdown_adjusted = self._try_adjust_shutdown_for_workout() elif ( slot is CreditSlot.FURTHER and extra and before and self._adjust_shutdown_time_by(extra) ): new_cfg = self._read_shutdown_config() if new_cfg: extra_bonus_delta = new_cfg[1] - before[1] after = self._read_shutdown_config() if slot is not CreditSlot.NONE: self._notify_credit(before, after) return WorkoutCreditResult( shutdown_adjusted=shutdown_adjusted, extra_bonus_delta=extra_bonus_delta, weekly_count=weekly_count, already_counted_today=False, ) def _notify_credit( self, before: tuple[int, int, int] | None, after: tuple[int, int, int] | None, ) -> None: """Pop the "Workout credited" notification; never fails the credit. Runs after the credit is fully applied. Anything it raises -- a malformed ledger inside the budget sum, a DBus oddity -- would otherwise escape into the ingest loop and leave the rest of that batch uncredited, so every exception is logged and dropped here. """ try: _credit_notify.notify_workout_credit(before, after, self.log_file) except Exception: _logger.exception( "Workout credit notification failed — the credit itself is " "applied; only the desktop notification is missing" ) def _apply_workout_credit(self) -> WorkoutCreditResult: """Append ``workout_data`` and apply its reward, scaled to the day. Shared by the locked-screen flow (:meth:`ScreenLocker.unlock_screen`), the voluntary ``StatusWindow`` "Log Manual Workout" path, and the Check-Phone verify path. Always files under *today*; see :meth:`_apply_credit_for_written_entry` for the shared reward logic (a duplicate — same ``workout_id`` already logged — earns no new credit). """ result = self.save_workout_log() if not result.appended: # A workout with this id was already recorded today — idempotent. return WorkoutCreditResult( shutdown_adjusted=False, extra_bonus_delta=0, weekly_count=count_weekly_workouts(self.log_file), already_counted_today=True, ) return self._apply_credit_for_written_entry(result.prior_entries)