/**
 * @deprecated Scheduled for removal in v2.0.0
 * --------------------------------------------------------------------------
 * ⚠️ NOTICE: V2 DATA&UI REFACTORING (by 0xfullex)
 * --------------------------------------------------------------------------
 * STOP: Feature PRs affecting this file are currently BLOCKED.
 * Only critical bug fixes are accepted during this migration phase.
 *
 * This file is being refactored to v2 standards.
 * Any non-critical changes will conflict with the ongoing work.
 *
 * 🔗 Context & Status:
 * - Contribution Hold: https://github.com/CherryHQ/cherry-studio/issues/10954
 * - v2 Refactor PR   : https://github.com/CherryHQ/cherry-studio/pull/10162
 * --------------------------------------------------------------------------
 */
import type { PermissionUpdate } from '@anthropic-ai/claude-agent-sdk'
import type { PayloadAction } from '@reduxjs/toolkit'
import { createSlice } from '@reduxjs/toolkit'

export type ToolPermissionRequestPayload = {
  requestId: string
  toolName: string
  toolId: string
  toolCallId: string
  description?: string
  requiresPermissions: boolean
  input: Record<string, unknown>
  inputPreview: string
  createdAt: number
  suggestions: PermissionUpdate[]
  autoApprove?: boolean
}

export type ToolPermissionResultPayload = {
  requestId: string
  behavior: 'allow' | 'deny'
  message?: string
  reason: 'response' | 'timeout' | 'aborted' | 'no-window'
  toolCallId?: string
  updatedInput?: Record<string, unknown>
}

export type ToolPermissionStatus = 'pending' | 'submitting-allow' | 'submitting-deny' | 'invoking'

export type ToolPermissionEntry = ToolPermissionRequestPayload & {
  status: ToolPermissionStatus
  resolvedInput?: Record<string, unknown>
}

export interface ToolPermissionsState {
  requests: Record<string, ToolPermissionEntry>
  resolvedInputs: Record<string, Record<string, unknown>>
}

const initialState: ToolPermissionsState = {
  requests: {},
  resolvedInputs: {}
}

const toolPermissionsSlice = createSlice({
  name: 'toolPermissions',
  initialState,
  reducers: {
    requestReceived: (state, action: PayloadAction<ToolPermissionRequestPayload>) => {
      const payload = action.payload
      state.requests[payload.requestId] = {
        ...payload,
        status: 'pending'
      }
    },
    submissionSent: (state, action: PayloadAction<{ requestId: string; behavior: 'allow' | 'deny' }>) => {
      const { requestId, behavior } = action.payload
      const entry = state.requests[requestId]
      if (!entry) return

      entry.status = behavior === 'allow' ? 'submitting-allow' : 'submitting-deny'
    },
    submissionFailed: (state, action: PayloadAction<{ requestId: string }>) => {
      const entry = state.requests[action.payload.requestId]
      if (!entry) return
      entry.status = 'pending'
    },
    requestResolved: (state, action: PayloadAction<ToolPermissionResultPayload>) => {
      const { requestId, behavior, updatedInput } = action.payload
      const entry = state.requests[requestId]

      if (!entry) return

      if (behavior === 'allow') {
        entry.status = 'invoking'
        entry.resolvedInput = updatedInput
        if (updatedInput && entry.toolCallId) {
          state.resolvedInputs[entry.toolCallId] = updatedInput
        }
      } else {
        delete state.requests[requestId]
      }
    },
    removeByToolCallId: (state, action: PayloadAction<{ toolCallId: string }>) => {
      const { toolCallId } = action.payload

      const entryId = Object.keys(state.requests).find((key) => state.requests[key]?.toolCallId === toolCallId)
      if (entryId) {
        delete state.requests[entryId]
      }
      delete state.resolvedInputs[toolCallId]
    },
    clearAll: (state) => {
      state.requests = {}
      state.resolvedInputs = {}
    },
    clearPending: (state) => {
      for (const [key, entry] of Object.entries(state.requests)) {
        if (entry.status === 'pending' || entry.status === 'submitting-allow' || entry.status === 'submitting-deny') {
          delete state.requests[key]
        }
      }
    }
  }
})

export const toolPermissionsActions = toolPermissionsSlice.actions

export const selectActiveToolPermission = (state: ToolPermissionsState): ToolPermissionEntry | null => {
  const activeEntries = Object.values(state.requests).filter((entry) =>
    ['pending', 'submitting-allow', 'submitting-deny', 'invoking'].includes(entry.status)
  )

  if (activeEntries.length === 0) return null

  activeEntries.sort((a, b) => a.createdAt - b.createdAt)
  return activeEntries[0]
}

export const selectPendingPermission = (
  state: ToolPermissionsState,
  toolCallId: string
): ToolPermissionEntry | undefined => {
  const activeEntries = Object.values(state.requests)
    .filter((entry) => entry.toolCallId === toolCallId)
    .filter((entry) => ['pending', 'submitting-allow', 'submitting-deny', 'invoking'].includes(entry.status))

  if (activeEntries.length === 0) return undefined

  activeEntries.sort((a, b) => a.createdAt - b.createdAt)
  return activeEntries[0]
}

export default toolPermissionsSlice.reducer
