import {
  buildWorkbenchDocumentCommandFollowupGuidance,
  buildWorkbenchDraftDeletionGuidance,
  isWorkbenchDraftDeletionIntent,
  resolveLatestWorkbenchDocumentCommandContext,
  resolveLatestWorkbenchDraftPayload
} from './workbenchAiCommandIntentModel.js'
import { resolveWorkbenchIntentActionRoute } from './workbenchIntentActionPolicy.js'
import { resolveWorkbenchIntentFrame } from './workbenchIntentFrameModel.js'

export function useWorkbenchAiCommandIntents({
  activateInlineConversation,
  activeConversationTitle,
  assistantDraft,
  clearAiModeFiles,
  closeWorkbenchDatePicker,
  conversationId,
  conversationMessages,
  createInlineMessage,
  documentQueryFlow,
  inlineConversationAutoScrollPinned,
  persistCurrentConversation,
  removeWorkbenchDateTag,
  scrollInlineConversationToBottom,
  searchConversationId,
  sending
}) {
  function prepareInlineCommandConversation(cleanPrompt, entry = {}) {
    if (conversationId.value === searchConversationId) {
      conversationId.value = ''
      conversationMessages.value = []
      activeConversationTitle.value = ''
    }
    activateInlineConversation({
      title: entry.label || cleanPrompt.slice(0, 18) || '新对话'
    })
    inlineConversationAutoScrollPinned.value = true
    conversationMessages.value.push(createInlineMessage('user', cleanPrompt))
    assistantDraft.value = ''
    removeWorkbenchDateTag()
    closeWorkbenchDatePicker()
    clearAiModeFiles()
    scrollInlineConversationToBottom()
  }

  function handleInlineDraftDeletionIntent(cleanPrompt, entry = {}) {
    const frame = resolveWorkbenchIntentFrame(cleanPrompt)
    const route = resolveWorkbenchIntentActionRoute(frame)
    const legacyDraftDelete = isWorkbenchDraftDeletionIntent(cleanPrompt)
    const commandObjectSupported = !frame || frame.action !== 'delete' || (
      ['draft', 'application', 'reimbursement', 'document'].includes(frame.objectType)
    )
    const handlesWorkbenchCommand = (
      commandObjectSupported && (
        route.nextStep === 'open_context_confirm' ||
        route.nextStep === 'query_candidates'
      ) ||
      legacyDraftDelete
    )
    if (!handlesWorkbenchCommand) {
      return false
    }
    const documentCommandContext = route.nextStep === 'query_candidates'
      ? resolveLatestWorkbenchDocumentCommandContext(conversationMessages.value, frame)
      : null
    prepareInlineCommandConversation(cleanPrompt, entry)
    const draftPayload = frame?.targetMode === 'current_context' || legacyDraftDelete
      ? resolveLatestWorkbenchDraftPayload(conversationMessages.value)
      : null
    if (route.nextStep === 'open_context_confirm' && draftPayload) {
      const guidance = buildWorkbenchDraftDeletionGuidance(draftPayload)
      conversationMessages.value.push(createInlineMessage('assistant', guidance.content, {
        suggestedActions: guidance.suggestedActions
      }))
      persistCurrentConversation()
      scrollInlineConversationToBottom({ force: inlineConversationAutoScrollPinned.value })
      return true
    }

    if (route.nextStep === 'query_candidates' && documentCommandContext) {
      const guidance = buildWorkbenchDocumentCommandFollowupGuidance(documentCommandContext, frame)
      conversationMessages.value.push(createInlineMessage('assistant', guidance.content, {
        suggestedActions: guidance.suggestedActions
      }))
      persistCurrentConversation()
      scrollInlineConversationToBottom({ force: inlineConversationAutoScrollPinned.value })
      return true
    }

    const queryPrompt = route.queryPrompt || frame?.normalizedQuery || '我的草稿单据'
    const pendingText = frame?.safetyLevel === 'confirm_required'
      ? '正在先筛选候选单据，不会直接执行删除或审核动作...'
      : '正在查询匹配条件的单据...'
    const pendingMessage = createInlineMessage('assistant', pendingText, {
      pending: true
    })
    conversationMessages.value.push(pendingMessage)
    persistCurrentConversation()
    sending.value = true
    void documentQueryFlow.handleAiDocumentQueryIntent(queryPrompt, pendingMessage, {
      commandFrame: frame
    })
      .finally(() => {
        sending.value = false
        scrollInlineConversationToBottom({ force: inlineConversationAutoScrollPinned.value })
      })
    return true
  }

  return {
    handleInlineDraftDeletionIntent
  }
}
