/**
 * /permissions slash command handler.
 *
 * The persisted permissioning JSON is the source of truth. This module owns the
 * interactive command flow for viewing and editing that schema so the startup
 * router can remain a thin dispatcher.
 */
import { existsSync, statSync } from 'fs';
import { join } from 'path';
import { getAgentDir } from '../../config.js';
import { resolveToCwd } from '../../shared/files/path-utils.js';
import { formatOpenError, openInEditor } from '../../shared/platform/open.js';
import { confirmRuntimePermissionBypass, formatPermissionBypassStatus, formatPermissionBypassStatusMessage } from './runtime-permission-bypass.js';
import { getRuntimePermissioningFieldSpecByCommand, RUNTIME_PERMISSIONING_FIELD_SPECS } from './settings.js';
/** Return the absolute path to the user-level settings.json file. */
function getGlobalSettingsPath() {
    return join(getAgentDir(), 'settings.json');
}
/** Resolve and validate a workspace-root path; returns the normalized path or an error string. */
function normalizeWorkspaceRoot(input, cwd) {
    const trimmed = input.trim();
    if (!trimmed) {
        return 'Workspace path is required';
    }
    const resolved = resolveToCwd(trimmed, cwd);
    if (!existsSync(resolved)) {
        return `Path does not exist: ${resolved}`;
    }
    try {
        if (!statSync(resolved).isDirectory()) {
            return `Workspace root must be a directory: ${resolved}`;
        }
    }
    catch (error) {
        return error instanceof Error ? error.message : String(error);
    }
    return { ok: true, path: resolved };
}
/** Resolve and validate a filesystem-grant path according to its file/folder scope. */
function normalizeFilesystemGrantPath(input, cwd, scope) {
    const normalized = normalizeWorkspaceRoot(input, cwd);
    if (scope === 'folder') {
        return normalized;
    }
    const trimmed = input.trim();
    if (!trimmed) {
        return 'Grant path is required';
    }
    const resolved = resolveToCwd(trimmed, cwd);
    if (!existsSync(resolved)) {
        return `Path does not exist: ${resolved}`;
    }
    try {
        if (!statSync(resolved).isFile()) {
            return `Grant path must be a file: ${resolved}`;
        }
    }
    catch (error) {
        return error instanceof Error ? error.message : String(error);
    }
    return { ok: true, path: resolved };
}
/** Format a single filesystem grant as `path — Access scope`. */
function formatFilesystemGrant(grant) {
    const access = grant.access === 'read' ? 'Read' : 'Write';
    const scope = grant.scope === 'file' ? 'file' : 'folder';
    return `${grant.path} — ${access} ${scope}`;
}
/** Reduce a set of filesystem grants to a single Read/Write/Read & write display label. */
function getFilesystemGrantAccessLabel(grants) {
    const accesses = new Set(grants.map((grant) => grant.access));
    if (accesses.has('read') && accesses.has('write')) {
        return 'Read & write';
    }
    return accesses.has('write') ? 'Write' : 'Read';
}
/** Bucket filesystem grants by `(path, scope)` for sorted, human-friendly display. */
function groupFilesystemGrants(grants) {
    const grouped = new Map();
    for (const grant of grants) {
        const key = `${grant.path}\u0000${grant.scope}`;
        const existing = grouped.get(key);
        if (existing) {
            existing.push(grant);
        }
        else {
            grouped.set(key, [grant]);
        }
    }
    return [...grouped.values()]
        .map((entries) => {
        const [first] = entries;
        const accessLabel = getFilesystemGrantAccessLabel(entries);
        const scope = first.scope === 'file' ? 'file' : 'folder';
        return {
            path: first.path,
            scope: first.scope,
            grants: [...entries].sort((left, right) => left.access.localeCompare(right.access)),
            accessLabel,
            label: `${first.path} — ${accessLabel} ${scope}`
        };
    })
        .sort((left, right) => left.label.localeCompare(right.label));
}
/** Render all filesystem grants as a comma-separated summary line for status messages. */
function formatFilesystemGrantSummary(grants) {
    return groupFilesystemGrants(grants)
        .map((group) => group.label)
        .join(', ');
}
/** Print the current approved workspace roots, annotating the agent dir specially. */
function showWorkspaceRoots(showStatus, settingsManager, _cwd) {
    const roots = settingsManager.getWorkspaceRoots();
    showStatus(`Approved workspaces: ${roots
        .map((root) => (root === getAgentDir() ? `${root} (ShortcutXL agent workspace)` : root))
        .join(', ')}`);
}
/** Return user-configured workspace roots, excluding the implicit agent dir. */
function getConfiguredWorkspaceRoots(settingsManager) {
    const agentDir = getAgentDir();
    return settingsManager.getWorkspaceRoots().filter((root) => root !== agentDir);
}
/** Add a workspace root to settings after normalizing the path; warns on duplicates. */
function addWorkspaceRoot(showStatus, settingsManager, cwd, rawPath) {
    const normalized = normalizeWorkspaceRoot(rawPath, cwd);
    if (typeof normalized === 'string') {
        showStatus(normalized);
        return;
    }
    const currentRoots = getConfiguredWorkspaceRoots(settingsManager);
    if (currentRoots.includes(normalized.path)) {
        showStatus(`Workspace already approved: ${normalized.path}`);
        return;
    }
    settingsManager.setWorkspaceRoots([...currentRoots, normalized.path]);
    showStatus(`Added workspace root: ${normalized.path}`);
}
/** Remove a workspace root from settings; warns if the path is not configured. */
function removeWorkspaceRoot(showStatus, settingsManager, cwd, rawPath) {
    const normalized = normalizeWorkspaceRoot(rawPath, cwd);
    if (typeof normalized === 'string') {
        showStatus(normalized);
        return;
    }
    const currentRoots = getConfiguredWorkspaceRoots(settingsManager);
    if (!currentRoots.includes(normalized.path)) {
        showStatus(`Workspace not found: ${normalized.path}`);
        return;
    }
    settingsManager.setWorkspaceRoots(currentRoots.filter((root) => root !== normalized.path));
    showStatus(`Removed workspace root: ${normalized.path}`);
}
/** Replace one configured workspace root with a new path in-place. */
function replaceWorkspaceRoot(showStatus, settingsManager, cwd, currentPath, rawPath) {
    const normalized = normalizeWorkspaceRoot(rawPath, cwd);
    if (typeof normalized === 'string') {
        showStatus(normalized);
        return;
    }
    const currentRoots = getConfiguredWorkspaceRoots(settingsManager);
    if (!currentRoots.includes(currentPath)) {
        showStatus(`Workspace not found: ${currentPath}`);
        return;
    }
    if (currentRoots.includes(normalized.path) && normalized.path !== currentPath) {
        showStatus(`Workspace already approved: ${normalized.path}`);
        return;
    }
    settingsManager.setWorkspaceRoots(currentRoots.map((root) => (root === currentPath ? normalized.path : root)));
    showStatus(`Updated workspace: ${currentPath} → ${normalized.path}`);
}
/** Print the persisted filesystem grants, or note that none exist. */
function showFilesystemGrants(showStatus, settingsManager) {
    const grants = settingsManager.getFilesystemApprovals();
    if (grants.length === 0) {
        showStatus('Persistent filesystem grants: none');
        return;
    }
    showStatus(`Persistent filesystem grants: ${formatFilesystemGrantSummary(grants)}`);
}
/** Persist a new filesystem grant with the given path/access/scope, deduplicating exact matches. */
function addFilesystemGrant(showStatus, settingsManager, cwd, rawPath, access, scope) {
    const normalized = normalizeFilesystemGrantPath(rawPath, cwd, scope);
    if (typeof normalized === 'string') {
        showStatus(normalized);
        return;
    }
    const grant = { path: normalized.path, access, scope };
    const current = settingsManager.getFilesystemApprovals();
    const exists = current.some((entry) => entry.path === grant.path && entry.access === grant.access && entry.scope === grant.scope);
    if (exists) {
        showStatus(`Filesystem grant already exists: ${formatFilesystemGrant(grant)}`);
        return;
    }
    settingsManager.addFilesystemApproval(grant);
    showStatus(`Added filesystem grant: ${formatFilesystemGrant(grant)}`);
}
/** Remove one or more filesystem grants from settings and report the change. */
function removeFilesystemGrant(showStatus, settingsManager, grantOrGrants) {
    const grants = Array.isArray(grantOrGrants) ? grantOrGrants : [grantOrGrants];
    for (const grant of grants) {
        settingsManager.removeFilesystemApproval(grant);
    }
    showStatus(`Removed filesystem grant: ${formatFilesystemGrantSummary(grants)}`);
}
/** Open the global settings.json in the user's editor and report the path. */
function openPermissionSettingsFile(showStatus) {
    const settingsPath = getGlobalSettingsPath();
    void openInEditor(settingsPath).catch((error) => showStatus(`Could not open ${settingsPath}: ${formatOpenError(error)}`));
    showStatus(`Opened ${settingsPath}`);
}
/** Interactive sub-flow for the workspace-roots field of `/permissions`. */
async function handleWorkspaceRootsField(showStatus, settingsManager, cwd, select, input, args) {
    if (!args) {
        while (true) {
            const roots = settingsManager.getWorkspaceRoots();
            const rootEntries = roots.map((root) => ({
                path: root,
                label: root === getAgentDir() ? `${root} — ShortcutXL agent workspace` : root
            }));
            const choice = await select('Approved workspaces', [
                ...rootEntries.map((entry) => entry.label),
                'Add workspace',
                'Back'
            ]);
            if (!choice || choice === 'Back') {
                return 'back';
            }
            if (choice === 'Add workspace') {
                const newPath = await input('Add workspace', cwd);
                if (newPath?.trim()) {
                    addWorkspaceRoot(showStatus, settingsManager, cwd, newPath);
                    return true;
                }
                continue;
            }
            const entry = rootEntries.find((candidate) => candidate.label === choice);
            if (!entry) {
                continue;
            }
            const actions = entry.path === getAgentDir() ? ['Back'] : ['Change path', 'Delete', 'Back'];
            const action = await select(choice, actions);
            if (!action || action === 'Back') {
                continue;
            }
            if (action === 'Change path') {
                const nextPath = await input('Change workspace', entry.path);
                if (nextPath?.trim()) {
                    replaceWorkspaceRoot(showStatus, settingsManager, cwd, entry.path, nextPath);
                    return true;
                }
                continue;
            }
            if (action === 'Delete') {
                removeWorkspaceRoot(showStatus, settingsManager, cwd, entry.path);
                return true;
            }
        }
    }
    const subcommandMatch = args.match(/^(\S+)(?:\s+([\s\S]+))?$/);
    const subcommand = subcommandMatch?.[1]?.toLowerCase();
    const value = subcommandMatch?.[2] ?? '';
    if (subcommand === 'list' || subcommand === 'show') {
        showWorkspaceRoots(showStatus, settingsManager, cwd);
        return true;
    }
    if (subcommand === 'open') {
        openPermissionSettingsFile(showStatus);
        return true;
    }
    if (subcommand === 'add') {
        const rawPath = value.trim() || (await input('Add workspace', cwd))?.trim();
        if (rawPath) {
            addWorkspaceRoot(showStatus, settingsManager, cwd, rawPath);
        }
        return true;
    }
    if (subcommand === 'remove' || subcommand === 'rm' || subcommand === 'delete') {
        const rawPath = value.trim();
        if (rawPath) {
            removeWorkspaceRoot(showStatus, settingsManager, cwd, rawPath);
            return true;
        }
        const roots = settingsManager.getWorkspaceRoots();
        if (roots.length <= 1) {
            showStatus('Cannot remove the last workspace root');
            return true;
        }
        const target = await select('Remove workspace root', [...roots, 'Cancel']);
        if (target && target !== 'Cancel') {
            removeWorkspaceRoot(showStatus, settingsManager, cwd, target);
        }
        return true;
    }
    showStatus('Usage: /permissions workspace-roots [list|add <path>|remove <path>|open]');
    return true;
}
/** Interactive sub-flow for filesystem-grants management within `/permissions`. */
async function handleFilesystemGrantsField(showStatus, settingsManager, cwd, select, input, args) {
    if (!args) {
        while (true) {
            const grants = settingsManager.getFilesystemApprovals();
            const grantGroups = groupFilesystemGrants(grants);
            const choice = await select('Approved files & folders outside workspaces', [
                ...grantGroups.map((group) => group.label),
                'Add approved path',
                'Back'
            ]);
            if (!choice || choice === 'Back') {
                return 'back';
            }
            if (choice === 'Add approved path') {
                const rawPath = await input('Path outside workspaces', cwd);
                if (!rawPath?.trim()) {
                    continue;
                }
                const access = await select('Permission', ['Read-only', 'Read & write', 'Back']);
                if (!access || access === 'Back') {
                    continue;
                }
                const scope = await select('Applies to', ['This file', 'This folder', 'Back']);
                if (!scope || scope === 'Back') {
                    continue;
                }
                addFilesystemGrant(showStatus, settingsManager, cwd, rawPath, access === 'Read-only' ? 'read' : 'write', scope === 'This file' ? 'file' : 'folder');
                return true;
            }
            const grantGroup = grantGroups.find((group) => group.label === choice);
            if (!grantGroup) {
                continue;
            }
            const action = await select(choice, ['Edit', 'Delete', 'Back']);
            if (!action || action === 'Back') {
                continue;
            }
            if (action === 'Delete') {
                removeFilesystemGrant(showStatus, settingsManager, grantGroup.grants);
                return true;
            }
            if (action === 'Edit') {
                const rawPath = await input('Path', grantGroup.path);
                if (!rawPath?.trim()) {
                    continue;
                }
                const permissionOptions = grantGroup.accessLabel === 'Read & write'
                    ? ['Read-only', 'Read & write', 'Back']
                    : grantGroup.accessLabel === 'Read'
                        ? ['Read-only', 'Read & write', 'Back']
                        : ['Read & write', 'Read-only', 'Back'];
                const permission = await select('Permission', permissionOptions);
                if (!permission || permission === 'Back') {
                    continue;
                }
                const scope = await select('Applies to', grantGroup.scope === 'file'
                    ? ['This file', 'This folder', 'Back']
                    : ['This folder', 'This file', 'Back']);
                if (!scope || scope === 'Back') {
                    continue;
                }
                const normalized = normalizeFilesystemGrantPath(rawPath, cwd, scope === 'This file' ? 'file' : 'folder');
                if (typeof normalized === 'string') {
                    showStatus(normalized);
                    return true;
                }
                for (const grant of grantGroup.grants) {
                    settingsManager.removeFilesystemApproval(grant);
                }
                const nextScope = scope === 'This file' ? 'file' : 'folder';
                const nextAccesses = permission === 'Read-only' ? ['read'] : ['read', 'write'];
                for (const access of nextAccesses) {
                    settingsManager.addFilesystemApproval({
                        path: normalized.path,
                        access,
                        scope: nextScope
                    });
                }
                showStatus(`Updated filesystem grant: ${grantGroup.label} → ${formatFilesystemGrantSummary(nextAccesses.map((access) => ({
                    path: normalized.path,
                    access,
                    scope: nextScope
                })))}`);
                return true;
            }
        }
    }
    const subcommandMatch = args.match(/^(\S+)(?:\s+([\s\S]+))?$/);
    const subcommand = subcommandMatch?.[1]?.toLowerCase();
    const value = subcommandMatch?.[2] ?? '';
    if (subcommand === 'list' || subcommand === 'show') {
        showFilesystemGrants(showStatus, settingsManager);
        return true;
    }
    if (subcommand === 'add') {
        const parts = value.trim().split(/\s+/);
        const maybeAccess = parts.at(-2);
        const maybeScope = parts.at(-1);
        if (!maybeAccess ||
            !maybeScope ||
            (maybeAccess !== 'read' && maybeAccess !== 'write') ||
            (maybeScope !== 'file' && maybeScope !== 'folder')) {
            showStatus('Usage: /permissions filesystem-grants add <path> <read|write> <file|folder>');
            return true;
        }
        const rawPath = parts.slice(0, -2).join(' ');
        addFilesystemGrant(showStatus, settingsManager, cwd, rawPath, maybeAccess, maybeScope);
        return true;
    }
    if (subcommand === 'remove' || subcommand === 'rm' || subcommand === 'delete') {
        const grants = settingsManager.getFilesystemApprovals();
        if (!value.trim()) {
            if (grants.length === 0) {
                showStatus('No persistent filesystem grants to remove');
                return true;
            }
            const grantGroups = groupFilesystemGrants(grants);
            const options = grantGroups.map((group) => group.label);
            const target = await select('Remove filesystem grant', [...options, 'Cancel']);
            if (target && target !== 'Cancel') {
                const grantGroup = grantGroups.find((group) => group.label === target);
                if (grantGroup) {
                    removeFilesystemGrant(showStatus, settingsManager, grantGroup.grants);
                }
            }
            return true;
        }
        const parts = value.trim().split(/\s+/);
        const maybeAccess = parts.at(-2);
        const maybeScope = parts.at(-1);
        const rawPath = maybeAccess && maybeScope && (maybeAccess === 'read' || maybeAccess === 'write')
            ? parts.slice(0, -2).join(' ')
            : value.trim();
        const candidates = grants.filter((grant) => grant.path === resolveToCwd(rawPath, cwd));
        if (candidates.length === 0) {
            showStatus(`Filesystem grant not found: ${value.trim()}`);
            return true;
        }
        const match = maybeAccess &&
            maybeScope &&
            (maybeAccess === 'read' || maybeAccess === 'write') &&
            (maybeScope === 'file' || maybeScope === 'folder')
            ? candidates.find((grant) => grant.access === maybeAccess && grant.scope === maybeScope)
            : candidates.length === 1
                ? candidates[0]
                : undefined;
        if (!match) {
            showStatus('Multiple grants match that path. Use /permissions filesystem-grants remove <path> <read|write> <file|folder>.');
            return true;
        }
        removeFilesystemGrant(showStatus, settingsManager, match);
        return true;
    }
    showStatus('Usage: /permissions filesystem-grants [list|add <path> <read|write> <file|folder>|remove <path> [read|write] [file|folder]]');
    return true;
}
/** Interactive sub-flow for the spreadsheet-auto-approve toggle. */
async function handleSpreadsheetAutoApproveField(showStatus, settingsManager, cwd, select, _input, args) {
    if (!args) {
        const current = settingsManager.getAutoApproveDefault();
        const choice = await select(current ? 'Spreadsheet changes: Auto-approve' : 'Spreadsheet changes: Ask before changes', [current ? 'Switch to ask before changes' : 'Switch to auto-approve changes', 'Back']);
        if (!choice || choice === 'Back') {
            return 'back';
        }
        if (choice === 'Switch to auto-approve changes') {
            settingsManager.setAutoApproveDefault(true);
            showStatus('Spreadsheet auto-approve default set to auto');
            return true;
        }
        if (choice === 'Switch to ask before changes') {
            settingsManager.setAutoApproveDefault(false);
            showStatus('Spreadsheet auto-approve default set to ask');
            return true;
        }
    }
    const subcommand = args.trim().toLowerCase();
    if (subcommand === 'show' || subcommand === 'list') {
        showStatus(`Spreadsheet auto-approve default: ${settingsManager.getAutoApproveDefault() ? 'auto' : 'ask'}`);
        return true;
    }
    if (subcommand === 'auto' || subcommand === 'on' || subcommand === 'enable') {
        settingsManager.setAutoApproveDefault(true);
        showStatus('Spreadsheet auto-approve default set to auto');
        return true;
    }
    if (subcommand === 'ask' || subcommand === 'off' || subcommand === 'disable') {
        settingsManager.setAutoApproveDefault(false);
        showStatus('Spreadsheet auto-approve default set to ask');
        return true;
    }
    if (subcommand === 'toggle') {
        const next = !settingsManager.getAutoApproveDefault();
        settingsManager.setAutoApproveDefault(next);
        showStatus(`Spreadsheet auto-approve default set to ${next ? 'auto' : 'ask'}`);
        return true;
    }
    showStatus('Usage: /permissions spreadsheet-auto-approve [show|auto|ask|toggle]');
    return true;
}
/** Interactive sub-flow for toggling the dangerous "skip runtime permissions" bypass. */
async function handleDangerouslySkipRuntimePermissionsField(showStatus, settingsManager, _cwd, select, _input, args) {
    if (!args) {
        const current = settingsManager.getDangerouslySkipRuntimePermissions();
        const choice = await select(formatPermissionBypassStatus(current), [
            'Toggle permission bypass',
            'Back'
        ]);
        if (!choice || choice === 'Back') {
            return 'back';
        }
        if (choice === 'Toggle permission bypass') {
            if (!current) {
                const confirmed = await confirmRuntimePermissionBypass(select);
                if (!confirmed) {
                    showStatus('Permissions remain enforced.');
                    return true;
                }
            }
            settingsManager.setDangerouslySkipRuntimePermissions(!current);
            showStatus(formatPermissionBypassStatusMessage(!current));
            return true;
        }
    }
    const subcommand = args.trim().toLowerCase();
    if (subcommand === 'show' || subcommand === 'list') {
        showStatus(formatPermissionBypassStatus(settingsManager.getDangerouslySkipRuntimePermissions()));
        return true;
    }
    if (subcommand === 'on' || subcommand === 'enable') {
        const confirmed = await confirmRuntimePermissionBypass(select);
        if (!confirmed) {
            showStatus('Permissions remain enforced.');
            return true;
        }
        settingsManager.setDangerouslySkipRuntimePermissions(true);
        showStatus(formatPermissionBypassStatusMessage(true));
        return true;
    }
    if (subcommand === 'off' || subcommand === 'disable') {
        settingsManager.setDangerouslySkipRuntimePermissions(false);
        showStatus(formatPermissionBypassStatusMessage(false));
        return true;
    }
    if (subcommand === 'toggle') {
        const next = !settingsManager.getDangerouslySkipRuntimePermissions();
        if (next) {
            const confirmed = await confirmRuntimePermissionBypass(select);
            if (!confirmed) {
                showStatus('Permissions remain enforced.');
                return true;
            }
        }
        settingsManager.setDangerouslySkipRuntimePermissions(next);
        showStatus(formatPermissionBypassStatusMessage(next));
        return true;
    }
    showStatus('Usage: /permissions skip-runtime-permissions [show|on|off|toggle]');
    return true;
}
/** Top-level interactive `/permissions` menu loop dispatching to per-field handlers. */
async function handlePermissionsMenu(showStatus, select, input, settingsManager, cwd) {
    const skipPermissionsField = getRuntimePermissioningFieldSpecByCommand('skip-runtime-permissions');
    const workspaceRootsField = getRuntimePermissioningFieldSpecByCommand('workspace-roots');
    const filesystemGrantsField = getRuntimePermissioningFieldSpecByCommand('filesystem-grants');
    const spreadsheetField = getRuntimePermissioningFieldSpecByCommand('spreadsheet-auto-approve');
    while (true) {
        const choice = await select(`Permissions (${settingsManager.getDangerouslySkipRuntimePermissions() ? 'Bypassed' : 'Enforced'})`, [
            skipPermissionsField.label,
            workspaceRootsField.label,
            filesystemGrantsField.label,
            settingsManager.getAutoApproveDefault()
                ? spreadsheetField.trueLabel
                : spreadsheetField.falseLabel,
            'Open permissions JSON',
            'Cancel'
        ]);
        if (!choice || choice === 'Cancel') {
            return true;
        }
        let result = true;
        if (choice === skipPermissionsField.label) {
            result = await handleDangerouslySkipRuntimePermissionsField(showStatus, settingsManager, cwd, select, input, '');
        }
        else if (choice === workspaceRootsField.label) {
            result = await handleWorkspaceRootsField(showStatus, settingsManager, cwd, select, input, '');
        }
        else if (choice === filesystemGrantsField.label) {
            result = await handleFilesystemGrantsField(showStatus, settingsManager, cwd, select, input, '');
        }
        else if (choice === spreadsheetField.trueLabel || choice === spreadsheetField.falseLabel) {
            result = await handleSpreadsheetAutoApproveField(showStatus, settingsManager, cwd, select, input, '');
        }
        else if (choice === 'Open permissions JSON') {
            openPermissionSettingsFile(showStatus);
            continue;
        }
        if (result === 'back' || result === 'handled' || result === true) {
            continue;
        }
    }
}
/**
 * Handle the /permissions slash command against the current settings state.
 */
