"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OutputHandler = void 0;
const chalk_1 = __importDefault(require("chalk"));
const uuid_1 = require("uuid");
const process = __importStar(require("process"));
class OutputHandler {
    format;
    options;
    sessionId = (0, uuid_1.v4)();
    startTime = Date.now();
    turnCount = 0;
    finalResult = '';
    totalUsage = {
        input_tokens: 0,
        output_tokens: 0,
        server_tool_use: { web_search_requests: 0 }
    };
    constructor(format = 'text', options = {}) {
        this.format = format;
        this.options = options;
    }
    /**
     * Initialize stream-json session
     */
    initializeSession(tools, mcpServers = [], model = '') {
        if (this.format === 'stream-json') {
            const init = {
                type: 'system',
                subtype: 'init',
                cwd: this.options.cwd || process.cwd(),
                session_id: this.sessionId,
                tools,
                mcp_servers: mcpServers,
                model,
                permissionMode: 'default',
                slash_commands: [],
                apiKeySource: 'environment',
                output_style: 'default',
                uuid: (0, uuid_1.v4)()
            };
            console.log(JSON.stringify(init));
        }
    }
    /**
     * Output a complete message
     */
    outputMessage(role, content, usage, toolCalls) {
        this.turnCount++;
        if (this.format === 'text') {
            if (role === 'assistant') {
                console.log(chalk_1.default.cyan('\nAssistant:'));
                console.log(content);
            }
            else if (role === 'user') {
                console.log(chalk_1.default.green('\nUser:'));
                console.log(content);
            }
        }
        else if (this.format === 'stream-json') {
            // Text content message
            const textMessage = {
                type: role,
                message: {
                    id: `msg_${(0, uuid_1.v4)().replace(/-/g, '')}`,
                    type: 'message',
                    role,
                    model: this.options.model,
                    content: [{
                            type: 'text',
                            text: content
                        }],
                    stop_reason: null,
                    stop_sequence: null,
                    usage: usage ? {
                        input_tokens: usage.prompt_tokens || 0,
                        cache_creation_input_tokens: 0,
                        cache_read_input_tokens: 0,
                        cache_creation: {
                            ephemeral_5m_input_tokens: 0,
                            ephemeral_1h_input_tokens: 0
                        },
                        output_tokens: usage.completion_tokens || 0,
                        service_tier: 'standard'
                    } : undefined
                },
                parent_tool_use_id: null,
                session_id: this.sessionId,
                uuid: (0, uuid_1.v4)()
            };
            console.log(JSON.stringify(textMessage));
            // Track usage
            if (usage) {
                this.totalUsage.input_tokens += usage.prompt_tokens || 0;
                this.totalUsage.output_tokens += usage.completion_tokens || 0;
            }
            // Store final result for summary
            if (role === 'assistant') {
                this.finalResult = content;
            }
            // Output tool calls as separate messages
            if (toolCalls && toolCalls.length > 0) {
                for (const toolCall of toolCalls) {
                    this.outputToolCallMessage(toolCall);
                }
            }
        }
    }
    /**
     * Output a tool call as a message
     */
    outputToolCallMessage(toolCall) {
        const toolMessage = {
            type: 'assistant',
            message: {
                id: `msg_${(0, uuid_1.v4)().replace(/-/g, '')}`,
                type: 'message',
                role: 'assistant',
                model: this.options.model,
                content: [{
                        type: 'tool_use',
                        id: toolCall.id || `toolu_${(0, uuid_1.v4)().replace(/-/g, '')}`,
                        name: toolCall.function.name,
                        input: JSON.parse(toolCall.function.arguments)
                    }],
                stop_reason: null,
                stop_sequence: null,
                usage: {
                    input_tokens: 0,
                    output_tokens: 0,
                    service_tier: 'standard'
                }
            },
            parent_tool_use_id: null,
            session_id: this.sessionId,
            uuid: (0, uuid_1.v4)()
        };
        console.log(JSON.stringify(toolMessage));
    }
    /**
     * Output a tool call (legacy method for text format)
     */
    outputToolCall(toolName, args) {
        if (this.format === 'text') {
            console.log(chalk_1.default.magenta(`\n🔧 Calling tool: ${toolName}`));
            console.log(chalk_1.default.gray(JSON.stringify(args, null, 2)));
        }
        // For stream-json, tool calls are handled in outputMessage
    }
    /**
     * Output a tool result
     */
    outputToolResult(toolUseId, result) {
        if (this.format === 'text') {
            console.log(chalk_1.default.blue(`\n✅ Tool result:`));
            if (typeof result === 'string') {
                console.log(result);
            }
            else {
                console.log(JSON.stringify(result, null, 2));
            }
        }
        else if (this.format === 'stream-json') {
            const resultMessage = {
                type: 'user',
                message: {
                    type: 'message',
                    role: 'user',
                    content: [{
                            type: 'tool_result',
                            tool_use_id: toolUseId,
                            content: typeof result === 'string' ? result : JSON.stringify(result)
                        }]
                },
                parent_tool_use_id: null,
                session_id: this.sessionId,
                uuid: (0, uuid_1.v4)()
            };
            console.log(JSON.stringify(resultMessage));
        }
    }
    /**
     * Output an error
     */
    outputError(error) {
        const errorMessage = error instanceof Error ? error.message : error;
        if (this.format === 'text') {
            console.error(chalk_1.default.red('\n❌ Error:'), errorMessage);
        }
        else if (this.format === 'stream-json') {
            const result = {
                type: 'result',
                subtype: 'error',
                is_error: true,
                duration_ms: Date.now() - this.startTime,
                duration_api_ms: 0,
                num_turns: this.turnCount,
                result: errorMessage,
                session_id: this.sessionId,
                total_cost_usd: 0,
                usage: this.totalUsage,
                permission_denials: [],
                uuid: (0, uuid_1.v4)()
            };
            console.log(JSON.stringify(result));
        }
    }
    /**
     * Output completion signal
     */
    outputComplete(usage, apiDuration = 0) {
        if (this.format === 'text') {
            if (usage) {
                console.log(chalk_1.default.gray(`\n📊 Tokens: ${usage.total_tokens} (prompt: ${usage.prompt_tokens}, completion: ${usage.completion_tokens})`));
            }
        }
        else if (this.format === 'stream-json') {
            // Update final usage
            if (usage) {
                this.totalUsage.input_tokens = usage.prompt_tokens || 0;
                this.totalUsage.output_tokens = usage.completion_tokens || 0;
            }
            const result = {
                type: 'result',
                subtype: 'success',
                is_error: false,
                duration_ms: Date.now() - this.startTime,
                duration_api_ms: apiDuration,
                num_turns: this.turnCount,
                result: this.finalResult,
                session_id: this.sessionId,
                total_cost_usd: this.calculateCost(this.totalUsage),
                usage: {
                    ...this.totalUsage,
                    service_tier: 'standard'
                },
                permission_denials: [],
                uuid: (0, uuid_1.v4)()
            };
            console.log(JSON.stringify(result));
        }
    }
    /**
     * Start a spinner (only for text format)
     */
    startSpinner(message) {
        if (this.format === 'text') {
            const ora = require('ora');
            return ora(message).start();
        }
        return null;
    }
    /**
     * Calculate approximate cost (simplified)
     */
    calculateCost(usage) {
        // Rough cost calculation - you may want to make this more accurate
        const inputCost = (usage.input_tokens || 0) * 0.000003; // $3 per 1M tokens
        const outputCost = (usage.output_tokens || 0) * 0.000015; // $15 per 1M tokens
        return inputCost + outputCost;
    }
    /**
     * Get session ID
     */
    getSessionId() {
        return this.sessionId;
    }
    /**
     * Update session ID (for coordination with SessionManager)
     */
    setSessionId(sessionId) {
        this.sessionId = sessionId;
    }
}
exports.OutputHandler = OutputHandler;
//# sourceMappingURL=output.js.map