"""Pick the right timetable column for a day and list upcoming departures.""" from datetime import date from typing import Container, Sequence from timetable import KIND_REST_DAY, KIND_SPECIAL, KIND_WORKDAY, Column 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. a KIND_SPECIAL column whose `dates` contain `day` wins; 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. """ 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]