import {
  buildAttachmentAssociationConfirmationMessage,
  collectReceiptFiles
} from './travelReimbursementAttachmentModel.js'

export async function handleSubmitRecognitionFlow({
  activeReviewPayload,
  attachmentAssociationConfirmed,
  buildOcrDocumentsFromReviewPayload,
  buildOcrSummaryFromDocuments,
  buildReviewFormContextFromPayload,
  completeFlowStep,
  createMessage,
  createPendingAttachmentAssociationId,
  draftClaimId,
  extraContext,
  fileNames,
  filePreviews,
  files,
  mergeUploadAttachmentNames,
  mergeUploadOcrDocuments,
  nextTick,
  normalizeRecognizedAttachmentData,
  pendingAttachmentAssociations,
  pendingMessage,
  persistSessionState,
  recognizeOcrFiles,
  rememberFilePreviews,
  replaceMessage,
  resolvedUploadDisposition,
  reviewAttachmentNames,
  reviewInlineForm,
  scrollToBottom,
  startFlowStep,
  stewardDelegated
}) {
  let ocrPayload = null
  let ocrSummary = ''
  let ocrDocuments = []
  let ocrFilePreviews = []
  const recognizedAttachmentData = normalizeRecognizedAttachmentData()

  if (files.length) {
    const ocrStartedAt = Date.now()
    if (!stewardDelegated) {
      startFlowStep('ocr', { detail: `正在识别 ${files.length} 份附件...`, startedAt: ocrStartedAt })
    }
    if (recognizedAttachmentData) {
      const collected = await collectReceiptFiles({
        files,
        recognizedAttachmentData
      })
      ocrPayload = collected.ocrPayload
      ocrSummary = collected.ocrSummary
      ocrDocuments = collected.ocrDocuments
      ocrFilePreviews = collected.ocrFilePreviews
      rememberFilePreviews(ocrFilePreviews)
      if (!stewardDelegated) {
        completeFlowStep('ocr', `复用已确认的 ${ocrDocuments.length || files.length} 张票据识别结果`, Date.now() - ocrStartedAt)
      }
    } else {
      try {
        const collected = await collectReceiptFiles({
          files,
          recognizeOcrFiles
        })
        ocrPayload = collected.ocrPayload
        ocrSummary = collected.ocrSummary
        ocrDocuments = collected.ocrDocuments
        ocrFilePreviews = collected.ocrFilePreviews
        rememberFilePreviews(ocrFilePreviews)
        if (!stewardDelegated) {
          completeFlowStep('ocr', `识别到 ${ocrDocuments.length || files.length} 张票据`, Date.now() - ocrStartedAt)
        }
      } catch (error) {
        console.warn('OCR request failed:', error)
        if (!stewardDelegated) {
          completeFlowStep('ocr', 'OCR识别失败，已继续使用附件名称', Date.now() - ocrStartedAt)
        }
      }
    }

    if (!stewardDelegated && resolvedUploadDisposition === 'continue_existing') {
      replaceMessage(pendingMessage.id, {
        ...pendingMessage,
        text: attachmentAssociationConfirmed
          ? '票据识别已完成，正在把本次附件归集到已选择的草稿...'
          : '票据识别已完成，正在整理归集前确认信息...',
        meta: attachmentAssociationConfirmed ? ['正在归集'] : ['等待确认归集']
      })
      persistSessionState()
    }
  }

  const associationTargetClaimId = String(extraContext.draft_claim_id || draftClaimId.value || '').trim()
  const associationTargetClaimNo = String(
    extraContext.selected_claim_no ||
      extraContext.draft_claim_no ||
      ''
  ).trim()
  if (
    files.length &&
    resolvedUploadDisposition === 'continue_existing' &&
    associationTargetClaimId &&
    !attachmentAssociationConfirmed
  ) {
    const associationId = createPendingAttachmentAssociationId()
    const pendingAssociation = {
      id: associationId,
      status: 'pending',
      claimId: associationTargetClaimId,
      claimNo: associationTargetClaimNo,
      fileNames
    }
    pendingAttachmentAssociations.set(associationId, {
      files,
      fileNames,
      ocrPayload,
      ocrSummary,
      ocrDocuments,
      ocrFilePreviews,
      filePreviews,
      claimId: associationTargetClaimId,
      claimNo: associationTargetClaimNo,
      extraContext: {
        ...extraContext,
        draft_claim_id: associationTargetClaimId,
        selected_claim_id: associationTargetClaimId,
        selected_claim_no: associationTargetClaimNo
      }
    })
    replaceMessage(pendingMessage.id, createMessage(
      'assistant',
      buildAttachmentAssociationConfirmationMessage({
        claimNo: associationTargetClaimNo,
        fileNames,
        ocrDocuments
      }),
      [],
      {
        meta: ['等待确认归集'],
        pendingAttachmentAssociation: pendingAssociation
      }
    ))
    persistSessionState()
    nextTick(scrollToBottom)
    return { handled: true, value: null }
  }

  let effectiveFileNames = [...fileNames]
  let effectiveOcrDocuments = [...ocrDocuments]
  let effectiveOcrSummary = ocrSummary

  if (resolvedUploadDisposition === 'continue_existing') {
    extraContext.review_action = 'link_to_existing_draft'
    const inheritedReviewContext = buildReviewFormContextFromPayload(
      activeReviewPayload.value,
      reviewInlineForm.value
    )
    if (inheritedReviewContext.review_form_values) {
      extraContext.review_form_values = {
        ...inheritedReviewContext.review_form_values,
        ...(extraContext.review_form_values && typeof extraContext.review_form_values === 'object'
          ? extraContext.review_form_values
          : {})
      }
    }
    if (inheritedReviewContext.business_time_context && !extraContext.business_time_context) {
      extraContext.business_time_context = inheritedReviewContext.business_time_context
    }
    effectiveFileNames = mergeUploadAttachmentNames(reviewAttachmentNames, fileNames)
    effectiveOcrDocuments = mergeUploadOcrDocuments(
      buildOcrDocumentsFromReviewPayload(activeReviewPayload.value),
      ocrDocuments
    )
    effectiveOcrSummary = buildOcrSummaryFromDocuments(effectiveOcrDocuments)
  } else if (resolvedUploadDisposition === 'new_document') {
    extraContext.review_action = 'create_new_claim_from_documents'
  }

  return {
    handled: false,
    value: null,
    effectiveFileNames,
    effectiveOcrDocuments,
    effectiveOcrSummary,
    ocrFilePreviews
  }
}
