const startDate = new Date(`${dv.current()["Start Date"]}`);
const endDate = new Date(`${dv.current()["End Date"]}`);
 
const MIN_SESSION_HOURS = 0.5; // 30 minutes
 
// Fetch pages with the 'clienthours' tag and #supervision
let pages = dv.pages('"100 CPD Record" and #supervision')
  .where(p => {
    const fileDate = new Date(p.date);
    const hrs = Number(p.hours) || 0;
    return fileDate >= startDate && fileDate <= endDate && hrs >= MIN_SESSION_HOURS;
  })
  .sort(p => p.date, 'asc');
 
dv.paragraph(`Total records fetched: ${pages.length}`);
 
if (pages.length === 0) {
  dv.paragraph("No pages found for the specified query.");
} else {
  // Group by Body
  const bodyGroups = {};
  let grandTotalHours = 0;
 
  pages.forEach(p => {
    const body = p.Body || "No Body";
    const hours = p.hours || 0;
 
    if (!bodyGroups[body]) {
      bodyGroups[body] = 0;
    }
 
    bodyGroups[body] += hours;
    grandTotalHours += hours;
  });
 
  // Prepare the table
  const tableData = [];
 
  for (const [body, hours] of Object.entries(bodyGroups).sort()) {
    const percentOfTotal = ((hours / grandTotalHours) * 100).toFixed(2);
    tableData.push([
      `**${body}**`,
      `**${hours}**`,
      `**${percentOfTotal}%**`,
    ]);
  }
 
  // Grand total row
  tableData.push([
    "**Grand Total**",
    `**${grandTotalHours}**`,
    "**100%**",
  ]);
 
  dv.table(["Body", "Total Hours", "% of Total"], tableData);
}