import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Box, Text, useStdout } from 'ink';
import { ThemedGradient } from './ThemedGradient.js';
import { theme } from '../semantic-colors.js';
import { formatDuration, formatResetTime } from '../utils/formatters.js';
import { useSessionStats, } from '../contexts/SessionContext.js';
import { getStatusColor, TOOL_SUCCESS_RATE_HIGH, TOOL_SUCCESS_RATE_MEDIUM, USER_AGREEMENT_RATE_HIGH, USER_AGREEMENT_RATE_MEDIUM, CACHE_EFFICIENCY_HIGH, CACHE_EFFICIENCY_MEDIUM, getUsedStatusColor, QUOTA_USED_WARNING_THRESHOLD, QUOTA_USED_CRITICAL_THRESHOLD, } from '../utils/displayUtils.js';
import { computeSessionStats } from '../utils/computeStats.js';
import { isActiveModel, getDisplayString, isAutoModel, AuthType, } from '@google/gemini-cli-core';
import { useSettings } from '../contexts/SettingsContext.js';
import { useConfig } from '../contexts/ConfigContext.js';
import { QuotaStatsInfo } from './QuotaStatsInfo.js';
const StatRow = ({ title, children }) => (_jsxs(Box, { children: [_jsx(Box, { width: 28, children: _jsx(Text, { color: theme.text.link, children: title }) }), children] }));
const SubStatRow = ({ title, children }) => (_jsxs(Box, { paddingLeft: 2, children: [_jsx(Box, { width: 26, children: _jsxs(Text, { color: theme.text.secondary, children: ["\u00BB ", title] }) }), children] }));
const Section = ({ title, children }) => (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { bold: true, color: theme.text.primary, children: title }), children] }));
// Logic for building the unified list of table rows
const buildModelRows = (models, config, quotas, useGemini3_1 = false, useCustomToolModel = false) => {
    const getBaseModelName = (name) => name.replace('-001', '');
    const usedModelNames = new Set(Object.keys(models)
        .map(getBaseModelName)
        .map((name) => getDisplayString(name, config)));
    // 1. Models with active usage
    const activeRows = Object.entries(models).map(([name, metrics]) => {
        const modelName = getBaseModelName(name);
        const cachedTokens = metrics.tokens.cached;
        const inputTokens = metrics.tokens.input;
        return {
            key: name,
            modelName: getDisplayString(modelName, config),
            requests: metrics.api.totalRequests,
            cachedTokens: cachedTokens.toLocaleString(),
            inputTokens: inputTokens.toLocaleString(),
            outputTokens: metrics.tokens.candidates.toLocaleString(),
            bucket: quotas?.buckets?.find((b) => b.modelId === modelName),
            isActive: true,
        };
    });
    // 2. Models with quota only
    const quotaRows = quotas?.buckets
        ?.filter((b) => b.modelId &&
        isActiveModel(b.modelId, useGemini3_1, useCustomToolModel) &&
        !usedModelNames.has(getDisplayString(b.modelId, config)))
        .map((bucket) => ({
        key: bucket.modelId,
        modelName: getDisplayString(bucket.modelId, config),
        requests: '-',
        cachedTokens: '-',
        inputTokens: '-',
        outputTokens: '-',
        bucket,
        isActive: false,
    })) || [];
    return [...activeRows, ...quotaRows];
};
const ModelUsageTable = ({ models, config, quotas, cacheEfficiency, totalCachedTokens, currentModel, pooledRemaining, pooledLimit, pooledResetTime, useGemini3_1, useCustomToolModel, }) => {
    const { stdout } = useStdout();
    const terminalWidth = stdout?.columns ?? 84;
    const rows = buildModelRows(models, config, quotas, useGemini3_1, useCustomToolModel);
    if (rows.length === 0) {
        return null;
    }
    const showQuotaColumn = !!quotas && rows.some((row) => !!row.bucket);
    const nameWidth = 23;
    const requestsWidth = 5;
    const uncachedWidth = 15;
    const cachedWidth = 14;
    const outputTokensWidth = 15;
    const percentageWidth = showQuotaColumn ? 6 : 0;
    const resetWidth = 22;
    // Total width of other columns (including parent box paddingX={2})
    const fixedWidth = nameWidth + requestsWidth + percentageWidth + resetWidth;
    const outerPadding = 4;
    const availableForUsage = terminalWidth - outerPadding - fixedWidth;
    const usageLimitWidth = showQuotaColumn
        ? Math.max(10, Math.min(24, availableForUsage))
        : 0;
    const progressBarWidth = Math.max(2, usageLimitWidth - 4);
    const renderProgressBar = (usedFraction, color, totalSteps = 20) => {
        let filledSteps = Math.round(usedFraction * totalSteps);
        // If something is used (fraction > 0) but rounds to 0, show 1 tick.
        // If < 100% (fraction < 1) but rounds to 20, show 19 ticks.
        if (usedFraction > 0 && usedFraction < 1) {
            filledSteps = Math.min(Math.max(filledSteps, 1), totalSteps - 1);
        }
        const emptySteps = Math.max(0, totalSteps - filledSteps);
        return (_jsx(Box, { flexDirection: "row", flexShrink: 0, children: _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: color, children: '▬'.repeat(filledSteps) }), _jsx(Text, { color: theme.border.default, children: '▬'.repeat(emptySteps) })] }) }));
    };
    const cacheEfficiencyColor = getStatusColor(cacheEfficiency, {
        green: CACHE_EFFICIENCY_HIGH,
        yellow: CACHE_EFFICIENCY_MEDIUM,
    });
    const totalWidth = nameWidth +
        requestsWidth +
        (showQuotaColumn
            ? usageLimitWidth + percentageWidth + resetWidth
            : uncachedWidth + cachedWidth + outputTokensWidth);
    const isAuto = currentModel && isAutoModel(currentModel);
    return (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [isAuto &&
                showQuotaColumn &&
                pooledRemaining !== undefined &&
                pooledLimit !== undefined &&
                pooledLimit > 0 && (_jsxs(Box, { flexDirection: "column", marginTop: 0, marginBottom: 1, children: [_jsx(QuotaStatsInfo, { remaining: pooledRemaining, limit: pooledLimit, resetTime: pooledResetTime }), _jsx(Text, { color: theme.text.primary, children: "For a full token breakdown, run `/stats model`." })] })), _jsxs(Box, { alignItems: "flex-end", children: [_jsx(Box, { width: nameWidth, flexShrink: 0, children: _jsx(Text, { bold: true, color: theme.text.primary, children: "Model" }) }), _jsx(Box, { width: requestsWidth, flexDirection: "column", alignItems: "flex-end", flexShrink: 0, children: _jsx(Text, { bold: true, color: theme.text.primary, children: "Reqs" }) }), !showQuotaColumn && (_jsxs(_Fragment, { children: [_jsx(Box, { width: uncachedWidth, flexDirection: "column", alignItems: "flex-end", flexShrink: 0, children: _jsx(Text, { bold: true, color: theme.text.primary, children: "Input Tokens" }) }), _jsx(Box, { width: cachedWidth, flexDirection: "column", alignItems: "flex-end", flexShrink: 0, children: _jsx(Text, { bold: true, color: theme.text.primary, children: "Cache Reads" }) }), _jsx(Box, { width: outputTokensWidth, flexDirection: "column", alignItems: "flex-end", flexShrink: 0, children: _jsx(Text, { bold: true, color: theme.text.primary, children: "Output Tokens" }) })] })), showQuotaColumn && (_jsxs(_Fragment, { children: [_jsx(Box, { width: usageLimitWidth, flexDirection: "column", alignItems: "flex-start", paddingLeft: 4, flexShrink: 0, children: _jsx(Text, { bold: true, color: theme.text.primary, children: "Model usage" }) }), _jsx(Box, { width: percentageWidth, flexShrink: 0 }), _jsx(Box, { width: resetWidth, flexDirection: "column", alignItems: "flex-start", paddingLeft: 2, flexShrink: 0, children: _jsx(Text, { bold: true, color: theme.text.primary, wrap: "truncate-end", children: "Usage resets" }) })] }))] }), _jsx(Box, { borderStyle: "round", borderBottom: true, borderTop: false, borderLeft: false, borderRight: false, borderColor: theme.border.default, width: totalWidth }), rows.map((row) => {
                let effectiveUsedFraction = 0;
                let usedPercentage = 0;
                let statusColor = theme.ui.comment;
                let percentageText = '';
                if (row.bucket && row.bucket.remainingFraction != null) {
                    const actualUsedFraction = 1 - row.bucket.remainingFraction;
                    effectiveUsedFraction =
                        actualUsedFraction === 0 && row.isActive
                            ? 0.001
                            : actualUsedFraction;
                    usedPercentage = effectiveUsedFraction * 100;
                    statusColor =
                        getUsedStatusColor(usedPercentage, {
                            warning: QUOTA_USED_WARNING_THRESHOLD,
                            critical: QUOTA_USED_CRITICAL_THRESHOLD,
                        }) ?? (row.isActive ? theme.text.primary : theme.ui.comment);
                    percentageText =
                        usedPercentage > 0 && usedPercentage < 1
                            ? `${usedPercentage.toFixed(1)}%`
                            : `${usedPercentage.toFixed(0)}%`;
                }
                return (_jsxs(Box, { children: [_jsx(Box, { width: nameWidth, flexShrink: 0, children: _jsx(Text, { color: row.isActive ? theme.text.primary : theme.text.secondary, wrap: "truncate-end", children: row.modelName }) }), _jsx(Box, { width: requestsWidth, flexDirection: "column", alignItems: "flex-end", flexShrink: 0, children: _jsx(Text, { color: row.isActive ? theme.text.primary : theme.text.secondary, children: row.requests }) }), !showQuotaColumn && (_jsxs(_Fragment, { children: [_jsx(Box, { width: uncachedWidth, flexDirection: "column", alignItems: "flex-end", flexShrink: 0, children: _jsx(Text, { color: row.isActive ? theme.text.primary : theme.text.secondary, children: row.inputTokens }) }), _jsx(Box, { width: cachedWidth, flexDirection: "column", alignItems: "flex-end", flexShrink: 0, children: _jsx(Text, { color: theme.text.secondary, children: row.cachedTokens }) }), _jsx(Box, { width: outputTokensWidth, flexDirection: "column", alignItems: "flex-end", flexShrink: 0, children: _jsx(Text, { color: row.isActive ? theme.text.primary : theme.text.secondary, children: row.outputTokens }) })] })), showQuotaColumn && (_jsxs(_Fragment, { children: [_jsx(Box, { width: usageLimitWidth, flexDirection: "column", alignItems: "flex-start", paddingLeft: 4, flexShrink: 0, children: row.bucket && row.bucket.remainingFraction != null && (_jsx(Box, { flexDirection: "row", flexShrink: 0, children: renderProgressBar(effectiveUsedFraction, statusColor, progressBarWidth) })) }), _jsx(Box, { width: percentageWidth, flexDirection: "column", alignItems: "flex-end", flexShrink: 0, children: row.bucket && row.bucket.remainingFraction != null && (_jsx(Box, { children: row.bucket.remainingFraction === 0 ? (_jsx(Text, { color: theme.status.error, wrap: "truncate-end", children: "Limit" })) : (_jsx(Text, { color: statusColor, wrap: "truncate-end", children: percentageText })) })) }), _jsx(Box, { width: resetWidth, flexDirection: "column", alignItems: "flex-start", paddingLeft: 2, flexShrink: 0, children: _jsx(Text, { color: theme.text.secondary, wrap: "truncate-end", children: row.bucket?.resetTime &&
                                            formatResetTime(row.bucket.resetTime, 'column')
                                            ? formatResetTime(row.bucket.resetTime, 'column')
                                            : '' }) })] }))] }, row.key));
            }), cacheEfficiency > 0 && !showQuotaColumn && (_jsx(Box, { flexDirection: "column", marginTop: 1, children: _jsxs(Text, { color: theme.text.primary, children: [_jsx(Text, { color: theme.status.success, children: "Savings Highlight:" }), ' ', totalCachedTokens.toLocaleString(), " (", _jsxs(Text, { color: cacheEfficiencyColor, children: [cacheEfficiency.toFixed(1), "%"] }), ") of input tokens were served from the cache, reducing costs."] }) }))] }));
};
export const StatsDisplay = ({ duration, title, quotas, footer, selectedAuthType, userEmail, tier, currentModel, quotaStats, creditBalance, }) => {
    const { stats } = useSessionStats();
    const { metrics } = stats;
    const { models, tools, files } = metrics;
    const computed = computeSessionStats(metrics);
    const settings = useSettings();
    const config = useConfig();
    const useGemini3_1 = config.getGemini31LaunchedSync?.() ?? false;
    const useCustomToolModel = useGemini3_1 &&
        config.getContentGeneratorConfig().authType === AuthType.USE_GEMINI;
    const pooledRemaining = quotaStats?.remaining;
    const pooledLimit = quotaStats?.limit;
    const pooledResetTime = quotaStats?.resetTime;
    const showUserIdentity = settings.merged.ui.showUserIdentity;
    const successThresholds = {
        green: TOOL_SUCCESS_RATE_HIGH,
        yellow: TOOL_SUCCESS_RATE_MEDIUM,
    };
    const agreementThresholds = {
        green: USER_AGREEMENT_RATE_HIGH,
        yellow: USER_AGREEMENT_RATE_MEDIUM,
    };
    const successColor = getStatusColor(computed.successRate, successThresholds);
    const agreementColor = getStatusColor(computed.agreementRate, agreementThresholds);
    const renderTitle = () => {
        if (title) {
            return _jsx(ThemedGradient, { bold: true, children: title });
        }
        return (_jsx(Text, { bold: true, color: theme.text.accent, children: "Session Stats" }));
    };
    const renderFooter = () => {
        if (!footer) {
            return null;
        }
        return _jsx(ThemedGradient, { bold: true, children: footer });
    };
    return (_jsxs(Box, { borderStyle: "round", borderColor: theme.border.default, flexDirection: "column", paddingTop: 1, paddingX: 2, overflow: "hidden", children: [renderTitle(), _jsx(Box, { height: 1 }), _jsxs(Section, { title: "Interaction Summary", children: [_jsx(StatRow, { title: "Session ID:", children: _jsx(Text, { color: theme.text.primary, children: stats.sessionId }) }), showUserIdentity && selectedAuthType && (_jsx(StatRow, { title: "Auth Method:", children: _jsx(Text, { color: theme.text.primary, children: selectedAuthType.startsWith('oauth')
                                ? userEmail
                                    ? `Signed in with Google (${userEmail})`
                                    : 'Signed in with Google'
                                : selectedAuthType }) })), showUserIdentity && tier && (_jsx(StatRow, { title: "Tier:", children: _jsx(Text, { color: theme.text.primary, children: tier }) })), showUserIdentity && creditBalance != null && creditBalance >= 0 && (_jsx(StatRow, { title: "Google AI Credits:", children: _jsx(Text, { color: creditBalance > 0 ? theme.text.primary : theme.text.secondary, children: creditBalance.toLocaleString() }) })), _jsx(StatRow, { title: "Tool Calls:", children: _jsxs(Text, { color: theme.text.primary, children: [tools.totalCalls, " (", ' ', _jsxs(Text, { color: theme.status.success, children: ["\u2713 ", tools.totalSuccess] }), ' ', _jsxs(Text, { color: theme.status.error, children: ["x ", tools.totalFail] }), " )"] }) }), _jsx(StatRow, { title: "Success Rate:", children: _jsxs(Text, { color: successColor, children: [computed.successRate.toFixed(1), "%"] }) }), computed.totalDecisions > 0 && (_jsx(StatRow, { title: "User Agreement:", children: _jsxs(Text, { color: agreementColor, children: [computed.agreementRate.toFixed(1), "%", ' ', _jsxs(Text, { color: theme.text.secondary, children: ["(", computed.totalDecisions, " reviewed)"] })] }) })), files &&
                        (files.totalLinesAdded > 0 || files.totalLinesRemoved > 0) && (_jsx(StatRow, { title: "Code Changes:", children: _jsxs(Text, { color: theme.text.primary, children: [_jsxs(Text, { color: theme.status.success, children: ["+", files.totalLinesAdded] }), ' ', _jsxs(Text, { color: theme.status.error, children: ["-", files.totalLinesRemoved] })] }) }))] }), _jsxs(Section, { title: "Performance", children: [_jsx(StatRow, { title: "Wall Time:", children: _jsx(Text, { color: theme.text.primary, children: duration }) }), _jsx(StatRow, { title: "Agent Active:", children: _jsx(Text, { color: theme.text.primary, children: formatDuration(computed.agentActiveTime) }) }), _jsx(SubStatRow, { title: "API Time:", children: _jsxs(Text, { color: theme.text.primary, children: [formatDuration(computed.totalApiTime), ' ', _jsxs(Text, { color: theme.text.secondary, children: ["(", computed.apiTimePercent.toFixed(1), "%)"] })] }) }), _jsx(SubStatRow, { title: "Tool Time:", children: _jsxs(Text, { color: theme.text.primary, children: [formatDuration(computed.totalToolTime), ' ', _jsxs(Text, { color: theme.text.secondary, children: ["(", computed.toolTimePercent.toFixed(1), "%)"] })] }) })] }), _jsx(ModelUsageTable, { models: models, config: config, quotas: quotas, cacheEfficiency: computed.cacheEfficiency, totalCachedTokens: computed.totalCachedTokens, currentModel: currentModel, pooledRemaining: pooledRemaining, pooledLimit: pooledLimit, pooledResetTime: pooledResetTime, useGemini3_1: useGemini3_1, useCustomToolModel: useCustomToolModel }), renderFooter()] }));
};
//# sourceMappingURL=StatsDisplay.js.map