export async function handlePermissionsCommand(command, showStatus, select, input, settingsManager, cwd) {
    const args = command.slice('/permissions'.length).trim();
    if (!args) {
        return handlePermissionsMenu(showStatus, select, input, settingsManager, cwd);
    }
    const topLevelMatch = args.match(/^(\S+)(?:\s+([\s\S]+))?$/);
    const topLevel = topLevelMatch?.[1]?.toLowerCase();
    const remainder = topLevelMatch?.[2] ?? '';
    if (topLevel === 'open') {
        if (!remainder.trim()) {
            openPermissionSettingsFile(showStatus);
            return true;
        }
        showStatus('Usage: /permissions open');
        return true;
    }
    const fieldSpec = topLevel ? getRuntimePermissioningFieldSpecByCommand(topLevel) : undefined;
    if (!fieldSpec) {
        showStatus(`Usage: /permissions [open|${RUNTIME_PERMISSIONING_FIELD_SPECS.map((spec) => `${spec.command} ...`).join('|')}]`);
        return true;
    }
    return ((await getPermissionFieldHandler(fieldSpec.command)(showStatus, settingsManager, cwd, select, input, remainder)) !== 'back');
}
/** Map a runtime-permissioning field command to its corresponding interactive handler. */
function getPermissionFieldHandler(command) {
    switch (command) {
        case 'skip-runtime-permissions':
            return handleDangerouslySkipRuntimePermissionsField;
        case 'workspace-roots':
            return handleWorkspaceRootsField;
        case 'filesystem-grants':
            return handleFilesystemGrantsField;
        case 'spreadsheet-auto-approve':
            return handleSpreadsheetAutoApproveField;
    }
}
//# sourceMappingURL=permissions-command.js.map