/** Shared CLI helpers for resolving runtime paths, config, and command execution context. */
import chalk from 'chalk';
import { AuthStorage } from './app/auth/auth-storage.js';
import { ModelRegistry } from './app/providers/model-registry.js';
import { registerShortcutProvider } from './app/providers/register-shortcut-provider.js';
import { DefaultPackageManager } from './app/resources/package-manager.js';
import { SettingsManager } from './app/settings-manager.js';
import { selectConfig } from './cli/config-selector.js';
import { processFileArguments } from './cli/file-processor.js';
import { reportSettingsErrors } from './cli/report-settings-errors.js';
import { getAgentDir, getModelsPath } from './config.js';
import { SHORTCUT_LLM_PROXY_URL } from './constants.js';
import { MODE } from './mode-names.js';
import { SHORTCUT_PROVIDER_ID } from './model-ids.js';
import { withPhoneStatusNotifications } from './remote-control/index.js';
/**
 * Read all content from piped stdin.
 * Returns undefined if stdin is a TTY (interactive terminal).
 */
export async function readPipedStdin() {
    if (process.stdin.isTTY) {
        return undefined;
    }
    return new Promise((resolve) => {
        let data = '';
        process.stdin.setEncoding('utf8');
        process.stdin.on('data', (chunk) => {
            data += chunk;
        });
        process.stdin.on('end', () => {
            resolve(data.trim() || undefined);
        });
        process.stdin.resume();
    });
}
export function isTruthyEnvFlag(value) {
    if (!value)
        return false;
    return value === '1' || value.toLowerCase() === 'true' || value.toLowerCase() === 'yes';
}
export async function prepareInitialMessage(fileArgs, messages, autoResizeImages) {
    if (fileArgs.length === 0) {
        return {};
    }
    const { text, images } = await processFileArguments(fileArgs, { autoResizeImages });
    let initialMessage;
    if (messages.length > 0) {
        initialMessage = text + messages[0];
        messages.shift();
    }
    else {
        initialMessage = text;
    }
    return {
        initialMessage,
        initialImages: images.length > 0 ? images : undefined
    };
}
export async function handleConfigCommand(args) {
    if (args[0] !== 'config') {
        return false;
    }
    const cwd = process.cwd();
    const agentDir = getAgentDir();
    const settingsManager = SettingsManager.create(cwd, agentDir);
    reportSettingsErrors(settingsManager, 'config command');
    const packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager });
    const resolvedPaths = await packageManager.resolve();
    await selectConfig({
        resolvedPaths,
        settingsManager,
        cwd,
        agentDir
    });
    process.exit(0);
}
export async function handleShortcutAuthCommand(args) {
    const command = args[0];
    if (command !== 'login' && command !== 'logout') {
        return false;
    }
    const authStorage = AuthStorage.create();
    if (command === 'logout') {
        authStorage.logout(SHORTCUT_PROVIDER_ID);
        console.log(chalk.green('Logged out of Shortcut.'));
        process.exit(0);
    }
    const modelRegistry = new ModelRegistry(authStorage, getModelsPath());
    registerShortcutProvider(modelRegistry, SHORTCUT_LLM_PROXY_URL, {
        authStorageForRecovery: authStorage
    });
    const controller = new AbortController();
    const onSignal = () => controller.abort();
    process.once('SIGINT', onSignal);
    process.once('SIGTERM', onSignal);
    try {
        console.log(chalk.bold('Logging in to Shortcut...'));
        await authStorage.login(SHORTCUT_PROVIDER_ID, {
            onAuth: (info) => {
                console.log('');
                console.log('Open this URL to authenticate Shortcut:');
                console.log(chalk.cyan(info.url));
                if (info.instructions) {
                    console.log('');
                    console.log(info.instructions);
                }
                console.log('');
                console.log(chalk.dim('Waiting for authentication...'));
            },
            onPrompt: async (prompt) => {
                console.log(prompt.placeholder ? `${prompt.message} (${prompt.placeholder})` : prompt.message);
                return '';
            },
            onProgress: (message) => {
                console.log(chalk.dim(message));
            },
            signal: controller.signal
        });
        console.log(chalk.green(`Logged in to Shortcut. Credentials saved to ${getAgentDir()}/auth.json`));
        process.exit(0);
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.error(chalk.red(`Shortcut login failed: ${message}`));
        process.exit(1);
    }
    finally {
        process.off('SIGINT', onSignal);
        process.off('SIGTERM', onSignal);
    }
}
export function handleXllStartupStatus(xllStatus, devMode, startupWarnings) {
    if (xllStatus.kind === 'ok' && xllStatus.updated > 0 && devMode) {
        startupWarnings.push(`Updated ${xllStatus.updated} XLL file(s) in ${getAgentDir()}/xll/`);
    }
    if (xllStatus.kind === 'source-missing') {
        console.error(chalk.red('Error: local development files are missing from ~/.shortcut/agent/xll/.'));
        for (const path of xllStatus.missingPaths) {
            console.error(chalk.red(`Missing: ${path}`));
        }
        console.error(chalk.yellow('Run `pnpm dev` to copy Python files to your local machine.'));
        console.error(chalk.yellow('If python/python.exe is missing, run `pnpm run vendor-python` once to prepare the embedded Python runtime.'));
        console.error(chalk.yellow('Run `pnpm run build:xll:local` to copy the built XLL to your local machine.'));
        process.exit(1);
    }
    if (xllStatus.kind === 'install-failed') {
        console.error(chalk.red('Error: ShortcutXL.xll could not be synced to the stable directory.'));
        console.error(chalk.red(`Expected at: ${getAgentDir()}/xll/ShortcutXL.xll`));
        console.error(chalk.yellow('Try reinstalling: npm install -g shortcutxl'));
        process.exit(1);
    }
    if (xllStatus.kind === 'degraded') {
        startupWarnings.push('XLL sync failed — continuing with previously installed files. ' +
            'To update, close Excel and restart the Shortcut agent.');
    }
}
export function validateAgentMode(agentMode) {
    const validModes = new Set([MODE.INSTALLATION, MODE.ACTION, MODE.PLAN, MODE.ASK]);
    if (agentMode && !validModes.has(agentMode)) {
        console.error(chalk.red(`Unknown agent mode "${agentMode}". Valid modes: ${[...validModes].join(', ')}`));
        process.exit(1);
    }
}
export async function runInteractiveShell(watch, mode, phoneManager) {
    if (watch !== undefined) {
        const { watchDirectory, resolveWatchDir } = await import('./startup/file-watcher.js');
        const watchDir = resolveWatchDir(watch);
        try {
            const watcher = watchDirectory(watchDir, () => {
                watcher.close();
                mode.requestRestart();
            });
        }
        catch {
            // Directory may not exist — skip watching
        }
    }
    await withPhoneStatusNotifications(phoneManager, (message) => mode.showInfo(message), () => mode.run());
}
//# sourceMappingURL=main-helpers.js.map