/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { Messages } from '@salesforce/core';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { effortPath, listEffortEstimates, summarizeEffort } from '../../../services/workflow-effort.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@jterrats/setup-agents', 'setup-agents.workflow.telemetry');
const MODE_LABEL_ENTRIES = [
    ['ai_autonomous', 'AI Autónomo'],
    ['ai_supervised', 'AI Supervisado'],
    ['ai_calibration_baseline', 'Calibration Baseline'],
    ['human_manual', 'Human Manual'],
    ['human_review', 'Human Review'],
];
const MODE_LABELS = new Map(MODE_LABEL_ENTRIES);
export default class WorkflowTelemetry extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        story: Flags.string({
            char: 's',
            summary: messages.getMessage('flags.story.summary'),
            description: messages.getMessage('flags.story.description'),
        }),
        recalculate: Flags.boolean({
            summary: messages.getMessage('flags.recalculate.summary'),
            description: messages.getMessage('flags.recalculate.description'),
            default: false,
        }),
    };
    async run() {
        const { flags } = await this.parse(WorkflowTelemetry);
        const cwd = process.cwd();
        const file = effortPath(cwd);
        const records = listEffortEstimates(cwd, flags.story);
        if (records.length === 0) {
            this.log(messages.getMessage('info.empty'));
            const summary = summarizeEffort([], flags.story ?? null);
            return { records, summary, file, cwd };
        }
        const summary = summarizeEffort(records, flags.story ?? null);
        if (flags.story) {
            this.log(messages.getMessage('info.story-header', [flags.story]));
        }
        else {
            this.log(messages.getMessage('info.aggregate-header', [records.length]));
        }
        this.log('');
        this.logModeBreakdown(summary);
        this.logTotals(summary);
        this.logTokenCosts(summary);
        return { records, summary, file, cwd };
    }
    logModeBreakdown(summary) {
        const modes = [
            'ai_autonomous',
            'ai_supervised',
            'ai_calibration_baseline',
            'human_manual',
            'human_review',
        ];
        for (const mode of modes) {
            const mins = summary.byMode[mode] ?? 0;
            if (mins === 0)
                continue;
            const pct = summary.totalMinutes > 0 ? Math.round((mins / summary.totalMinutes) * 100) : 0;
            this.log(messages.getMessage('info.by-mode', [MODE_LABELS.get(mode) ?? mode, mins, pct]));
        }
    }
    logTotals(summary) {
        this.log('');
        this.log(messages.getMessage('info.total', [summary.totalMinutes]));
        this.log(messages.getMessage('info.autonomy', [summary.autonomyPct !== null ? `${summary.autonomyPct}%` : '—']));
        if (summary.rulesMultiplier !== null) {
            this.log(`  Rules multiplier:  ${summary.rulesMultiplier}x (unguided/actual)`);
        }
    }
    logTokenCosts(summary) {
        if (!summary.tokenCost)
            return;
        this.log('');
        this.log(messages.getMessage('info.token-cost-header'));
        this.log(messages.getMessage('info.token-cost-total', [summary.tokenCost.totalCostUsd.toFixed(4)]));
        for (const [mode, entry] of Object.entries(summary.tokenCost.byMode)) {
            this.log(messages.getMessage('info.token-cost-by-mode', [
                MODE_LABELS.get(mode) ?? mode,
                entry.costUsd.toFixed(4),
                entry.phases,
            ]));
        }
        const storyEntries = Object.entries(summary.tokenCost.byStory).sort(([, a], [, b]) => b - a);
        if (storyEntries.length > 1) {
            this.log('');
            this.log(messages.getMessage('info.token-cost-by-story-header'));
            for (const [story, cost] of storyEntries) {
                this.log(messages.getMessage('info.token-cost-by-story', [story, cost.toFixed(4)]));
            }
        }
    }
}
//# sourceMappingURL=telemetry.js.map