from __future__ import annotations

from datetime import datetime


def _expand_field(field: str, value: int, min_val: int, max_val: int) -> bool:
    for part in field.split(","):
        part = part.strip()
        if not part:
            continue
        step = 1
        if "/" in part:
            base, step_s = part.split("/", 1)
            step = int(step_s)
        else:
            base = part

        if base == "*":
            if (value - min_val) % step == 0:
                return True
            continue

        if "-" in base:
            lo_s, hi_s = base.split("-", 1)
            lo, hi = int(lo_s), int(hi_s)
            for candidate in range(lo, hi + 1, step):
                if candidate == value:
                    return True
            continue

        if int(base) == value:
            return True
    return False


def cron_matches(expr: str, dt: datetime) -> bool:
    """标准 5 段 cron：分 时 日 月 周（周 0=周日）。"""
    parts = expr.strip().split()
    if len(parts) != 5:
        return False
    minute, hour, dom, month, dow = parts
    cron_dow = (dt.weekday() + 1) % 7
    return (
        _expand_field(minute, dt.minute, 0, 59)
        and _expand_field(hour, dt.hour, 0, 23)
        and _expand_field(dom, dt.day, 1, 31)
        and _expand_field(month, dt.month, 1, 12)
        and _expand_field(dow, cron_dow, 0, 6)
    )
