/*
 * 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, lstatSync, readdirSync, readlinkSync } 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.status');
export default class CanvasStatus 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'),
        }),
    };
    async run() {
        const { flags } = await this.parse(CanvasStatus);
        const cwd = flags.path ?? process.cwd();
        if (!isCanvasToolActive(cwd)) {
            this.warn(messages.getMessage('warn.cursorNotActive'));
        }
        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 canvases = sources.map((src) => {
            const name = basename(src);
            const cachePath = join(cacheDir, name);
            return { name, state: getState(cachePath, src) };
        });
        // Find orphans
        const sourceNames = new Set(sources.map((s) => basename(s)));
        const orphans = existsSync(cacheDir)
            ? readdirSync(cacheDir).filter((f) => f.endsWith('.canvas.tsx') && !sourceNames.has(f))
            : [];
        if (!this.jsonEnabled()) {
            this.log(messages.getMessage('info.header', [projectDir, cacheDir]));
            this.log('');
            const nameWidth = Math.max(6, ...canvases.map((c) => c.name.length));
            this.log(`${'Canvas'.padEnd(nameWidth)}  State`);
            this.log(`${'------'.padEnd(nameWidth)}  -----`);
            for (const canvas of canvases) {
                this.log(`${canvas.name.padEnd(nameWidth)}  ${canvas.state}`);
            }
            if (orphans.length > 0) {
                this.log('');
                for (const orphan of orphans) {
                    this.warn(messages.getMessage('warn.orphan', [orphan]));
                }
            }
        }
        return { canvases, orphans, cacheDir, cwd };
    }
}
function getState(cachePath, src) {
    try {
        const stat = lstatSync(cachePath);
        if (stat.isSymbolicLink()) {
            return readlinkSync(cachePath) === src ? 'symlink-ok' : 'symlink-wrong';
        }
        if (stat.isFile())
            return 'regular';
    }
    catch {
        // not found
    }
    return 'missing';
}
//# sourceMappingURL=status.js.map