/**
 * @license
 * Copyright 2026 HopCode Team Code
 * SPDX-License-Identifier: Apache-2.0
 */
import { CommandKind } from './types.js';
import { MessageType } from '../types.js';
import { t } from '../../i18n/index.js';
import { join } from 'path';
import { StaticInsightGenerator } from '../../services/insight/generators/StaticInsightGenerator.js';
import { createDebugLogger, encodeInsightProgressMessage, encodeInsightReadyMessage, Storage, } from '@hoptrendy/hopcode-core';
import open from 'open';
const logger = createDebugLogger('DataProcessor');
export const insightCommand = {
    name: 'insight',
    get description() {
        return t('generate personalized programming insights from your chat history');
    },
    kind: CommandKind.BUILT_IN,
    supportedModes: ['interactive', 'non_interactive', 'acp'],
    action: async (context) => {
        try {
            context.ui.setDebugMessage(t('Generating insights...'));
            const projectsDir = join(Storage.getRuntimeBaseDir(), 'projects');
            if (!context.services.config) {
                if (context.executionMode !== 'interactive') {
                    return {
                        type: 'message',
                        messageType: 'error',
                        content: 'Config service is not available.',
                    };
                }
                throw new Error('Config service is not available');
            }
            const insightGenerator = new StaticInsightGenerator(context.services.config);
            if (context.executionMode === 'non_interactive') {
                // non_interactive: run synchronously and return a single message
                try {
                    const outputPath = await insightGenerator.generateStaticInsight(projectsDir, () => {
                        // progress callback is no-op in non_interactive mode
                    });
                    return {
                        type: 'message',
                        messageType: 'info',
                        content: t('Insight report generated at: {{path}}', {
                            path: outputPath,
                        }),
                    };
                }
                catch (error) {
                    return {
                        type: 'message',
                        messageType: 'error',
                        content: t('Failed to generate insights: {{error}}', {
                            error: error.message,
                        }),
                    };
                }
            }
            if (context.executionMode === 'acp') {
                const pendingMessages = [];
                let isComplete = false;
                let resume = null;
                const flushResume = () => {
                    const resolve = resume;
                    if (!resolve) {
                        return;
                    }
                    resume = null;
                    resolve();
                };
                const pushMessage = (message) => {
                    pendingMessages.push(message);
                    flushResume();
                };
                const streamMessages = async function* () {
                    while (!isComplete || pendingMessages.length > 0) {
                        if (pendingMessages.length === 0) {
                            await new Promise((resolve) => {
                                resume = resolve;
                            });
                        }
                        while (pendingMessages.length > 0) {
                            const message = pendingMessages.shift();
                            if (message) {
                                yield message;
                            }
                        }
                    }
                };
                void (async () => {
                    try {
                        pushMessage({
                            messageType: 'info',
                            content: t('This may take a couple minutes. Sit tight!'),
                        });
                        pushMessage({
                            messageType: 'info',
                            content: encodeInsightProgressMessage(t('Starting insight generation...'), 0),
                        });
                        const outputPath = await insightGenerator.generateStaticInsight(projectsDir, (stage, progress, detail) => {
                            pushMessage({
                                messageType: 'info',
                                content: encodeInsightProgressMessage(stage, progress, detail),
                            });
                        });
                        pushMessage({
                            messageType: 'info',
                            content: encodeInsightReadyMessage(outputPath),
                        });
                    }
                    catch (error) {
                        pushMessage({
                            messageType: 'error',
                            content: t('Failed to generate insights: {{error}}', {
                                error: error.message,
                            }),
                        });
                        logger.error('Insight generation error:', error);
                    }
                    finally {
                        isComplete = true;
                        flushResume();
                    }
                })();
                return {
                    type: 'stream_messages',
                    messages: streamMessages(),
                };
            }
            const updateProgress = (stage, progress, detail) => {
                const progressItem = {
                    type: MessageType.INSIGHT_PROGRESS,
                    progress: {
                        stage,
                        progress,
                        detail,
                    },
                };
                context.ui.setPendingItem(progressItem);
            };
            context.ui.addItem({
                type: MessageType.INFO,
                text: t('This may take a couple minutes. Sit tight!'),
            }, Date.now());
            updateProgress(t('Starting insight generation...'), 0);
            const outputPath = await insightGenerator.generateStaticInsight(projectsDir, updateProgress);
            context.ui.setPendingItem(null);
            context.ui.addItem({
                type: MessageType.INFO,
                text: t('Insight report generated successfully!'),
            }, Date.now());
            try {
                await open(outputPath);
                context.ui.addItem({
                    type: MessageType.INFO,
                    text: t('Opening insights in your browser: {{path}}', {
                        path: outputPath,
                    }),
                }, Date.now());
            }
            catch (browserError) {
                logger.error('Failed to open browser automatically:', browserError);
                context.ui.addItem({
                    type: MessageType.INFO,
                    text: t('Insights generated at: {{path}}. Please open this file in your browser.', {
                        path: outputPath,
                    }),
                }, Date.now());
            }
            context.ui.setDebugMessage(t('Insights ready.'));
            return;
        }
        catch (error) {
            context.ui.setPendingItem(null);
            if (context.executionMode !== 'interactive') {
                return {
                    type: 'message',
                    messageType: 'error',
                    content: `Failed to generate insights: ${error.message}`,
                };
            }
            context.ui.addItem({
                type: MessageType.ERROR,
                text: t('Failed to generate insights: {{error}}', {
                    error: error.message,
                }),
            }, Date.now());
            logger.error('Insight generation error:', error);
            return;
        }
        return;
    },
};
//# sourceMappingURL=insightCommand.js.map