/**
 * @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
  expiresAt: number
  suggestions: PermissionUpdate[]
  autoApprove?: boolean
}

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

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

export type ToolPermissionEntry = ToolPermissionRequestPayload & {
  status: ToolPermissionStatus
}

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

const initialState: ToolPermissionsState = {
  requests: {}
}

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 } = action.payload
      const entry = state.requests[requestId]

      if (!entry) return

      if (behavior === 'allow') {
        entry.status = 'invoking'
      } 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]
      }
    },
    clearAll: (state) => {
      state.requests = {}
    }
  }
})

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
