import { Spacer, Text } from '../../tui/index.js';
import { theme } from '../theme/runtime.js';
const SHORTY_USAGE = 'Usage: /shorty [whatsapp|status|reset|relink|disconnect]';
const SHORTY_MENU_OPTIONS = [
    {
        value: 'connect',
        label: 'Connect WhatsApp',
        description: 'Link or reconnect WhatsApp so you can control ShortcutXL from Message yourself.'
    },
    {
        value: 'status',
        label: 'Show Status',
        description: 'Show the current phone-control status, pairing state, and QR if needed.'
    },
    {
        value: 'reset',
        label: 'Reset WhatsApp Link',
        description: 'Delete the saved WhatsApp link and start over with a fresh QR code.'
    },
    {
        value: 'disconnect',
        label: 'Disconnect',
        description: 'Turn off phone control for now, but keep the command available.'
    },
    {
        value: 'cancel',
        label: 'Cancel',
        description: 'Close this menu without changing anything.'
    }
];
function renderPhoneStatus(ctx, status) {
    ctx.chat.addChild(new Spacer(1));
    if (!status.enabled || !status.provider) {
        ctx.chat.addChild(new Text(theme.fg('dim', 'ShortcutXL phone connection is not connected.'), 1, 0));
        return;
    }
    const lines = [
        `ShortcutXL phone connection: ${status.provider}`,
        status.qrText
            ? 'Scan this QR in WhatsApp -> Linked Devices. After linking, use Message yourself to control ShortcutXL from your phone.'
            : status.pairedChatId
                ? 'Phone chat is paired. Send prompts normally and you will get the final assistant reply back.'
                : 'WhatsApp account is linked. Open Message yourself in WhatsApp and send a normal message there. The first self-chat message becomes the controller for this session.',
        'ShortcutXL uses your current edit approval setting. If it asks for approval, reply with y or n.'
    ];
    if (status.liveDesktopCount && status.liveDesktopCount > 1) {
        if (status.currentDesktopIsActiveTarget) {
            lines.push('', 'This CLI is currently connected to your phone.');
        }
        else if (status.activeDesktopLabel) {
            lines.push('', `Your phone is connected to another ShortcutXL session: ${status.activeDesktopLabel}.`);
            if (status.switchableToCurrentDesktop && status.currentDesktopLabel) {
                lines.push(`Run /shorty connect to switch phone control to this session: ${status.currentDesktopLabel}.`);
            }
        }
    }
    if (status.lastError) {
        lines.push('', `Last issue: ${status.lastError}`);
    }
    if (status.qrText) {
        lines.push('', 'Scan this QR in WhatsApp -> Linked Devices:', '', status.qrText);
    }
    ctx.chat.addChild(new Text(lines.join('\n'), 1, 0));
}
function parseAction(args) {
    const trimmedArgs = args.trim().toLowerCase();
    if (trimmedArgs === 'connect' || trimmedArgs === 'whatsapp') {
        return 'connect';
    }
    if (trimmedArgs === 'status') {
        return 'status';
    }
    if (trimmedArgs === 'reset' || trimmedArgs === 'relink') {
        return 'reset';
    }
    if (trimmedArgs === 'disconnect') {
        return 'disconnect';
    }
    return undefined;
}
async function resolveAction(args, ctx) {
    const parsed = parseAction(args);
    if (parsed) {
        return parsed;
    }
    if (args.trim()) {
        return undefined;
    }
    if (!ctx.selectOption) {
        return 'connect';
    }
    const selected = await ctx.selectOption('Connect ShortcutXL to your phone', SHORTY_MENU_OPTIONS);
    return selected ?? 'cancel';
}
async function resetWhatsAppLink(phoneManager, ctx) {
    ctx.feedback.showStatus('Resetting WhatsApp link...');
    try {
        const status = await phoneManager.resetWhatsAppLink({ reconnect: true });
        renderPhoneStatus(ctx, status);
        ctx.requestRender();
    }
    catch (error) {
        ctx.feedback.showError(error instanceof Error ? error.message : String(error));
    }
}
export function createShortyCommand(phoneManager) {
    return async (args, ctx) => {
        const action = await resolveAction(args, ctx);
        if (!action) {
            ctx.feedback.showWarning(SHORTY_USAGE);
            return;
        }
        if (action === 'cancel') {
            return;
        }
        if (action === 'status') {
            renderPhoneStatus(ctx, await phoneManager.refreshStatus());
            ctx.requestRender();
            return;
        }
        if (action === 'reset') {
            await resetWhatsAppLink(phoneManager, ctx);
            return;
        }
        if (action === 'disconnect') {
            await phoneManager.disconnect();
            ctx.feedback.showStatus('ShortcutXL phone connection disconnected.');
            return;
        }
        ctx.feedback.showStatus('Starting WhatsApp link flow...');
        try {
            const status = await phoneManager.connectWhatsApp();
            renderPhoneStatus(ctx, status);
            ctx.requestRender();
        }
        catch (error) {
            ctx.feedback.showError(error instanceof Error ? error.message : String(error));
        }
    };
}
export function createShortySlashCommand(phoneManager) {
    return {
        name: 'shorty',
        description: 'Connect Shorty to your phone',
        handler: createShortyCommand(phoneManager)
    };
}
//# sourceMappingURL=shorty-command.js.map