export function extractNotesCountFromPostedResponse(raw: any): number {
  const payload = raw?.data || raw || {};
  const tags = payload?.tags || raw?.tags || [];
  let countFromTags = 0;

  if (Array.isArray(tags)) {
    const preferredTag = tags.find((t: any) => t?.id === 'special.note_time_desc');
    const preferred = preferredTag?.notes_count ?? preferredTag?.notesCount ?? preferredTag?.count;
    if (preferred !== undefined && preferred !== null) {
      countFromTags = Number(preferred) || 0;
    } else {
      countFromTags = tags.reduce((max: number, t: any) => {
        const n = Number(t?.notes_count ?? t?.notesCount ?? t?.count ?? 0);
        return Number.isFinite(n) ? Math.max(max, n) : max;
      }, 0);
    }
  }

  const countFromPayload =
    Number(
      payload?.total ||
      payload?.total_count ||
      payload?.totalCount ||
      payload?.notes_count ||
      payload?.note_count ||
      payload?.page?.total ||
      payload?.page?.totalCount ||
      0
    ) || 0;

  const notes = payload?.notes || raw?.notes || [];
  return countFromTags || countFromPayload || (Array.isArray(notes) ? notes.length : 0);
}

export function extractDeclaredNotesCountFromPostedResponse(raw: any): number {
  const payload = raw?.data || raw || {};
  const tags = payload?.tags || raw?.tags || [];
  let countFromTags = 0;

  if (Array.isArray(tags)) {
    const preferredTag = tags.find((t: any) => t?.id === 'special.note_time_desc');
    const preferred = preferredTag?.notes_count ?? preferredTag?.notesCount ?? preferredTag?.count;
    if (preferred !== undefined && preferred !== null) {
      countFromTags = Number(preferred) || 0;
    } else {
      countFromTags = tags.reduce((max: number, t: any) => {
        const n = Number(t?.notes_count ?? t?.notesCount ?? t?.count ?? 0);
        return Number.isFinite(n) ? Math.max(max, n) : max;
      }, 0);
    }
  }

  const countFromPayload =
    Number(
      payload?.total ||
      payload?.total_count ||
      payload?.totalCount ||
      payload?.notes_count ||
      payload?.note_count ||
      payload?.page?.total ||
      payload?.page?.totalCount ||
      0
    ) || 0;

  return countFromTags || countFromPayload;
}
