import { getServiceStats } from '@agentuity/server';
import { z } from 'zod';
import { getCommand } from "../../../command-prefix.js";
import { getGlobalCatalystAPIClient } from "../../../config.js";
import * as tui from "../../../tui.js";
import { createCommand } from "../../../types.js";
function formatNumber(n) {
    if (n >= 1_000_000)
        return `${(n / 1_000_000).toFixed(1)}M`;
    if (n >= 1_000)
        return `${(n / 1_000).toFixed(1)}K`;
    return String(n);
}
function displayStats(data) {
    const svc = data.services.database;
    if (!svc) {
        tui.info('No database data found.');
        return;
    }
    tui.header('Database Statistics');
    tui.newline();
    console.log(`  ${tui.muted('Databases:')}       ${formatNumber(svc.databaseCount)}`);
    console.log(`  ${tui.muted('Tables:')}          ${formatNumber(svc.totalTableCount)}`);
    console.log(`  ${tui.muted('Records:')}         ${formatNumber(svc.totalRecordCount)}`);
    console.log(`  ${tui.muted('Total Size:')}      ${tui.formatBytes(svc.totalSizeBytes)}`);
}
export const statsSubcommand = createCommand({
    name: 'stats',
    description: 'View database statistics',
    tags: ['read-only', 'requires-auth'],
    requires: { auth: true, org: true },
    examples: [
        {
            command: getCommand('cloud db stats'),
            description: 'View database statistics',
        },
    ],
    schema: {
        options: z.object({
            start: z.string().optional().describe('Start time (ISO 8601)'),
            end: z.string().optional().describe('End time (ISO 8601)'),
        }),
    },
    idempotent: true,
    async handler(ctx) {
        const { opts, options } = ctx;
        const client = await getGlobalCatalystAPIClient(ctx.logger, ctx.auth, ctx.config?.name, undefined, ctx.config);
        const orgId = ctx.orgId ?? ctx.options.orgId ?? ctx.config?.preferences?.orgId;
        if (!orgId) {
            ctx.logger.fatal('Organization ID is required. Use --org-id or set a preferred org.');
            return;
        }
        const data = await getServiceStats(client, orgId, {
            service: 'database',
            start: opts.start,
            end: opts.end,
            orgIdHeader: orgId,
        });
        if (!options.json) {
            displayStats(data);
        }
        return data;
    },
});
//# sourceMappingURL=stats.js.map