import {
  applyApplicationBusinessTimeContext,
  applyApplicationPolicyEstimateError,
  applyApplicationPolicyEstimateResult,
  buildApplicationPolicyEstimateRequest,
  buildLocalApplicationPreview,
  buildModelRefinedApplicationPreview
} from '../../utils/expenseApplicationPreview.js'
import { waitForMockApplicationTransportQuote } from '../../utils/expenseApplicationEstimate.js'
import { fetchOntologyParse } from '../../services/ontology.js'
import { buildExpenseApplicationOntologyContext } from '../../utils/expenseApplicationOntology.js'
import { calculateTravelReimbursement } from '../../services/reimbursements.js'

export function createSubmitApplicationPreviewHelpers({
  activeSessionType,
  currentUser,
  isKnowledgeSession,
  linkedRequest,
  props,
  refreshCurrentUserFromBackend
}) {
    function buildBackendMessage(rawText, fileNames, ocrSummary = '', sessionTypeOverride = '') {
      const parts = []
      const normalizedText = String(rawText || '').trim()
      const sessionType = String(sessionTypeOverride || activeSessionType.value || '').trim()
      const isKnowledgeMessage = sessionType === 'knowledge'

      if (normalizedText) {
        parts.push(normalizedText)
      } else if (fileNames.length) {
        parts.push(
          isKnowledgeMessage
            ? `我上传了 ${fileNames.length} 份附件，请结合附件名称回答财务相关问题。`
            : sessionType === 'application'
              ? `我上传了 ${fileNames.length} 份附件，请结合附件名称整理费用申请建议和待核对信息。`
              : sessionType === 'approval'
                ? `我上传了 ${fileNames.length} 份附件，请结合附件名称整理审核风险和处理建议。`
                : `我上传了 ${fileNames.length} 份票据，请结合附件名称给出报销建议并整理待核对信息。`
        )
      }

      if (fileNames.length) {
        parts.push(`附件名称：${fileNames.join('、')}`)
      }

      if (ocrSummary) {
        parts.push(`OCR摘要：${ocrSummary}`)
      }

      if (props.entrySource === 'detail' && linkedRequest.value?.id) {
        parts.push(`关联单号：${linkedRequest.value.id}`)
      }

      return parts.join('\n')
    }

    function resolveDetailScopedClaimId() {
      if (props.entrySource !== 'detail' || isKnowledgeSession.value) {
        return ''
      }
      return String(
        linkedRequest.value?.claimId ||
          linkedRequest.value?.claim_id ||
          ''
      ).trim()
    }

    function buildApplicationPreviewReviewMeta(ontology) {
      return [
        '申请核对预览',
        String(ontology?.parse_strategy || '').trim() === 'llm_primary'
          ? '模型复核完成'
          : '规则兜底复核'
      ]
    }

    async function resolveApplicationPreviewUser() {
      const user = currentUser.value || {}
      if (String(user.position || '').trim() || typeof refreshCurrentUserFromBackend !== 'function') {
        return user
      }

      await refreshCurrentUserFromBackend({ silent: true })
      return currentUser.value || user
    }

    async function buildApplicationPreviewWithModelReview(
      rawText,
      businessTimeContext = null,
      sessionTypeOverride = '',
      options = {}
    ) {
      const user = await resolveApplicationPreviewUser()
      const localPreview = applyApplicationBusinessTimeContext(
        buildLocalApplicationPreview(rawText, user),
        businessTimeContext
      )

      const enrichWithPolicyEstimate = async (preview) => {
        const estimateRequest = buildApplicationPolicyEstimateRequest(preview, user)
        if (!estimateRequest.canCalculate) {
          return preview
        }
        try {
          const fields = preview?.fields || {}
          await waitForMockApplicationTransportQuote({
            transportMode: fields.transportMode,
            location: fields.location,
            time: fields.time
          })
          const result = await calculateTravelReimbursement(estimateRequest.payload)
          return applyApplicationPolicyEstimateResult(preview, result, user)
        } catch (error) {
          console.warn('Application policy estimate failed:', error)
          return applyApplicationPolicyEstimateError(preview, error, user)
        }
      }

      if (options.skipModelReview) {
        return {
          applicationPreview: await enrichWithPolicyEstimate({
            ...localPreview,
            modelReviewStatus: 'skipped'
          }),
          meta: ['申请核对预览', '结构化快路径']
        }
      }

      try {
        const ontology = await fetchOntologyParse(
          {
            query: rawText,
            user_id: user.username || user.name || 'anonymous',
            context_json: {
              ...buildExpenseApplicationOntologyContext(user),
              session_type: String(sessionTypeOverride || activeSessionType.value || '').trim(),
              entry_source: props.entrySource,
              user_input_text: rawText
            }
          },
          {
            timeoutMs: 45000,
            timeoutMessage: '模型抽取申请字段超时，已保留当前本地预览。'
          }
        )

        const refinedPreview = applyApplicationBusinessTimeContext(
          buildModelRefinedApplicationPreview(
            localPreview,
            ontology,
            rawText,
            user
          ),
          businessTimeContext
        )
        return {
          applicationPreview: await enrichWithPolicyEstimate(refinedPreview),
          meta: buildApplicationPreviewReviewMeta(ontology)
        }
      } catch (error) {
        console.warn('Application preview model refinement failed:', error)
        return {
          applicationPreview: await enrichWithPolicyEstimate({
            ...localPreview,
            modelReviewStatus: 'failed'
          }),
          meta: ['申请核对预览', '模型复核失败']
        }
      }
    }


  return {
    buildApplicationPreviewWithModelReview,
    buildBackendMessage,
    resolveDetailScopedClaimId
  }
}
