/**
 * @license
 * Copyright 2026 HopCode Team Team
 * SPDX-License-Identifier: Apache-2.0
 */
import * as fs from 'node:fs/promises';
import path from 'node:path';
import { CommandKind, } from './types.js';
import { SessionService } from '@hoptrendy/hopcode-core';
import { collectSessionData, normalizeSessionData, toMarkdown, toHtml, toJson, toJsonl, generateExportFilename, } from '../utils/export/index.js';
import { t } from '../../i18n/index.js';
/**
 * Action for the 'md' subcommand - exports session to markdown.
 */
async function exportMarkdownAction(context) {
    const { services } = context;
    const { config } = services;
    if (!config) {
        return {
            type: 'message',
            messageType: 'error',
            content: 'Configuration not available.',
        };
    }
    const cwd = config.getWorkingDir() || config.getProjectRoot();
    if (!cwd) {
        return {
            type: 'message',
            messageType: 'error',
            content: 'Could not determine current working directory.',
        };
    }
    try {
        // Load the current session using the current session ID
        const sessionService = new SessionService(cwd);
        const sessionId = config.getSessionId();
        const sessionData = await sessionService.loadSession(sessionId);
        if (!sessionData) {
            return {
                type: 'message',
                messageType: 'error',
                content: 'No active session found to export.',
            };
        }
        const { conversation } = sessionData;
        // Collect and normalize export data (SSOT)
        const exportData = await collectSessionData(conversation, config);
        const normalizedData = normalizeSessionData(exportData, conversation.messages, config);
        // Generate markdown from SSOT
        const markdown = toMarkdown(normalizedData);
        const filename = generateExportFilename('md');
        const filepath = path.join(cwd, filename);
        // Write to file
        await fs.writeFile(filepath, markdown, 'utf-8');
        return {
            type: 'message',
            messageType: 'info',
            content: `Session exported to markdown: ${filename}`,
        };
    }
    catch (error) {
        return {
            type: 'message',
            messageType: 'error',
            content: `Failed to export session: ${error instanceof Error ? error.message : String(error)}`,
        };
    }
}
/**
 * Action for the 'html' subcommand - exports session to HTML.
 */
async function exportHtmlAction(context) {
    const { services } = context;
    const { config } = services;
    if (!config) {
        return {
            type: 'message',
            messageType: 'error',
            content: 'Configuration not available.',
        };
    }
    const cwd = config.getWorkingDir() || config.getProjectRoot();
    if (!cwd) {
        return {
            type: 'message',
            messageType: 'error',
            content: 'Could not determine current working directory.',
        };
    }
    try {
        // Load the current session using the current session ID
        const sessionService = new SessionService(cwd);
        const sessionId = config.getSessionId();
        const sessionData = await sessionService.loadSession(sessionId);
        if (!sessionData) {
            return {
                type: 'message',
                messageType: 'error',
                content: 'No active session found to export.',
            };
        }
        const { conversation } = sessionData;
        // Collect and normalize export data (SSOT)
        const exportData = await collectSessionData(conversation, config);
        const normalizedData = normalizeSessionData(exportData, conversation.messages, config);
        // Generate HTML from SSOT
        const html = toHtml(normalizedData);
        const filename = generateExportFilename('html');
        const filepath = path.join(cwd, filename);
        // Write to file
        await fs.writeFile(filepath, html, 'utf-8');
        return {
            type: 'message',
            messageType: 'info',
            content: `Session exported to HTML: ${filename}`,
        };
    }
    catch (error) {
        return {
            type: 'message',
            messageType: 'error',
            content: `Failed to export session: ${error instanceof Error ? error.message : String(error)}`,
        };
    }
}
/**
 * Action for the 'json' subcommand - exports session to JSON.
 */
