import { z } from 'zod';
import { createCommand } from '../../../types';
import * as tui from '../../../tui';
import { createStorageAdapter } from './util';
import { getCommand } from '../../../command-prefix';
const KVStatsResponseSchema = z.union([
    z.object({
        namespace: z.string().describe('Namespace name'),
        count: z.number().describe('Number of keys'),
        sum: z.number().describe('Total size in bytes'),
        createdAt: z.string().optional().describe('Creation timestamp'),
        lastUsedAt: z.string().optional().describe('Last used timestamp'),
    }),
    z.record(z.string(), z.object({
        count: z.number().describe('Number of keys'),
        sum: z.number().describe('Total size in bytes'),
        createdAt: z.string().optional().describe('Creation timestamp'),
        lastUsedAt: z.string().optional().describe('Last used timestamp'),
    })),
]);
export const statsSubcommand = createCommand({
    name: 'stats',
    description: 'Get statistics for keyvalue storage',
    tags: ['read-only', 'fast', 'requires-auth'],
    requires: { auth: true, region: true },
    optional: { project: true },
    idempotent: true,
    examples: [
        { command: getCommand('kv stats'), description: 'Show stats for all namespaces' },
        {
            command: getCommand('kv stats production'),
            description: 'Show stats for production namespace',
        },
        { command: getCommand('kv stats cache'), description: 'Show stats for cache namespace' },
    ],
    schema: {
        args: z.object({
            name: z.string().optional().describe('the keyvalue namespace'),
        }),
        response: KVStatsResponseSchema,
    },
    webUrl: (ctx) => ctx.args.name ? `/services/kv/${encodeURIComponent(ctx.args.name)}` : '/services/kv',
    async handler(ctx) {
        const { args, options } = ctx;
        const kv = await createStorageAdapter(ctx);
        if (args.name) {
            const stats = await kv.getStats(args.name);
            if (!options.json) {
                tui.info(`Statistics for ${tui.bold(args.name)}:`);
                tui.info(`  Keys: ${stats.count}`);
                const sizeDisplay = stats.sum < 1024 * 1024
                    ? `${stats.sum.toLocaleString()} bytes`
                    : `${(stats.sum / (1024 * 1024)).toFixed(2)} MB`;
                tui.info(`  Total size: ${sizeDisplay} (raw: ${stats.sum})`);
                if (stats.createdAt) {
                    tui.info(`  Created: ${new Date(stats.createdAt).toLocaleString()}`);
                }
                if (stats.lastUsedAt) {
                    tui.info(`  Last used: ${new Date(stats.lastUsedAt).toLocaleString()}`);
                }
            }
            return {
                namespace: args.name,
                count: stats.count,
                sum: stats.sum,
                createdAt: stats.createdAt ? String(stats.createdAt) : undefined,
                lastUsedAt: stats.lastUsedAt ? String(stats.lastUsedAt) : undefined,
            };
        }
        else {
            const allStats = await kv.getAllStats();
            const entries = Object.entries(allStats);
            if (!options.json) {
                if (entries.length === 0) {
                    tui.info('No namespaces found');
                }
                else {
                    tui.info(`Found ${entries.length} ${tui.plural(entries.length, 'namespace', 'namespaces')}:`);
                    for (const [name, stats] of entries) {
                        const sizeDisplay = stats.sum < 1024 * 1024
                            ? `${stats.sum.toLocaleString()} bytes`
                            : `${(stats.sum / (1024 * 1024)).toFixed(2)} MB`;
                        tui.arrow(`${tui.bold(name.padEnd(15, ' '))}: ${stats.count} keys, ${sizeDisplay}`);
                    }
                }
            }
            // Convert timestamp fields to strings
            const result = {};
            for (const [name, stats] of entries) {
                result[name] = {
                    count: stats.count,
                    sum: stats.sum,
                    createdAt: stats.createdAt ? String(stats.createdAt) : undefined,
                    lastUsedAt: stats.lastUsedAt ? String(stats.lastUsedAt) : undefined,
                };
            }
            return result;
        }
    },
});
export default statsSubcommand;
//# sourceMappingURL=stats.js.map