/*
 * 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 { execFile } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { Messages } from '@salesforce/core';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { computeMetrics, generateDashboardHtml } from '../../generators/dashboard-generator.js';
import { listWorkflowRuns } from '../../services/workflow-state.js';
import { listTasks } from '../../services/task-state.js';
import { listEffortEstimates } from '../../services/workflow-effort.js';
import { listEstimates } from '../../services/workflow-benchmark.js';
import { listRecords } from '../../services/orchestration-records.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@jterrats/setup-agents', 'setup-agents.dashboard');
const DEFAULT_OUTPUT = 'docs/dashboard.html';
export default class Dashboard extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        output: Flags.string({
            char: 'p',
            summary: messages.getMessage('flags.output.summary'),
            description: messages.getMessage('flags.output.description'),
            default: DEFAULT_OUTPUT,
        }),
        open: Flags.boolean({
            summary: messages.getMessage('flags.open.summary'),
            default: false,
        }),
        format: Flags.string({
            char: 'f',
            summary: messages.getMessage('flags.format.summary'),
            description: messages.getMessage('flags.format.description'),
            options: ['html', 'json'],
            default: 'html',
        }),
    };
    async run() {
        const { flags } = await this.parse(Dashboard);
        const cwd = process.cwd();
        const format = flags.format;
        const tasks = listTasks(cwd);
        const runs = listWorkflowRuns(cwd);
        const effortRecords = listEffortEstimates(cwd);
        const handoffs = listRecords(cwd, 'handoff');
        const sizingEstimates = listEstimates(cwd);
        const projectName = readProjectName(cwd);
        const metrics = computeMetrics(tasks, runs, projectName, effortRecords, handoffs, sizingEstimates);
        if (format === 'json') {
            this.log(JSON.stringify(metrics, null, 2));
            return { metrics, outputPath: null, format, cwd };
        }
        const outputPath = resolve(cwd, flags.output);
        const outDir = dirname(outputPath);
        if (!existsSync(outDir))
            mkdirSync(outDir, { recursive: true });
        const html = generateDashboardHtml(metrics);
        writeFileSync(outputPath, html, 'utf8');
        this.log(messages.getMessage('info.written', [outputPath]));
        if (flags.open) {
            this.log(messages.getMessage('info.opening'));
            openInBrowser(outputPath);
        }
        return { metrics, outputPath, format, cwd };
    }
}
function readProjectName(cwd) {
    const sfdxPath = join(cwd, 'sfdx-project.json');
    if (existsSync(sfdxPath)) {
        try {
            const parsed = JSON.parse(readFileSync(sfdxPath, 'utf8'));
            if (parsed.name)
                return parsed.name;
        }
        catch {
            // fall through
        }
    }
    return cwd.split('/').pop() ?? 'Project';
}
const PLATFORM_OPENER = { darwin: 'open', win32: 'start' };
function openInBrowser(filePath) {
    const opener = PLATFORM_OPENER[process.platform] ?? 'xdg-open';
    execFile(opener, [filePath], () => undefined);
}
//# sourceMappingURL=dashboard.js.map