/**
 * Usage data aggregation helper functions
 * Pure transformation functions for chart data
 */

/**
 * Groups records by day and sums tokens/cost
 * @param {Array} records - Array of usage records
 * @returns {Array} Daily aggregated data sorted by date (newest first)
 */
export function calculateDailyTotals(records) {
  if (!records || records.length === 0) return [];

  const dailyMap = new Map();

  for (const record of records) {
    const date = record.timestamp ? record.timestamp.split('T')[0] : 'unknown';
    if (!dailyMap.has(date)) {
      dailyMap.set(date, {
        date,
        requestCount: 0,
        totalInputTokens: 0,
        totalOutputTokens: 0,
        totalTokens: 0,
        totalCost: 0,
        errorCount: 0,
      });
    }

    const day = dailyMap.get(date);
    day.requestCount++;
    day.totalInputTokens += record.inputTokens || 0;
    day.totalOutputTokens += record.outputTokens || 0;
    day.totalTokens += record.totalTokens || 0;
    day.totalCost += record.cost || 0;
    if (record.status === 'error') day.errorCount++;
  }

  return Array.from(dailyMap.values()).sort((a, b) => b.date.localeCompare(a.date));
}

/**
 * Groups records by model and calculates totals
 * @param {Array} records - Array of usage records
 * @returns {Array} Model breakdown data sorted by total tokens (descending)
 */
export function calculateModelBreakdown(records) {
  if (!records || records.length === 0) return [];

  const modelMap = new Map();

  for (const record of records) {
    const model = record.model || 'unknown';
    if (!modelMap.has(model)) {
      modelMap.set(model, {
        model,
        requestCount: 0,
        totalTokens: 0,
        totalCost: 0,
      });
    }

    const entry = modelMap.get(model);
    entry.requestCount++;
    entry.totalTokens += record.totalTokens || 0;
    entry.totalCost += record.cost || 0;
  }

  return Array.from(modelMap.values()).sort((a, b) => b.totalTokens - a.totalTokens);
}

/**
 * Formats data for line chart (fills missing days with zeros)
 * @param {Array} records - Array of usage records
 * @param {number} days - Number of days to include (default: 30)
 * @returns {Array} Trend data for charts
 */
export function calculateTrendData(records, days = 30) {
  const dailyTotals = calculateDailyTotals(records);
  const today = new Date();
  const trendData = [];

  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(date.getDate() - i);
    const dateStr = date.toISOString().split('T')[0];

    const existing = dailyTotals.find(d => d.date === dateStr);
    trendData.push({
      date: dateStr,
      tokens: existing?.totalTokens || 0,
      cost: existing?.totalCost || 0,
      requests: existing?.requestCount || 0,
    });
  }

  return trendData;
}

/**
 * Formats cost for display
 * @param {number} amount - Cost amount
 * @returns {string} Formatted currency string
 */
export function formatCurrency(amount) {
  if (amount === null || amount === undefined) return '$0.00';
  if (amount < 0.01 && amount > 0) return '<$0.01';
  return `$${amount.toFixed(2)}`;
}

/**
 * Formats token count with K/M suffix
 * @param {number} count - Token count
 * @returns {string} Formatted token string
 */
export function formatTokens(count) {
  if (count === null || count === undefined) return '0';
  if (count >= 1000000) return `${(count / 1000000).toFixed(1)}M`;
  if (count >= 1000) return `${(count / 1000).toFixed(1)}K`;
  return count.toString();
}
