ore: number
 * }>>}
 *        Promise resolving to an array of mapped chat message objects.
 */
export async function getRecentChats(
  startTime = 0,
  maxResults = DEFAULT_MAX_RESULTS,
  halfLifeDays = DEFAULT_HALF_LIFE_DAYS
) {
  // Underlying Chatstore uses Date type but MemoriesStore maintains in TS
  const startDate = new Date(startTime);
  const endDate = new Date();
  const chatStore = new ChatStore();
  const messages = await chatStore.findMessagesByDate(
    startDate,
    endDate,
    MESSAGE_ROLE.USER,
    maxResults
  );

  const chatMessages = messages.map(msg => {
    const createdDate = msg.createdDate;
    const freshness_score = computeFreshnessScore(createdDate, halfLifeDays);
    return {
      createdDate,
      role: msg.role,
      content: msg.content?.body ?? null,
      pageUrl: msg.pageUrl,
      freshness_score,
    };
  });

  return chatMessages;
}

/**
 * Compute a freshness score for a message based on its age, using an
 * exponential decay with a configurable half-life.
 *
 * The score is:
 *   -> 1.0 for messages with ageDays <= 0 (now or in the future)
 *   -> exp(-ln(2) * (ageDays / halfLifeDays)) for older messages,
 *   clamped into the [0, 1] range.
 *
 * @param {number|Date} createdDate
 *        Message creation time, either as a millisecond timestamp or a Date.
 * @param {number} [halfLifeDays=DEFAULT_HALF_LIFE_DAYS]
 *        Half-life in days; larger values decay more slowly.
 * @returns {number}
 *          Freshness score in the range [0, 1].
 */
export function computeFreshnessScore(
  createdDate,
  halfLifeDays = DEFAULT_HALF_LIFE_DAYS
) {
  const now = Date.now();
  const createdMs =
    typeof createdDate === "number" ? createdDate : createdDate.getTime();
  const ageMs = now - createdMs;
  const ageDays =
    ageMs / (MS_PER_SEC * SEC_PER_MIN * MINS_PER_HOUR * HOURS_PER_DAY);
  if (ageDays <= 0) {
    return 1;
  }
  const raw = Math.exp(-Math.LN2 * (ageDays / halfLifeDays));
  return Math.max(0, Math.min(1, raw));
}
PK