/**
 * Coerce an SDK tool_result content payload into a single string.
 * The SDK can emit string | (string | { text?: string })[] | object.
 */
function coerceToolResultContent(raw) {
    if (typeof raw === "string")
        return raw;
    if (Array.isArray(raw)) {
        return raw
            .map((c) => {
            if (typeof c === "string")
                return c;
            if (c && typeof c === "object") {
                const obj = c;
                return obj.text ?? JSON.stringify(c);
            }
            return JSON.stringify(c);
        })
            .join("\n");
    }
    return JSON.stringify(raw);
}
function resultStatus(subtype) {
    if (subtype === "error_max_turns")
        return "max_turns";
    if (subtype === "error_max_budget_usd")
        return "max_budget";
    if (subtype === "error_during_execution")
        return "error";
    return "success";
}
export async function* translateSdkMessages(source) {
    for await (const raw of source) {
        const message = raw;
        // Terminal result
        if (message.type === "result") {
            const usage = message.usage;
            const cost = message.total_cost_usd;
            const durationMs = message.duration_ms;
            const errors = message.errors;
            yield {
                type: "result",
                status: resultStatus(message.subtype),
                reason: errors?.join("; "),
                usage: usage
                    ? {
                        inputTokens: usage.input_tokens ?? 0,
                        outputTokens: usage.output_tokens ?? 0,
                        ...(typeof cost === "number" ? { costUsd: cost } : {}),
                    }
                    : undefined,
                ...(typeof durationMs === "number" ? { durationMs } : {}),
            };
            continue;
        }
        // Slash commands arrive on the system init message
        if (Array.isArray(message.slash_commands) && message.slash_commands.length > 0) {
            yield { type: "slash_commands", commands: message.slash_commands };
        }
        // Session id arrives on the init + can be re-emitted; callers dedupe.
        if (typeof message.session_id === "string" && message.session_id.length > 0) {
            yield { type: "session_started", sessionId: message.session_id };
        }
        // Conversation compaction boundary
        if (message.type === "system" && message.subtype === "compact_boundary") {
            yield { type: "compaction_boundary", content: message.content };
        }
        // Per-turn content blocks
        const blocks = message.message?.content;
        if (Array.isArray(blocks)) {
            for (const block of blocks) {
                const b = block;
                switch (b.type) {
                    case "text":
                        yield { type: "text", content: b.text ?? "" };
                        break;
                    case "thinking":
                        // Pass thinking blocks through whether plaintext or encrypted-empty —
                        // the frontend renders `🔒 Thinking (encrypted)` for the empty case
                        // (see sessionParser.ts for the full explanation).
                        yield { type: "thinking", content: b.thinking ?? "" };
                        break;
                    case "tool_use":
                        yield {
                            type: "tool_use",
                            toolName: b.name ?? "",
                            input: b.input,
                            callId: b.id ?? "",
                        };
                        break;
                    case "tool_result":
                        yield {
                            type: "tool_result",
                            callId: b.tool_use_id ?? "",
                            content: coerceToolResultContent(b.content),
                            ...(typeof b.is_error === "boolean" ? { isError: b.is_error } : {}),
                        };
                        break;
                }
            }
        }
    }
}
