feat: list next departures across stops with day rollover

Co-Authored-By: Claude Haiku 4.5 <[email protected]>
This commit is contained in:
rickzkmandClaude Haiku 4.5 committed 2026-10-07 00:34:16 +02:00
1 parent 2eecbab365
commit ce52e38f66
2 files changed
+142 -5

No files matched your search

+37 -2
View File
@@ -1,8 +1,11 @@
"""Pick the right timetable column for a day and list upcoming departures."""
from datetime import date
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from typing import Container, Sequence
from timetable import KIND_REST_DAY, KIND_SPECIAL, KIND_WORKDAY, Column
from timetable import KIND_REST_DAY, KIND_SPECIAL, KIND_WORKDAY, Column, Departure, Timetable
LOOKAHEAD_DAYS = 3 # days after today we search before giving up
def is_rest_day(day: date, state_holidays: Container[date]) -> bool:
@@ -30,3 +33,35 @@ def select_column(columns: Sequence[Column], day: date, rest_day: bool) -> Colum
return None
started = [c for c in candidates if c.valid_from <= day]
return started[-1] if started else candidates[0]
@dataclass(frozen=True)
class Upcoming:
departure: Departure
when: datetime
minutes: int # whole minutes from now; 0 means "leaving now"
next_day: bool # departs on a later calendar day than now
def next_departures(
timetables: Sequence[Timetable], now: datetime, count: int, state_holidays: Container[date]
) -> list[Upcoming]:
"""The next `count` departures at or after `now` (minute precision), earliest first."""
start = now.replace(second=0, microsecond=0)
found: list[Upcoming] = []
for offset in range(LOOKAHEAD_DAYS + 1):
day = start.date() + timedelta(days=offset)
rest = is_rest_day(day, state_holidays)
for timetable in timetables:
column = select_column(timetable.columns, day, rest)
if column is None:
continue
for dep in column.departures:
when = datetime.combine(day, dep.time)
if when >= start:
minutes = int((when - start).total_seconds() // 60)
found.append(Upcoming(dep, when, minutes, day != now.date()))
if len(found) >= count:
break
found.sort(key=lambda u: (u.when, u.departure.line))
return found[:count]