Files
bus-department-schedule/schedule.py
T
2026-10-07 00:55:17 +02:00

72 lines
3.0 KiB
Python

"""Pick the right timetable column for a day and list upcoming departures."""
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, Departure, Timetable
LOOKAHEAD_DAYS = 3 # days after today we search before giving up
def is_rest_day(day: date, state_holidays: Container[date]) -> bool:
"""Saturday, Sunday or a Czech state holiday."""
return day.weekday() >= 5 or day in state_holidays
def select_column(columns: Sequence[Column], day: date, rest_day: bool) -> Column | None:
"""The column that applies on `day`, or None if the timetable has no usable column.
Rules (see spec "Choosing the column"):
1. on a non-rest day, a KIND_SPECIAL column whose `dates` contain `day` wins
(the special column is workdays-during-school-holidays, so it never applies
on a Saturday, Sunday or state holiday);
2. otherwise rest days use KIND_REST_DAY columns, other days KIND_WORKDAY;
3. among columns of that kind the one with the latest valid_from <= day;
if none has started yet, the one with the earliest valid_from;
4. no column of the needed kind -> None.
"""
if not rest_day:
for column in columns:
if column.kind == KIND_SPECIAL and day in column.dates:
return column
wanted = KIND_REST_DAY if rest_day else KIND_WORKDAY
candidates = sorted((c for c in columns if c.kind == wanted), key=lambda c: c.valid_from)
if not candidates:
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:
# naive local-time difference: off by one hour on the two DST nights (00:00-03:00)
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]