"""Assign random publish days within the ISO calendar week."""

import random
from datetime import date, timedelta


def week_bounds(reference=None):
    today = reference or date.today()
    iso = today.isocalendar()
    start = date.fromisocalendar(iso[0], iso[1], 1)
    end = date.fromisocalendar(iso[0], iso[1], 7)
    return start, end


def random_publish_dates(count, reference=None):
    """
    Pick `count` distinct random days in the current ISO week (today through Sunday).
    """
    if count <= 0:
        return []

    today = reference or date.today()
    week_start, week_end = week_bounds(today)
    first = max(week_start, today)
    eligible = []
    d = first
    while d <= week_end:
        eligible.append(d)
        d += timedelta(days=1)

    if not eligible:
        return []

    if count >= len(eligible):
        return eligible[:count]

    return sorted(random.sample(eligible, count))
