import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface AgentConfigState {
  activeEngine: 'claude_code_cli' | 'claude_api' | 'custom';
  systemPrompt: string;
  maxTurns: number;
  maxBudgetUsd: number;
  allowedTools: string[];
  hooks: Array<{ id: string; name: string; script: string; enabled: boolean }>;
}

const initialState: AgentConfigState = {
  activeEngine: 'claude_code_cli',
  systemPrompt: '',
  maxTurns: 20,
  maxBudgetUsd: 5.0,
  allowedTools: ['Bash', 'Read', 'Write', 'Glob', 'Grep'],
  hooks: [],
};

export const agentConfigSlice = createSlice({
  name: 'agentConfig',
  initialState,
  reducers: {
    setActiveEngine: (state, action: PayloadAction<AgentConfigState['activeEngine']>) => {
      state.activeEngine = action.payload;
    },
    setSystemPrompt: (state, action: PayloadAction<string>) => {
      state.systemPrompt = action.payload;
    },
    setMaxTurns: (state, action: PayloadAction<number>) => {
      state.maxTurns = action.payload;
    },
    setAllowedTools: (state, action: PayloadAction<string[]>) => {
      state.allowedTools = action.payload;
    },
    addHook: (state, action: PayloadAction<{ name: string; script: string }>) => {
      state.hooks.push({
        id: crypto.randomUUID(),
        ...action.payload,
        enabled: true,
      });
    },
    toggleHook: (state, action: PayloadAction<string>) => {
      const hook = state.hooks.find((h) => h.id === action.payload);
      if (hook) hook.enabled = !hook.enabled;
    },
  },
});

export const agentConfigActions = agentConfigSlice.actions;
