function createProtectToday() {
  function propose({ agenda = [], today = [], identity, limit = 5 }) {
    const key = item => String(identity?.(item) || '');
    const urgent = [];
    const seen = new Set();
    for (const item of [...agenda, ...today]) {
      const id = key(item);
      const eligible = item?.kind === 'issue' && item.is_assigned === true && item.state !== 'closed' &&
        ['Overdue', 'Today'].includes(item.agenda_group);
      if (!eligible || !id || seen.has(id)) continue;
      seen.add(id);
      urgent.push(item);
    }
    urgent.sort((left, right) =>
      String(left.due_date || '').localeCompare(String(right.due_date || '')) ||
      String(left.repository || '').localeCompare(String(right.repository || '')) ||
      Number(left.number || 0) - Number(right.number || 0)
    );
    if (!urgent.length) return {
      selected:[], protected:[], displaced:[],
      summary:'No overdue or due-today work needs protection.',
    };
    const existing = [];
    for (const item of today) {
      const id = key(item);
      if (!id || seen.has(id)) continue;
      seen.add(id);
      existing.push(item);
    }
    const combined = [...urgent, ...existing];
    const selected = combined.slice(0, limit);
    const selectedIds = new Set(selected.map(key));
    const displaced = today.filter(item => !selectedIds.has(key(item)) && !urgent.some(candidate => key(candidate) === key(item)));
    return {
      selected,
      protected:urgent,
      displaced,
      summary:urgent.length + ' urgent ' + (urgent.length === 1 ? 'item' : 'items') + ' protected · ' +
        displaced.length + (displaced.length ? ' displaced for review' : ' displaced'),
    };
  }
  return { propose };
}

const protectToday = createProtectToday();
if (typeof module !== 'undefined' && module.exports) module.exports = protectToday;
