import {
  buildLocalApplicationPreviewMessage,
  shouldUseLocalApplicationPreview
} from '../../utils/expenseApplicationPreview.js'
import { STEWARD_ASSISTANT_NAME } from './travelReimbursementSubmitConstants.js'
import {
  buildApplicationDateConflictActions,
  buildApplicationDateConflictMessage,
  findOverlappingApplicationClaim
} from './travelReimbursementSubmitApplicationConflicts.js'

export async function handleLocalApplicationPreviewFlow({
  adjustComposerTextareaHeight,
  buildApplicationPreviewWithModelReview,
  buildStewardApplicationPreviewMessage,
  buildStewardApplicationPreviewSuggestedActions,
  buildStewardDelegatedPlan,
  buildStewardSlotDecisionMessage,
  buildStewardSlotDecisionSuggestedActions,
  clearAttachedFiles,
  completeFlowStep,
  composerBusinessTimeDraftTouched,
  composerBusinessTimeTags,
  composerDraft,
  createMessage,
  effectiveSessionType,
  fetchExpenseClaims,
  fetchStewardApplicationSlotDecision,
  fileInputRef,
  fileNames,
  files,
  messages,
  nextTick,
  options,
  persistSessionState,
  rawText,
  registerApplicationPreviewDecision = async ({ applicationPreview }) => applicationPreview,
  replaceMessage,
  resetFlowRun,
  resetStewardDelegatedInsightState,
  reviewAction,
  scrollToBottom,
  selectedBusinessTimeContext,
  shouldPauseStewardApplicationPreview,
  startFlowStep,
  stewardDelegated,
  submitting,
  systemGenerated,
  typeStewardDelegatedMessage,
  userText
}) {
  if (!shouldUseLocalApplicationPreview(rawText, {
    sessionType: effectiveSessionType,
    attachmentCount: files.length,
    reviewAction,
    systemGenerated
  })) {
    return { handled: false, value: null }
  }

        const intentStartedAt = Date.now()
        const reviewStartedAt = intentStartedAt
        if (stewardDelegated) {
          resetStewardDelegatedInsightState()
        } else {
          resetFlowRun()
          startFlowStep('intent', {
            title: '业务意图识别',
            tool: 'ontology.intent_detection',
            detail: '正在识别是否为费用申请事项...'
          })
          startFlowStep('application-review-preview', {
            title: '申请信息核对',
            tool: 'ontology.application_review',
            detail: '正在复核申请信息，并查询交通票价...'
          })
        }
        if (!options.skipUserMessage) {
          messages.value.push(createMessage('user', userText, fileNames))
        }
        const pendingMessage = createMessage(
          'assistant',
          stewardDelegated ? '' : '正在复核申请信息，并查询交通票价，请稍候。',
          [],
          stewardDelegated
            ? {
                assistantName: STEWARD_ASSISTANT_NAME,
                meta: [STEWARD_ASSISTANT_NAME, '思考中'],
                stewardContinuation: options.stewardContinuation || null,
                stewardPlan: buildStewardDelegatedPlan(options.stewardContinuation || null, [], 'streaming')
              }
            : {
                meta: ['模型复核中']
              }
        )
        messages.value.push(pendingMessage)
        composerDraft.value = ''
        composerBusinessTimeTags.value = []
        composerBusinessTimeDraftTouched.value = false
        clearAttachedFiles()
        if (fileInputRef.value) {
          fileInputRef.value.value = ''
        }
        nextTick(() => {
          adjustComposerTextareaHeight()
          scrollToBottom()
        })
        persistSessionState()

        submitting.value = true
        try {
          const { applicationPreview: generatedApplicationPreview, meta } = await buildApplicationPreviewWithModelReview(
            rawText,
            selectedBusinessTimeContext,
            effectiveSessionType,
            {
              skipModelReview: Boolean(stewardDelegated && options.skipApplicationModelReview)
            }
          )
          const reviewStatus = String(meta?.[1] || '').trim()
          let applicationDateConflict = null
          try {
            const existingClaims = await fetchExpenseClaims({ page: 1, pageSize: 100 })
            applicationDateConflict = findOverlappingApplicationClaim(generatedApplicationPreview, existingClaims)
          } catch (error) {
            console.warn('Failed to check overlapping application dates:', error)
          }

          if (applicationDateConflict) {
            const conflictText = buildApplicationDateConflictMessage(applicationDateConflict)
            const conflictActions = buildApplicationDateConflictActions(applicationDateConflict)
            if (!stewardDelegated) {
              completeFlowStep('intent', '已识别为费用申请事项', Date.now() - intentStartedAt)
              completeFlowStep(
                'application-review-preview',
                '检测到同日期已有申请，已停止重复创建',
                Date.now() - reviewStartedAt
              )
              replaceMessage(pendingMessage.id, createMessage(
                'assistant',
                conflictText,
                [],
                {
                  meta: ['申请日期冲突'],
                  suggestedActions: conflictActions,
                  stewardContinuation: options.stewardContinuation || null
                }
              ))
            } else {
              await typeStewardDelegatedMessage(
                pendingMessage.id,
                conflictText,
                {
                  meta: [STEWARD_ASSISTANT_NAME, '申请日期冲突'],
                  suggestedActions: conflictActions,
                  stewardContinuation: options.stewardContinuation || null
                },
                {
                  sessionType: effectiveSessionType,
                  rawText,
                  applicationPreview: generatedApplicationPreview,
                  stewardContinuation: options.stewardContinuation || null
                }
              )
            }
            persistSessionState()
            nextTick(scrollToBottom)
            return { handled: true, value: null }
          }

          if (!stewardDelegated) {
            completeFlowStep('intent', '已识别为费用申请事项', Date.now() - intentStartedAt)
            completeFlowStep(
              'application-review-preview',
              reviewStatus === '模型复核完成'
                ? '模型复核完成，已生成申请核对表'
                : reviewStatus === '模型复核失败'
                  ? '模型复核失败，已生成临时核对表'
                  : '模型未返回稳定结果，已完成规则兜底核对',
              Date.now() - reviewStartedAt
            )
          }
          let applicationPreview = generatedApplicationPreview
          if (stewardDelegated) {
            const fallbackStewardApplicationText = buildStewardApplicationPreviewMessage(
              applicationPreview,
              buildLocalApplicationPreviewMessage(applicationPreview)
            )
            const localPauseForMissingFields = shouldPauseStewardApplicationPreview(applicationPreview)
            const shouldFetchSlotDecision = localPauseForMissingFields && !options.skipStewardSlotDecision
            const slotDecision = shouldFetchSlotDecision
              ? await fetchStewardApplicationSlotDecision(
                applicationPreview,
                rawText,
                options.stewardContinuation || null
              )
              : null
            const slotDecisionActions = buildStewardSlotDecisionSuggestedActions(slotDecision, applicationPreview)
            const pauseForMissingFields = slotDecision
              ? String(slotDecision.next_action || '').trim() === 'ask_user'
              : localPauseForMissingFields
            if (!pauseForMissingFields) {
              applicationPreview = await registerApplicationPreviewDecision({
                applicationPreview,
                sourceText: rawText,
                targetMessage: pendingMessage
              })
            }
            const stewardApplicationText = buildStewardSlotDecisionMessage(
              slotDecision,
              applicationPreview,
              fallbackStewardApplicationText
            )
            await typeStewardDelegatedMessage(
              pendingMessage.id,
              stewardApplicationText,
              {
                meta,
                applicationPreview: pauseForMissingFields ? null : applicationPreview,
                suggestedActions: slotDecisionActions.length
                  ? slotDecisionActions
                  : buildStewardApplicationPreviewSuggestedActions(applicationPreview),
                stewardContinuation: options.stewardContinuation || null
              },
              {
                sessionType: effectiveSessionType,
                rawText,
                applicationPreview,
                stewardContinuation: options.stewardContinuation || null
              }
            )
          } else {
            applicationPreview = await registerApplicationPreviewDecision({
              applicationPreview,
              sourceText: rawText,
              targetMessage: pendingMessage
            })
            replaceMessage(pendingMessage.id, createMessage(
              'assistant',
              buildLocalApplicationPreviewMessage(applicationPreview),
              [],
              {
                meta,
                applicationPreview,
                stewardContinuation: options.stewardContinuation || null
              }
            ))
          }
          persistSessionState()
          nextTick(scrollToBottom)
        } finally {
          submitting.value = false
        }
        return { handled: true, value: null }
}
