import { createSlice } from '@genesislcap/foundation-redux';
import { emptyUsage, sumUsage } from '../utils/sum-usage';
/**
 * Build a fresh default session state. A factory (not just a shared const) so
 * each call returns independent collections — `resetSession` can hand back a
 * clean slate without aliasing the initial state's arrays.
 */
export function createDefaultSessionState() {
    return {
        messages: [],
        state: 'idle',
        showToolCalls: false,
        showThinkingSteps: false,
        showNarration: false,
        showAgentSwitchIndicator: false,
        enabledAnimations: [],
        suggestionsState: { status: 'idle' },
        contextTokens: undefined,
        contextLimit: undefined,
        sessionUsage: emptyUsage(),
        activeModel: undefined,
        activeProviderName: undefined,
        providerStatuses: [],
        activeAgent: undefined,
        pinnedAgentName: null,
        flowOwnerAgentName: null,
        flowActivationPrompt: null,
        agentPickerOpen: false,
        sessionMenuOpen: false,
        compacting: false,
        restoring: false,
        inputValue: '',
        liveSubAgentTrace: [],
        liveSubAgentName: null,
        inputOverrides: [],
    };
}
export const defaultSessionState = createDefaultSessionState();
export const aiAssistantSlice = createSlice({
    name: 'aiAssistant',
    initialState: defaultSessionState,
    reducers: {
        setMessages(state, action) {
            state.messages = action.payload;
        },
        setState(state, action) {
            state.state = action.payload;
        },
        setShowToolCalls(state, action) {
            state.showToolCalls = action.payload;
        },
        setShowThinkingSteps(state, action) {
            state.showThinkingSteps = action.payload;
        },
        setShowNarration(state, action) {
            state.showNarration = action.payload;
        },
        setShowAgentSwitchIndicator(state, action) {
            state.showAgentSwitchIndicator = action.payload;
        },
        setEnabledAnimations(state, action) {
            state.enabledAnimations = action.payload;
        },
        setSuggestionsState(state, action) {
            state.suggestionsState = action.payload;
        },
        setContextTokens(state, action) {
            state.contextTokens = action.payload;
        },
        setContextLimit(state, action) {
            state.contextLimit = action.payload;
        },
        setSessionUsage(state, action) {
            state.sessionUsage = action.payload;
        },
        setActiveModel(state, action) {
            state.activeModel = action.payload;
        },
        setActiveProviderName(state, action) {
            state.activeProviderName = action.payload;
        },
        setProviderStatuses(state, action) {
            state.providerStatuses = action.payload;
        },
        setActiveAgent(state, action) {
            state.activeAgent = action.payload;
        },
        setPinnedAgentName(state, action) {
            state.pinnedAgentName = action.payload;
        },
        setFlowOwnerAgentName(state, action) {
            state.flowOwnerAgentName = action.payload;
        },
        setFlowActivationPrompt(state, action) {
            state.flowActivationPrompt = action.payload;
        },
        setAgentPickerOpen(state, action) {
            state.agentPickerOpen = action.payload;
        },
        setSessionMenuOpen(state, action) {
            state.sessionMenuOpen = action.payload;
        },
        setCompacting(state, action) {
            state.compacting = action.payload;
        },
        setRestoring(state, action) {
            state.restoring = action.payload;
        },
        setInputValue(state, action) {
            state.inputValue = action.payload;
        },
        setLiveSubAgentTrace(state, action) {
            state.liveSubAgentTrace = action.payload;
        },
        setLiveSubAgentName(state, action) {
            state.liveSubAgentName = action.payload;
        },
        addInputOverride(state, action) {
            state.inputOverrides.push(action.payload);
        },
        removeInputOverride(state, action) {
            state.inputOverrides = state.inputOverrides.filter((o) => o.id !== action.payload.id);
        },
        /**
         * Bulk-hydrate the restorable fields of a persisted session (page-reload
         * restore) and set `state` back to `idle`. Agent identity and the per-agent
         * machine snapshot are applied separately by the host — see
         * `LoadSessionPayload`.
         */
        loadSession(state, action) {
            const p = action.payload;
            state.messages = p.messages;
            state.pinnedAgentName = p.pinnedAgentName;
            state.flowOwnerAgentName = p.flowOwnerAgentName;
            // Derive the totals from the restored transcript rather than trusting a stored
            // counter. Restore dispatches this action directly, bypassing the host's
            // `messages` setter — the thing that normally recomputes — so a stored total
            // would sit stale (historically at 0) until the next turn arrived. The
            // transcript is the source of truth: per-message usage survives the snapshot,
            // and a compacted summary carries the usage of the turns it replaced.
            state.sessionUsage = sumUsage(p.messages);
            state.contextTokens = p.contextTokens;
            state.contextLimit = p.contextLimit;
            state.activeModel = p.activeModel;
            state.activeProviderName = p.activeProviderName;
            state.state = 'idle';
        },
        /**
         * Wipe the session back to a fresh default — the "Clear" / "New chat" action.
         * The user's **display preferences** (tool-call / thinking / narration / agent-switch
         * visibility + animations) are deliberately preserved across Clear: they are settings,
         * not conversation state, and are persisted independently of the snapshot (GENC-1351).
         * Without this they'd flip to their all-off defaults in the live store on Clear, since
         * `clearSession` re-applies no baseline and the idempotent setters suppress a re-apply.
         */
        resetSession(state) {
            const preservedPrefs = {
                showToolCalls: state.showToolCalls,
                showThinkingSteps: state.showThinkingSteps,
                showNarration: state.showNarration,
                showAgentSwitchIndicator: state.showAgentSwitchIndicator,
                enabledAnimations: state.enabledAnimations,
            };
            Object.assign(state, createDefaultSessionState(), preservedPrefs);
        },
    },
    selectors: {},
});
