"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.translateHookEvent = translateHookEvent;
exports.newPermissionRequestId = newPermissionRequestId;
const uuid_1 = require("uuid");
/**
 * Convert a single hook payload from claude into ParsedEvent objects that
 * the existing stream-processor / session emitter pipeline can consume.
 *
 * Pure function: no state, no side effects. The session manager owns
 * status tracking, permission request bookkeeping, and emission.
 *
 * Returns an empty array for events that don't map to a ParsedEvent
 * (e.g. UserPromptSubmit, which only affects status).
 */
function translateHookEvent(eventName, payload) {
    switch (eventName) {
        case "PreToolUse":
            return translatePreToolUse(payload);
        case "PostToolUse":
            return translatePostToolUse(payload);
        case "Stop":
            return translateStop(payload);
        case "StopFailure":
            return translateStopFailure(payload);
        case "PermissionRequest":
            return translatePermissionRequest(payload);
        case "Notification":
            return translateNotification(payload);
        case "SubagentStart":
            return translateSubagentStart(payload);
        case "SubagentStop":
            return translateSubagentStop(payload);
        case "PreCompact":
            return translatePreCompact(payload);
        case "PostCompact":
            return translatePostCompact(payload);
        case "UserPromptSubmit":
        case "UserPromptExpansion":
            return [];
    }
}
/** PermissionRequest payloads don't carry a request ID; cockpit synthesises one. */
function newPermissionRequestId() {
    return (0, uuid_1.v4)();
}
function translatePreToolUse(payload) {
    const toolName = stringOr(payload.tool_name, "unknown");
    const toolInput = payload.tool_input;
    const toolId = stringOr(payload.tool_use_id, "");
    const events = [
        {
            type: "system_message",
            text: "__tool_use_start",
        },
        {
            type: "tool_use_start",
            toolName,
            toolId: toolId || undefined,
            toolInput: toolInput ? JSON.stringify(toolInput) : "",
        },
    ];
    if (toolName === "EnterPlanMode") {
        events.push({ type: "system_message", text: "__permission_mode::plan" });
    }
    return events;
}
function translatePostToolUse(payload) {
    const toolName = stringOr(payload.tool_name, "unknown");
    const toolId = stringOr(payload.tool_use_id, "");
    const toolInput = payload.tool_input;
    const response = payload.tool_response;
    const output = extractToolOutput(response);
    const filePath = extractFilePath(toolInput);
    const events = [
        {
            type: "tool_result",
            toolId: toolId || undefined,
            toolOutput: output,
            filePath,
        },
    ];
    if (toolName === "ExitPlanMode") {
        events.push({ type: "system_message", text: "__permission_mode::standard" });
    }
    return events;
}
function translateStop(payload) {
    const text = stringOr(payload.last_assistant_message, "");
    const message = {
        id: (0, uuid_1.v4)(),
        role: "assistant",
        content: text,
        toolUses: [],
        blocks: [],
        timestamp: Date.now(),
    };
    return [{ type: "message_done", message }];
}
function translateStopFailure(payload) {
    const errorType = stringOr(payload.error_type, "unknown");
    const errorMessage = stringOr(payload.error_message, "Unknown error");
    const message = {
        id: (0, uuid_1.v4)(),
        role: "assistant",
        content: "",
        toolUses: [],
        blocks: [],
        timestamp: Date.now(),
    };
    return [
        { type: "message_done", message },
        { type: "system_message", text: `__stop_failure::${errorType}::${errorMessage}` },
    ];
}
function translatePermissionRequest(payload) {
    const toolName = stringOr(payload.tool_name, "unknown");
    const toolInput = payload.tool_input;
    return [
        {
            type: "permission_request",
            requestId: newPermissionRequestId(),
            toolName,
            toolInput: toolInput ? JSON.stringify(toolInput) : "",
            rawToolInput: toolInput,
        },
    ];
}
function translateSubagentStart(payload) {
    const sessionId = stringOr(payload.session_id, (0, uuid_1.v4)());
    const agentId = stringOr(payload.agent_id, "");
    const agentType = stringOr(payload.agent_type, "");
    const description = stringOr(payload.description, "");
    return [
        {
            type: "task_update",
            taskInfo: {
                taskId: sessionId,
                toolUseId: agentId,
                status: "running",
                title: agentType || "Agent",
                description: description || agentType || "Subagent running",
            },
        },
    ];
}
function translateSubagentStop(payload) {
    const sessionId = stringOr(payload.session_id, "");
    const agentId = stringOr(payload.agent_id, "");
    const agentType = stringOr(payload.agent_type, "");
    const lastMessage = stringOr(payload.last_assistant_message, "");
    const description = stringOr(payload.description, "");
    return [
        {
            type: "task_update",
            taskInfo: {
                taskId: sessionId,
                toolUseId: agentId,
                status: "completed",
                title: agentType || "Agent",
                description: description || agentType || "Subagent completed",
                summary: lastMessage.slice(0, 500) || undefined,
            },
        },
    ];
}
function translatePreCompact(_payload) {
    return [{ type: "system_message", text: "__compact::hook_start" }];
}
function translatePostCompact(_payload) {
    return [{ type: "system_message", text: "__compact::hook_done" }];
}
function translateNotification(payload) {
    const message = stringOr(payload.message, "");
    if (!message)
        return [];
    return [{ type: "system_message", text: `__notification::${message}` }];
}
function stringOr(value, fallback) {
    return typeof value === "string" ? value : fallback;
}
function extractToolOutput(response) {
    if (response == null)
        return "";
    if (typeof response === "string")
        return response;
    if (typeof response === "object") {
        const obj = response;
        if (typeof obj.stdout === "string") {
            let out = obj.stdout;
            if (typeof obj.stderr === "string" && obj.stderr.length > 0)
                out += `\n${obj.stderr}`;
            return out;
        }
        if (typeof obj.content === "string")
            return obj.content;
        return JSON.stringify(response);
    }
    return String(response);
}
function extractFilePath(toolInput) {
    if (!toolInput)
        return undefined;
    if (typeof toolInput.file_path === "string")
        return toolInput.file_path;
    if (typeof toolInput.filePath === "string")
        return toolInput.filePath;
    if (typeof toolInput.path === "string")
        return toolInput.path;
    return undefined;
}
