"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.queryWidgetData = queryWidgetData;
function queryWidgetData(db) {
    const todayStart = getTodayStartMs();
    const monthStart = getMonthStartMs();
    const tomorrow = todayStart + 86400000;
    const nextMonthStart = getNextMonthStartMs();
    const todayRow = db.prepare(`
    SELECT
      COALESCE(SUM(input_tokens), 0) AS input,
      COALESCE(SUM(output_tokens), 0) AS output,
      COALESCE(SUM(cache_read_tokens + cache_write_tokens + thinking_tokens), 0) AS other
    FROM records
    WHERE ts >= ? AND ts < ?
  `).get(todayStart, tomorrow);
    const monthRow = db.prepare(`
    SELECT COALESCE(SUM(input_tokens + output_tokens + cache_read_tokens + cache_write_tokens + thinking_tokens), 0) AS total
    FROM records
    WHERE ts >= ? AND ts < ?
  `).get(monthStart, nextMonthStart);
    const modelRows = db.prepare(`
    SELECT
      model,
      SUM(input_tokens + output_tokens + cache_read_tokens + cache_write_tokens + thinking_tokens) AS tokens
    FROM records
    WHERE ts >= ? AND ts < ?
    GROUP BY model
    ORDER BY tokens DESC
  `).all(todayStart, tomorrow);
    let topModel = null;
    if (modelRows.length > 0) {
        const totalTokens = modelRows.reduce((acc, r) => acc + r.tokens, 0);
        const top = modelRows[0];
        topModel = {
            name: top.model,
            share: totalTokens > 0 ? Math.round((top.tokens / totalTokens) * 100) : 0,
        };
    }
    return {
        todayTokens: {
            total: todayRow.input + todayRow.output + todayRow.other,
            input: todayRow.input,
            output: todayRow.output,
        },
        monthTokens: {
            total: monthRow.total,
        },
        topModel,
        lastUpdated: Date.now(),
    };
}
function getTodayStartMs() {
    const now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
}
function getMonthStartMs() {
    const now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), 1).getTime();
}
function getNextMonthStartMs() {
    const now = new Date();
    return new Date(now.getFullYear(), now.getMonth() + 1, 1).getTime();
}