async function exportJsonAction(context) {
    const { services } = context;
    const { config } = services;
    if (!config) {
        return {
            type: 'message',
            messageType: 'error',
            content: 'Configuration not available.',
        };
    }
    const cwd = config.getWorkingDir() || config.getProjectRoot();
    if (!cwd) {
        return {
            type: 'message',
            messageType: 'error',
            content: 'Could not determine current working directory.',
        };
    }
    try {
        // Load the current session using the current session ID
        const sessionService = new SessionService(cwd);
        const sessionId = config.getSessionId();
        const sessionData = await sessionService.loadSession(sessionId);
        if (!sessionData) {
            return {
                type: 'message',
                messageType: 'error',
                content: 'No active session found to export.',
            };
        }
        const { conversation } = sessionData;
        // Collect and normalize export data (SSOT)
        const exportData = await collectSessionData(conversation, config);
        const normalizedData = normalizeSessionData(exportData, conversation.messages, config);
        // Generate JSON from SSOT
        const json = toJson(normalizedData);
        const filename = generateExportFilename('json');
        const filepath = path.join(cwd, filename);
        // Write to file
        await fs.writeFile(filepath, json, 'utf-8');
        return {
            type: 'message',
            messageType: 'info',
            content: `Session exported to JSON: ${filename}`,
        };
    }
    catch (error) {
        return {
            type: 'message',
            messageType: 'error',
            content: `Failed to export session: ${error instanceof Error ? error.message : String(error)}`,
        };
    }
}
/**
 * Action for the 'jsonl' subcommand - exports session to JSONL.
 */
async function exportJsonlAction(context) {
    const { services } = context;
    const { config } = services;
    if (!config) {
        return {
            type: 'message',
            messageType: 'error',
            content: 'Configuration not available.',
        };
    }
    const cwd = config.getWorkingDir() || config.getProjectRoot();
    if (!cwd) {
        return {
            type: 'message',
            messageType: 'error',
            content: 'Could not determine current working directory.',
        };
    }
    try {
        // Load the current session using the current session ID
        const sessionService = new SessionService(cwd);
        const sessionId = config.getSessionId();
        const sessionData = await sessionService.loadSession(sessionId);
        if (!sessionData) {
            return {
                type: 'message',
                messageType: 'error',
                content: 'No active session found to export.',
            };
        }
        const { conversation } = sessionData;
        // Collect and normalize export data (SSOT)
        const exportData = await collectSessionData(conversation, config);
        const normalizedData = normalizeSessionData(exportData, conversation.messages, config);
        // Generate JSONL from SSOT
        const jsonl = toJsonl(normalizedData);
        const filename = generateExportFilename('jsonl');
        const filepath = path.join(cwd, filename);
        // Write to file
        await fs.writeFile(filepath, jsonl, 'utf-8');
        return {
            type: 'message',
            messageType: 'info',
            content: `Session exported to JSONL: ${filename}`,
        };
    }
    catch (error) {
        return {
            type: 'message',
            messageType: 'error',
            content: `Failed to export session: ${error instanceof Error ? error.message : String(error)}`,
        };
    }
}
/**
 * Main export command with subcommands.
 */
export const exportCommand = {
    name: 'export',
    get description() {
        return t('Export current session message history to a file');
    },
    argumentHint: 'md|html|json|jsonl [path]',
    kind: CommandKind.BUILT_IN,
    supportedModes: ['interactive', 'non_interactive', 'acp'],
    action: exportHtmlAction,
    subCommands: [
        {
            name: 'html',
            get description() {
                return t('Export session to HTML format');
            },
            kind: CommandKind.BUILT_IN,
            supportedModes: ['interactive', 'non_interactive', 'acp'],
            action: exportHtmlAction,
        },
        {
            name: 'md',
            get description() {
                return t('Export session to markdown format');
            },
            kind: CommandKind.BUILT_IN,
            supportedModes: ['interactive', 'non_interactive', 'acp'],
            action: exportMarkdownAction,
        },
        {
            name: 'json',
            get description() {
                return t('Export session to JSON format');
            },
            kind: CommandKind.BUILT_IN,
            supportedModes: ['interactive', 'non_interactive', 'acp'],
            action: exportJsonAction,
        },
        {
            name: 'jsonl',
            get description() {
                return t('Export session to JSONL format (one message per line)');
            },
            kind: CommandKind.BUILT_IN,
            supportedModes: ['interactive', 'non_interactive', 'acp'],
            action: exportJsonlAction,
        },
    ],
};
//# sourceMappingURL=exportCommand.js.map