| 1 | import asyncio |
| 2 | |
| 3 | from helpers.localization import Localization |
| 4 | from helpers.print_style import PrintStyle |
| 5 | |
| 6 | |
| 7 | def format_remaining_time(total_seconds: float) -> str: |
| 8 | if total_seconds < 0: |
| 9 | total_seconds = 0 |
| 10 | |
| 11 | days, remainder = divmod(total_seconds, 86400) |
| 12 | hours, remainder = divmod(remainder, 3600) |
| 13 | minutes, seconds = divmod(remainder, 60) |
| 14 | |
| 15 | days = int(days) |
| 16 | hours = int(hours) |
| 17 | minutes = int(minutes) |
| 18 | |
| 19 | parts = [] |
| 20 | if days > 0: |
| 21 | parts.append(f"{days}d") |
| 22 | if hours > 0: |
| 23 | parts.append(f"{hours}h") |
| 24 | if minutes > 0: |
| 25 | parts.append(f"{minutes}m") |
| 26 | |
| 27 | if days > 0 or hours > 0: |
| 28 | if seconds >= 1: |
| 29 | parts.append(f"{int(seconds)}s") |
| 30 | elif minutes > 0: |
| 31 | if seconds >= 0.1: |
| 32 | parts.append(f"{seconds:.1f}s") |
| 33 | else: |
| 34 | parts.append(f"{total_seconds:.1f}s") |
| 35 | |
| 36 | if not parts: |
| 37 | return "0.0s remaining" |
| 38 | |
| 39 | return " ".join(parts) + " remaining" |
| 40 | |
| 41 | |
| 42 | async def managed_wait(agent, target_time, is_duration_wait, log, get_heading_callback): |
| 43 | |
| 44 | while Localization.get().now() < target_time: |
| 45 | before_intervention = Localization.get().now() |
| 46 | await agent.handle_intervention() |
| 47 | after_intervention = Localization.get().now() |
| 48 | |
| 49 | if is_duration_wait: |
| 50 | pause_duration = after_intervention - before_intervention |
| 51 | if pause_duration.total_seconds() > 1.5: # Adjust for pauses longer than the sleep cycle |
| 52 | target_time += pause_duration |
| 53 | PrintStyle.info( |
| 54 | f"Wait extended by {pause_duration.total_seconds():.1f}s to {Localization.get().serialize_datetime(target_time)}...", |
| 55 | ) |
| 56 | |
| 57 | current_time = Localization.get().now() |
| 58 | if current_time >= target_time: |
| 59 | break |
| 60 | |
| 61 | remaining_seconds = (target_time - current_time).total_seconds() |
| 62 | if log: |
| 63 | log.update(heading=get_heading_callback(format_remaining_time(remaining_seconds))) |
| 64 | sleep_duration = min(1.0, remaining_seconds) |
| 65 | |
| 66 | await asyncio.sleep(sleep_duration) |
| 67 | |
| 68 | return target_time |