import { all } from "@/lib/db";
import { UsageView } from "@/components/usage-view";

export const dynamic = "force-dynamic";

type UsageRow = {
  agent: string;
  provider: string;
  model: string;
  tokens_used: number;
  cost_estimate: number;
};

export default async function UsagePage() {
  const rows = await all<UsageRow>("SELECT * FROM usage_tracking ORDER BY timestamp DESC");

  const stats = rows.reduce(
    (accumulator, row) => {
      accumulator.totalRequests += 1;
      accumulator.totalTokens += row.tokens_used || 0;
      accumulator.totalCost += row.cost_estimate || 0;
      if (!accumulator.byAgent[row.agent]) {
        accumulator.byAgent[row.agent] = { requests: 0, tokens: 0, cost: 0 };
      }
      accumulator.byAgent[row.agent].requests += 1;
      accumulator.byAgent[row.agent].tokens += row.tokens_used || 0;
      accumulator.byAgent[row.agent].cost += row.cost_estimate || 0;
      return accumulator;
    },
    {
      totalRequests: 0,
      totalTokens: 0,
      totalCost: 0,
      byAgent: {} as Record<string, { requests: number; tokens: number; cost: number }>,
    },
  );

  return <UsageView stats={stats} />;
}
