"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventParser = void 0;
const uuid_1 = require("uuid");
class EventParser {
    lastAssistantModel = null;
    parseLine(line) {
        const trimmed = line.trim();
        if (!trimmed)
            return [];
        let event;
        try {
            event = JSON.parse(trimmed);
        }
        catch {
            return [];
        }
        const type = event.type;
        if (type === "assistant") {
            return this.parseAssistantEvent(event);
        }
        if (type === "user") {
            return this.parseUserEvent(event);
        }
        if (type === "result") {
            return this.parseResultEvent(event);
        }
        if (type === "control_request") {
            return this.parseControlRequest(event);
        }
        if (type === "tool_progress") {
            const toolId = event.tool_use_id;
            const content = event.content;
            if (toolId && content) {
                return [{ type: "tool_progress", toolId, text: content }];
            }
            return [];
        }
        if (type === "rate_limit_event") {
            const info = event.rate_limit_info;
            if (info) {
                return [{ type: "rate_limit", rateLimitInfo: { status: info.status || "unknown", retryAfterMs: info.retry_after_ms } }];
            }
            return [];
        }
        if (type === "prompt_suggestion") {
            const suggestions = (event.suggestions || event.prompt_suggestions);
            if (suggestions?.length) {
                return [{ type: "prompt_suggestion", suggestions }];
            }
            return [];
        }
        if (type === "auth_status") {
            return [{ type: "system_message", text: `__auth::${event.status || "unknown"}` }];
        }
        // tool_use_summary: dropped because tool_result already provides output
        // stream_event: dropped because we use full assistant events
        if (type === "tool_use_summary" || type === "stream_event") {
            return [];
        }
        // Parse initialize control_response to extract model/account/command data
        if (type === "control_response") {
            const response = event.response;
            if (!response)
                return [];
            const subtype = response.subtype;
            // The initialize response nests data under response.response
            const data = (response.response || response);
            if (subtype !== "success" || !data.models)
                return [];
            const models = (data.models || []);
            const account = data.account;
            const commands = (data.commands || []);
            const agents = (data.agents || []);
            return [
                {
                    type: "init",
                    initData: {
                        slashCommands: commands.map((c) => (c.name || "")),
                        skills: [],
                        agents: agents.map((a) => ({
                            name: (a.name || ""),
                            description: (a.description || undefined),
                        })),
                        version: "",
                        model: "",
                        mcpServers: [],
                        models: models.map((m) => ({
                            value: (m.value || ""),
                            displayName: (m.displayName || ""),
                            description: (m.description || ""),
                            supportsEffort: m.supportsEffort,
                            supportedEffortLevels: m.supportedEffortLevels,
                            supportsAdaptiveThinking: m.supportsAdaptiveThinking,
                            supportsFastMode: m.supportsFastMode,
                            supportsAutoMode: m.supportsAutoMode,
                        })),
                        account: account
                            ? {
                                email: (account.email || ""),
                                organization: (account.organization || ""),
                                subscriptionType: (account.subscriptionType || ""),
                            }
                            : undefined,
                        commands: commands.map((c) => ({
                            name: (c.name || ""),
                            description: (c.description || ""),
                            argumentHint: c.argumentHint,
                        })),
                    },
                },
            ];
        }
        if (type === "system") {
            const subtype = event.subtype;
            if (subtype === "compact_boundary") {
                return [{ type: "system_message", text: "__compact_boundary__" }];
            }
            if (subtype === "status" && event.status === "compacting") {
                return [{ type: "system_message", text: "__compact::start" }];
            }
            if (subtype === "status" && event.permissionMode) {
                const mode = event.permissionMode;
                return [{ type: "system_message", text: `__permission_mode::${mode}` }];
            }
            // Refined hook subtypes
            if (subtype === "hook_started") {
                const hookName = (event.hook_name || event.name || "unknown");
                return [{ type: "system_message", text: `__hook::started::${hookName}` }];
            }
            if (subtype === "hook_progress") {
                const content = (event.content || "");
                return [{ type: "system_message", text: `__hook::progress::${content}` }];
            }
            if (subtype === "hook_response") {
                return [{ type: "system_message", text: "__hook::done" }];
            }
            // Structured task events
            if (subtype === "task_started") {
                return [
                    {
                        type: "task_update",
                        taskInfo: {
                            taskId: (event.task_id || ""),
                            toolUseId: (event.tool_use_id || ""),
                            status: "running",
                            description: (event.description || ""),
                        },
                    },
                ];
            }
            if (subtype === "task_progress") {
                return [
                    {
                        type: "task_update",
                        taskInfo: {
                            taskId: (event.task_id || ""),
                            toolUseId: (event.tool_use_id || ""),
                            status: "progress",
                            description: (event.description || ""),
                        },
                    },
                ];
            }
            if (subtype === "task_notification") {
                return [
                    {
                        type: "task_update",
                        taskInfo: {
                            taskId: (event.task_id || ""),
                            toolUseId: (event.tool_use_id || ""),
                            status: "completed",
                            description: (event.description || ""),
                            summary: (event.summary || ""),
                        },
                    },
                ];
            }
            if (subtype === "init") {
                const slashCommands = (event.slash_commands || []);
                const skills = (event.skills || []);
                const rawAgents = (event.agents || []);
                const agents = rawAgents.map((a) => typeof a === "string" ? { name: a } : { name: (a.name || ""), description: a.description });
                const version = (event.claude_code_version || "");
                const model = (event.model || "");
                const rawServers = (event.mcp_servers || []);
                const mcpServers = rawServers.map((s) => ({
                    name: (s.name || ""),
                    status: (s.status || ""),
                }));
                return [{ type: "init", initData: { slashCommands, skills, agents, version, model, mcpServers } }];
            }
            // Forward all other system events so the debug log captures them
            if (subtype) {
                return [{ type: "system_message", text: `__system::${subtype}` }];
            }
        }
        return [];
    }
    parseAssistantEvent(event) {
        const msg = event.message;
        if (!msg?.content)
            return [];
        if (msg.model) {
            this.lastAssistantModel = msg.model;
        }
        const assistantMessageId = msg.id || undefined;
        const events = [];
        for (const block of msg.content) {
            if (block.type === "thinking") {
                const redacted = !block.thinking && !!block.signature;
                if (!block.thinking && !redacted)
                    continue;
                events.push({ type: "thinking", text: block.thinking ?? "", redacted, assistantMessageId });
            }
            else if (block.type === "text" && block.text) {
                events.push({ type: "text_delta", text: block.text, assistantMessageId });
            }
            else if (block.type === "tool_use") {
                events.push({
                    type: "tool_use_start",
                    toolName: block.name || "unknown",
                    toolId: block.id,
                    toolInput: block.input ? JSON.stringify(block.input) : "",
                    assistantMessageId,
                });
            }
        }
        return events;
    }
    parseUserEvent(event) {
        const msg = event.message;
        if (!msg?.content || !Array.isArray(msg.content))
            return [];
        const events = [];
        for (const block of msg.content) {
            if (block.type === "tool_result" && block.tool_use_id) {
                const output = this.extractToolResultOutput(block);
                const filePath = this.extractFilePath(block);
                events.push({
                    type: "tool_result",
                    toolId: block.tool_use_id,
                    toolOutput: output,
                    filePath,
                });
            }
        }
        return events;
    }
    extractToolResultOutput(block) {
        if (typeof block.content === "string") {
            return block.content;
        }
        if (Array.isArray(block.content)) {
            const parts = [];
            for (const item of block.content) {
                if (typeof item === "string") {
                    parts.push(item);
                }
                else if (item.type === "text" && item.text) {
                    parts.push(item.text);
                }
            }
            return parts.join("\n");
        }
        return "";
    }
    extractFilePath(block) {
        if (!Array.isArray(block.content))
            return undefined;
        for (const item of block.content) {
            if (typeof item !== "string") {
                const input = item.input;
                if (input) {
                    if (typeof input.file_path === "string")
                        return input.file_path;
                    if (typeof input.filePath === "string")
                        return input.filePath;
                    if (typeof input.path === "string")
                        return input.path;
                }
            }
        }
        return undefined;
    }
    parseControlRequest(event) {
        const request = event.request;
        if (request?.subtype === "can_use_tool") {
            return [
                {
                    type: "permission_request",
                    requestId: event.request_id,
                    toolName: request.tool_name || "unknown",
                    toolInput: request.input ? JSON.stringify(request.input) : "",
                    rawToolInput: request.input,
                    permissionSuggestions: request.permission_suggestions,
                },
            ];
        }
        return [];
    }
    parseResultEvent(event) {
        const result = event.result;
        const uuid = event.uuid;
        const subtype = event.subtype;
        const message = {
            id: uuid || (0, uuid_1.v4)(),
            role: "assistant",
            content: result || "",
            toolUses: [],
            blocks: [],
            timestamp: Date.now(),
            model: this.lastAssistantModel ?? undefined,
        };
        return [{ type: "message_done", message, interrupted: subtype === "error_during_execution" }];
    }
}
exports.EventParser = EventParser;
