import { randomUUID } from "node:crypto";
export function createChannelTurnLifecycle(promptDescription) {
    const startedAt = Date.now();
    const turnId = randomUUID().slice(0, 12);
    const progress = {
        status: "running",
        promptDescription,
        startedAt,
        updatedAt: startedAt,
        toolCounts: new Map(),
        textCharacters: 0,
    };
    const touch = () => {
        progress.updatedAt = Date.now();
    };
    return {
        turnId,
        startedAt,
        progress,
        touch,
        recordTextDelta: (characters) => {
            progress.textCharacters += Math.max(0, characters);
            touch();
        },
        recordToolStart: (toolName) => {
            progress.currentTool = toolName;
            progress.lastTool = toolName;
            progress.toolCounts.set(toolName, (progress.toolCounts.get(toolName) ?? 0) + 1);
            touch();
        },
        recordToolUpdate: touch,
        recordToolEnd: () => {
            progress.currentTool = undefined;
            touch();
        },
        recordCompleted: () => {
            progress.status = "completed";
            progress.completedAt = Date.now();
            progress.updatedAt = progress.completedAt;
        },
        recordFailed: (error) => {
            progress.status = "failed";
            progress.error = error;
            progress.completedAt = Date.now();
            progress.updatedAt = progress.completedAt;
        },
    };
}
export function createChannelTypingLoop(options) {
    let timer;
    let running = false;
    const sendTyping = () => {
        void options.sendTyping().catch(() => { });
    };
    return {
        start: () => {
            if (running) {
                return;
            }
            running = true;
            timer = setInterval(sendTyping, options.intervalMs);
            timer.unref?.();
            sendTyping();
        },
        stop: () => {
            running = false;
            if (timer) {
                clearInterval(timer);
                timer = undefined;
            }
        },
    };
}
