/*
 * 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 { existsSync, readdirSync, rmSync } from 'node:fs';
import { basename, join } from 'node:path';
import { SfError, Messages } from '@salesforce/core';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { findSourceCanvases, isCanvasToolActive, resolveCacheDir, resolveProjectDir, } from '../../../util/canvas-helpers.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@jterrats/setup-agents', 'setup-agents.canvas.clean');
export default class CanvasClean extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        path: Flags.string({
            summary: messages.getMessage('flags.path.summary'),
        }),
        yes: Flags.boolean({
            summary: messages.getMessage('flags.yes.summary'),
            default: false,
        }),
    };
    async run() {
        const { flags } = await this.parse(CanvasClean);
        const cwd = flags.path ?? process.cwd();
        if (!isCanvasToolActive(cwd)) {
            this.warn('cursor is not listed in workspace tools — skipping canvas clean.');
        }
        const projectDir = resolveProjectDir(cwd);
        const cacheDir = resolveCacheDir(projectDir);
        if (!existsSync(cacheDir)) {
            throw new SfError(messages.getMessage('error.noCacheDir', [cacheDir]));
        }
        const sources = findSourceCanvases(projectDir);
        if (sources.length === 0) {
            throw new SfError(messages.getMessage('error.noSources', [projectDir]));
        }
        const sourceNames = new Set(sources.map((s) => basename(s)));
        const orphans = readdirSync(cacheDir)
            .filter((f) => f.endsWith('.canvas.tsx') && !sourceNames.has(f))
            .map((f) => join(cacheDir, f));
        if (orphans.length === 0) {
            this.log(messages.getMessage('info.none'));
            return { removed: [], cacheDir, cwd };
        }
        const shouldRemove = flags.yes || !process.stdout.isTTY || (await confirmRemoval(orphans.length, cacheDir));
        if (!shouldRemove) {
            return { removed: [], cacheDir, cwd };
        }
        const removed = [];
        for (const orphan of orphans) {
            rmSync(orphan, { force: true });
            const statusFile = orphan.replace(/\.tsx$/, '.status.json');
            rmSync(statusFile, { force: true });
            removed.push(basename(orphan));
        }
        this.log(messages.getMessage('info.removed', [String(removed.length)]));
        return { removed, cacheDir, cwd };
    }
}
async function confirmRemoval(count, cacheDir) {
    const { confirm } = await import('@inquirer/prompts');
    return confirm({
        message: messages.getMessage('prompt.confirm', [String(count), cacheDir]),
        default: false,
    });
}
//# sourceMappingURL=clean.js.map