import {
  parseRelativeDate
} from "./chunk-ZXKLPC2E.js";
import {
  getAnalyticsTimeseries
} from "./chunk-CAY57CKF.js";
import "./chunk-KOO5733S.js";

// src/tools/get-analytics.ts
function getGroupedData(bucket, groupBy) {
  const data = bucket[groupBy];
  if (typeof data === "object" && data !== null && !Array.isArray(data)) {
    return data;
  }
  return void 0;
}
async function handleGetAnalytics(params) {
  const now = Date.now();
  const startDate = params.startDate ? parseRelativeDate(params.startDate) : now - 7 * 864e5;
  const endDate = params.endDate ? parseRelativeDate(params.endDate) : now;
  const [category, name] = params.metric.includes(".") ? params.metric.split(".", 2) : ["metadata", params.metric];
  const metricKey = `${category}.${name}`;
  const aggregation = params.aggregation ?? "avg";
  const result = await getAnalyticsTimeseries({
    series: [{ metric: metricKey, aggregation }],
    startDate,
    endDate,
    timeZone: params.timeZone ?? "UTC",
    groupBy: params.groupBy,
    filters: params.filters
  });
  const lines = [];
  lines.push(`# Analytics: ${metricKey} (${aggregation})
`);
  lines.push(
    `Period: ${new Date(startDate).toISOString().split("T")[0]} to ${new Date(endDate).toISOString().split("T")[0]}`
  );
  if (params.groupBy) lines.push(`Grouped by: ${params.groupBy}`);
  lines.push("");
  const currentPeriod = result.currentPeriod ?? [];
  if (currentPeriod.length === 0) {
    lines.push("No data available for this period.");
  } else if (params.groupBy && currentPeriod.some((b) => getGroupedData(b, params.groupBy) !== void 0)) {
    lines.push("| Date | Group | Value |");
    lines.push("|------|-------|-------|");
    for (const bucket of currentPeriod) {
      const groups = getGroupedData(bucket, params.groupBy);
      if (!groups) continue;
      for (const [groupKey, metrics] of Object.entries(groups)) {
        const value = Object.values(metrics).find((v) => typeof v === "number") ?? "N/A";
        lines.push(`| ${bucket.date} | ${groupKey} | ${value} |`);
      }
    }
  } else {
    lines.push("| Date | Value |");
    lines.push("|------|-------|");
    for (const bucket of currentPeriod) {
      const value = Object.entries(bucket).find(
        ([k]) => k !== "date" && typeof bucket[k] === "number"
      )?.[1] ?? "N/A";
      lines.push(`| ${bucket.date} | ${value} |`);
    }
  }
  lines.push(
    "\n> Tip: Use `discover_schema` to see all available metrics and aggregation types."
  );
  return lines.join("\n");
}
export {
  handleGetAnalytics
};
//# sourceMappingURL=get-analytics-EDFAYYIQ.js.map