/**
 * Interactive slash-command handlers for the TUI.
 *
 * Maps user-typed commands (/dev, /docs, /mcp, /sandbox, /connect, /mog,
 * /action, /plan, /ask, /manage, /loop) to their implementations. Also provides
 * factories for downloading and uploading cloud skills on demand.
 */
import { existsSync } from 'fs';
import { handleConnectCommand } from '../app/connectors/connect-command.js';
import { switchMode } from '../app/modes/switch-mode.js';
import { handleMogCommand } from '../app/mog-command.js';
import { handlePermissionsCommand } from '../app/permissions/permissions-command.js';
import { fetchUserInfo } from '../app/services/user-context.js';
import { downloadSkillsWithApproval } from '../app/sync/skills-download.js';
import { checkSkillsSyncStatus } from '../app/sync/skills-status.js';
import { uploadSkills } from '../app/sync/skills-upload.js';
import { getUserDocsPath, isNewSheetForcedEnabled } from '../config.js';
import { formatOpenError, openInEditor } from '../shared/platform/open.js';
import { handleMcpCommand, handleSandboxCommand } from '../shell/index.js';
const MOG_TEAM_DISABLED_MESSAGE = 'Mog is disabled for team accounts.';
async function fetchAuthorizedSkillTeamIds(accessToken) {
    const userInfo = await fetchUserInfo(accessToken);
    if (!userInfo)
        return null;
    return userInfo.authorizedSkillTeamIds ?? [];
}
async function resolveMogCommandPolicy(authStorage) {
    if (isNewSheetForcedEnabled()) {
        return { forceEnabled: true };
    }
    const credential = authStorage.get('shortcut');
    const accessToken = credential?.type === 'oauth' ? credential.access : undefined;
    const userInfo = accessToken ? await fetchUserInfo(accessToken) : null;
    if (userInfo !== null && !userInfo.teamId) {
        return {};
    }
    return { enableDisabledReason: MOG_TEAM_DISABLED_MESSAGE };
}
/** Create a handler that dispatches interactive slash-commands to their implementations. */
export function createInteractiveCommandHandler(context) {
    return async (command, showStatus, select, input, triggerLogin, triggerLogout) => {
        if (command.startsWith('/loop')) {
            const args = command.slice('/loop'.length).trim();
            const skillCommand = args ? `/skill:loop ${args}` : '/skill:loop';
            await context.session.prompt(skillCommand);
            return true;
        }
        if (command === '/dev') {
            const current = context.settingsManager.getDevMode();
            context.settingsManager.setDevMode(!current);
            showStatus(`Dev mode ${!current ? 'enabled' : 'disabled'} — restart session to take effect`);
            return true;
        }
        if (command === '/docs') {
            const docsFile = getUserDocsPath();
            if (existsSync(docsFile)) {
                void openInEditor(docsFile).catch((error) => showStatus(`Could not open documentation: ${formatOpenError(error)}`));
                showStatus('Opened documentation in browser');
            }
            else {
                showStatus('Documentation not found — try reinstalling ShortcutXL');
            }
            return true;
        }
        if (command === '/mcp')
            return handleMcpCommand(showStatus, select, input, context.getMcpManager, context.settingsManager, triggerLogin
                ? async (providerId) => {
                    await triggerLogin(providerId);
                }
                : undefined, triggerLogout
                ? async (providerId) => {
                    await triggerLogout(providerId);
                }
                : undefined, async () => {
                const settings = context.settingsManager.getMcpOAuthSettings();
                context.mcpOAuthStore.setSettings(settings);
            }, {
                authStorage: context.authStorage,
                mcpOAuthStore: context.mcpOAuthStore,
                onMcpConfigChanged: async () => {
                    await context.session.reload();
                }
            });
        if (command === '/sandbox')
            return handleSandboxCommand(showStatus, select, input, context.settingsManager);
        if (command === '/connect')
            return handleConnectCommand(showStatus, select, input, context.settingsManager);
        if (command === '/mog') {
            return handleMogCommand(showStatus, select, context.settingsManager, await resolveMogCommandPolicy(context.authStorage));
        }
        if (command === '/permissions' || command.startsWith('/permissions ')) {
            return handlePermissionsCommand(command, showStatus, select, input, context.settingsManager, context.session.sessionManager.getCwd());
        }
        if (command === '/action' ||
            command === '/plan' ||
            command === '/ask' ||
            command === '/manage') {
            const result = await switchMode(context.session, command.slice(1), {
                settings: context.session.approvalState,
                force: true
            });
            showStatus(result.message);
            return true;
        }
        return context.traceHooks.onCommand(command, showStatus);
    };
}
/** Create a handler that downloads cloud skills using the current OAuth token. */
export function createInteractiveSkillDownloadHandler(authStorage) {
    return (approve) => {
        const credential = authStorage.get('shortcut');
        const accessToken = credential?.type === 'oauth' ? credential.access : undefined;
        if (!accessToken) {
            return Promise.resolve({
                downloaded: [],
                skipped: [],
                skippedByUser: [],
                filesDownloaded: 0,
                changes: [],
                errors: ['Not logged in. Run /login first.']
            });
        }
        return fetchAuthorizedSkillTeamIds(accessToken).then((authorizedSkillTeamIds) => downloadSkillsWithApproval(accessToken, approve, authorizedSkillTeamIds));
    };
}
/** Create a handler that uploads local managed skills using the current OAuth token. */
export function createSkillUploadHandler(authStorage) {
    return (approve) => {
        const credential = authStorage.get('shortcut');
        const accessToken = credential?.type === 'oauth' ? credential.access : undefined;
        if (!accessToken) {
            return Promise.resolve({
                uploaded: [],
                skipped: [],
                skippedByUser: [],
                blockedTeam: [],
                changes: [],
                errors: ['Not logged in. Run /login first.']
            });
        }
        return fetchAuthorizedSkillTeamIds(accessToken).then((authorizedSkillTeamIds) => uploadSkills(accessToken, approve, authorizedSkillTeamIds));
    };
}
/**
 * Create the read-only skill drift check used by interactive startup.
 *
 * The returned function reads the current OAuth token at call time so a /login
 * performed earlier in the same process is respected.
 */
export function createSkillSyncStatusHandler(authStorage) {
    return () => {
        const credential = authStorage.get('shortcut');
        const accessToken = credential?.type === 'oauth' ? credential.access : undefined;
        if (!accessToken) {
            return Promise.resolve({
                needsDownload: [],
                needsUpload: [],
                changedTeam: [],
                errors: ['Not logged in. Run /login first.']
            });
        }
        return fetchAuthorizedSkillTeamIds(accessToken).then((authorizedSkillTeamIds) => checkSkillsSyncStatus(accessToken, authorizedSkillTeamIds));
    };
}
//# sourceMappingURL=interactive-commands.js.map