import a from './index5.mjs';
import { i18n } from './index2.mjs';
import { g as getStatsStorage } from '../shared/ccjk.OTnevPNE.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:fs';
import 'node:process';
import 'node:url';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import 'node:os';

async function stats(options = {}) {
  const period = options.period || "7d";
  const format = options.format || "table";
  const storage = getStatsStorage();
  const { startDate, endDate } = storage.getDateRangeForPeriod(period);
  const records = storage.getRecordsByDateRange(startDate, endDate);
  if (records.length === 0) {
    console.log(a.yellow(`
${i18n.t("stats:noData")}
`));
    return;
  }
  const filteredRecords = options.provider ? records.filter((r) => r.provider === options.provider) : records;
  if (filteredRecords.length === 0) {
    console.log(a.yellow(`
${i18n.t("stats:noData")} for provider: ${options.provider}
`));
    return;
  }
  const stats2 = calculateStats(filteredRecords);
  if (format === "json") {
    console.log(JSON.stringify(stats2, null, 2));
  } else if (format === "csv") {
    displayCSV(stats2);
  } else {
    displayTable(stats2, period);
  }
  if (options.export) {
    await exportStats(stats2, options.export, format);
    console.log(a.green(`
${i18n.t("stats:exportSuccess")}: ${options.export}
`));
  }
}
function calculateStats(records) {
  const totalRequests = records.length;
  const successfulRequests = records.filter((r) => r.success).length;
  const successRate = totalRequests > 0 ? successfulRequests / totalRequests * 100 : 0;
  let totalInputTokens = 0;
  let totalOutputTokens = 0;
  let totalCost = 0;
  let totalLatency = 0;
  const providerCounts = {};
  const modelCounts = {};
  for (const record of records) {
    totalInputTokens += record.inputTokens || 0;
    totalOutputTokens += record.outputTokens || 0;
    totalCost += record.cost || 0;
    totalLatency += record.latency || 0;
    const provider = record.provider || "unknown";
    providerCounts[provider] = (providerCounts[provider] || 0) + 1;
    const model = record.model || "unknown";
    modelCounts[model] = (modelCounts[model] || 0) + 1;
  }
  const averageLatency = totalRequests > 0 ? totalLatency / totalRequests : 0;
  return {
    totalRequests,
    successfulRequests,
    failedRequests: totalRequests - successfulRequests,
    successRate,
    totalInputTokens,
    totalOutputTokens,
    totalTokens: totalInputTokens + totalOutputTokens,
    totalCost,
    averageLatency,
    providerCounts,
    modelCounts
  };
}
function displayTable(stats2, period) {
  console.log(a.cyan.bold(`
\u{1F4CA} ${i18n.t("stats:title")} - ${i18n.t(`stats:period.${period}`)}`));
  console.log(a.dim("\u2500".repeat(60)));
  console.log(a.yellow("\n\u{1F4C8} Request Statistics:"));
  console.log(`  ${i18n.t("stats:totalRequests")}: ${a.bold(stats2.totalRequests.toLocaleString())}`);
  console.log(`  ${a.green("\u2713")} Successful: ${a.bold(stats2.successfulRequests.toLocaleString())}`);
  console.log(`  ${a.red("\u2717")} Failed: ${a.bold(stats2.failedRequests.toLocaleString())}`);
  console.log(`  ${i18n.t("stats:successRate")}: ${a.bold(stats2.successRate.toFixed(2))}%`);
  console.log(a.yellow("\n\u{1F3AF} Token Usage:"));
  console.log(`  ${i18n.t("stats:input")}: ${a.bold(stats2.totalInputTokens.toLocaleString())}`);
  console.log(`  ${i18n.t("stats:output")}: ${a.bold(stats2.totalOutputTokens.toLocaleString())}`);
  console.log(`  ${i18n.t("stats:totalTokens")}: ${a.bold(stats2.totalTokens.toLocaleString())}`);
  console.log(a.yellow("\n\u{1F4B0} Cost Analysis:"));
  console.log(`  ${i18n.t("stats:estimatedCost")}: ${a.bold(`$${stats2.totalCost.toFixed(4)}`)}`);
  console.log(a.yellow("\n\u26A1 Performance:"));
  console.log(`  ${i18n.t("stats:averageLatency")}: ${a.bold(stats2.averageLatency.toFixed(0))}ms`);
  if (Object.keys(stats2.providerCounts).length > 0) {
    console.log(a.yellow(`
\u2601\uFE0F  ${i18n.t("stats:providerDistribution")}:`));
    for (const [provider, count] of Object.entries(stats2.providerCounts)) {
      const percentage = (count / stats2.totalRequests * 100).toFixed(1);
      console.log(`  ${provider}: ${a.bold(count)} (${percentage}%)`);
    }
  }
  if (Object.keys(stats2.modelCounts).length > 0) {
    console.log(a.yellow("\n\u{1F916} Model Distribution:"));
    for (const [model, count] of Object.entries(stats2.modelCounts)) {
      const percentage = (count / stats2.totalRequests * 100).toFixed(1);
      console.log(`  ${model}: ${a.bold(count)} (${percentage}%)`);
    }
  }
  console.log(a.dim(`
${"\u2500".repeat(60)}
`));
}
function displayCSV(stats2) {
  console.log("metric,value");
  console.log(`total_requests,${stats2.totalRequests}`);
  console.log(`successful_requests,${stats2.successfulRequests}`);
  console.log(`failed_requests,${stats2.failedRequests}`);
  console.log(`success_rate,${stats2.successRate.toFixed(2)}`);
  console.log(`total_input_tokens,${stats2.totalInputTokens}`);
  console.log(`total_output_tokens,${stats2.totalOutputTokens}`);
  console.log(`total_tokens,${stats2.totalTokens}`);
  console.log(`total_cost,${stats2.totalCost.toFixed(4)}`);
  console.log(`average_latency,${stats2.averageLatency.toFixed(0)}`);
}
async function exportStats(stats2, filePath, format) {
  const { writeFileSync } = await import('node:fs');
  let content;
  if (format === "json") {
    content = JSON.stringify(stats2, null, 2);
  } else if (format === "csv") {
    const lines = [
      "metric,value",
      `total_requests,${stats2.totalRequests}`,
      `successful_requests,${stats2.successfulRequests}`,
      `failed_requests,${stats2.failedRequests}`,
      `success_rate,${stats2.successRate.toFixed(2)}`,
      `total_input_tokens,${stats2.totalInputTokens}`,
      `total_output_tokens,${stats2.totalOutputTokens}`,
      `total_tokens,${stats2.totalTokens}`,
      `total_cost,${stats2.totalCost.toFixed(4)}`,
      `average_latency,${stats2.averageLatency.toFixed(0)}`
    ];
    content = lines.join("\n");
  } else {
    content = JSON.stringify(stats2, null, 2);
  }
  writeFileSync(filePath, content, "utf-8");
}
async function listStatsDates() {
  const storage = getStatsStorage();
  const dates = storage.getAvailableDates();
  if (dates.length === 0) {
    console.log(a.yellow("\nNo statistics data available\n"));
    return;
  }
  console.log(a.cyan.bold("\n\u{1F4C5} Available Statistics Dates:"));
  console.log(a.dim("\u2500".repeat(40)));
  for (const date of dates) {
    const records = storage.getRecordsByDate(date);
    console.log(`  ${date}: ${a.bold(records.length)} requests`);
  }
  console.log(a.dim(`
${"\u2500".repeat(40)}
`));
}
async function storageStats() {
  const storage = getStatsStorage();
  const stats2 = storage.getStorageStats();
  console.log(a.cyan.bold("\n\u{1F4BE} Storage Statistics:"));
  console.log(a.dim("\u2500".repeat(40)));
  console.log(`  Total record files: ${a.bold(stats2.totalRecordFiles)}`);
  console.log(`  Total daily files: ${a.bold(stats2.totalDailyFiles)}`);
  console.log(`  Total records: ${a.bold(stats2.totalRecords.toLocaleString())}`);
  console.log(`  Oldest date: ${a.bold(stats2.oldestDate || "N/A")}`);
  console.log(`  Newest date: ${a.bold(stats2.newestDate || "N/A")}`);
  console.log(a.dim(`
${"\u2500".repeat(40)}
`));
}
async function cleanupStats(daysToKeep = 90) {
  const storage = getStatsStorage();
  const deletedCount = storage.cleanupOldRecords(daysToKeep);
  console.log(a.green(`
\u2713 Cleanup complete: ${deletedCount} old records marked for deletion
`));
}

export { cleanupStats, listStatsDates, stats, storageStats };
