from datetime import datetime, timedelta


def frequency_to_timedelta(freq: dict) -> timedelta:
    value = int(freq.get("value", 0))
    unit = freq.get("unit")

    if value <= 0:
        raise ValueError("Frequency value must be > 0")

    if unit == "minutes":
        return timedelta(minutes=value)
    if unit == "days":
        return timedelta(days=value)
    raise ValueError(f"Unsupported frequency unit: {unit}")


def normalize_logical_time(ts: datetime) -> datetime:
    return ts.replace(microsecond=0)


def compute_logical_time(
    now: datetime,
    last_run: str | None,
    interval_seconds: float | None,
) -> datetime:
    base = now
    if last_run and interval_seconds:
        try:
            parsed = datetime.fromisoformat(last_run.replace("Z", "+00:00"))
        except ValueError:
            parsed = None
        if parsed is not None:
            if now.tzinfo and parsed.tzinfo is None:
                parsed = parsed.replace(tzinfo=now.tzinfo)
            elif now.tzinfo is None and parsed.tzinfo:
                parsed = parsed.replace(tzinfo=None)
            candidate = parsed + timedelta(seconds=interval_seconds)
            if now >= candidate:
                base = candidate
    return normalize_logical_time(base)
