/** Default idle window before CLI may self-update (5 minutes). */
export const IDLE_UPDATE_DEFAULT_MS = 5 * 60 * 1000;
export function isCurrentlyBusy(state) {
    const reasons = [];
    if (state.agentWorking === true)
        reasons.push('agentWorking');
    if ((state.pendingApprovals?.length ?? 0) > 0)
        reasons.push('pendingApprovals');
    if (state.pendingQuestionnaire)
        reasons.push('questionnaire');
    if (Object.values(state.lentaPendingByAgent ?? {}).some(Boolean)) {
        reasons.push('lentaPending');
    }
    if ((state.queuedMessages?.length ?? 0) > 0)
        reasons.push('queuedMessages');
    for (const tab of state.tabs ?? []) {
        if (tab.isWorking) {
            reasons.push('tabWorking');
            break;
        }
    }
    for (const repo of state.sidebarRepos ?? []) {
        for (const agent of repo.agents) {
            if (agent.isWorking) {
                reasons.push('sidebarWorking');
                break;
            }
        }
        if (reasons.includes('sidebarWorking'))
            break;
    }
    return { busy: reasons.length > 0, reasons };
}
export class ActivityTracker {
    lastActivityAt = 0;
    touch() {
        this.lastActivityAt = Date.now();
    }
    recordFromState(state) {
        if (isCurrentlyBusy(state).busy)
            this.touch();
    }
    getStatus(state, idleMs) {
        const { busy, reasons } = isCurrentlyBusy(state);
        if (busy)
            this.touch();
        const last = this.lastActivityAt > 0 ? this.lastActivityAt : null;
        const since = last ? Date.now() - last : Number.POSITIVE_INFINITY;
        const idleLongEnough = last === null || since >= idleMs;
        return {
            busy,
            busyReasons: reasons,
            lastActivityAt: last,
            idleMs,
            idleForMs: busy ? 0 : last === null ? idleMs : since,
            idleForUpdate: !busy && idleLongEnough,
        };
    }
}
export const activityTracker = new ActivityTracker();
export function parseIdleMsQuery(raw) {
    const n = typeof raw === 'string' ? Number.parseInt(raw, 10) : Number(raw);
    if (!Number.isFinite(n) || n < 60_000)
        return IDLE_UPDATE_DEFAULT_MS;
    return Math.min(n, 24 * 60 * 60 * 1000);
}
