import {
  buildRiskRuleFieldSummary,
  formatRiskRuleAge,
  resolveRiskRuleBusinessDescription,
  resolveRiskRuleCreatedAt,
  resolveRiskRuleFields,
  resolveRiskRuleFlow,
  resolveRiskRuleFlowDiagramSvg,
  resolveRiskRuleScore,
  resolveRiskRuleScoreDetail,
  resolveRiskRuleScoreLabel,
  resolveRiskRuleScoreLevel,
  resolveRiskRuleSeverity,
  resolveRiskRuleSeverityLabel
} from './auditViewRiskRuleModel.js'
import {
  isPlainObject,
  normalizeText,
  readConfigJson
} from './auditViewDataUtils.js'
import { formatDateTime } from './auditViewFormatters.js'
import {
  buildRiskListSubtitle,
  resolveRiskRuleCategory,
  resolveRiskRuleDescription,
  resolveRiskRuleSourceRef
} from './auditViewRuleClassifier.js'
export function resolveRiskRuleEnabled(source, rulePayload = null) {
  const configJson = readConfigJson(source)
  if (isPlainObject(rulePayload) && rulePayload.enabled === false) {
    return false
  }
  if (source?.enabled === false || configJson.enabled === false) {
    return false
  }
  return true
}

const LAST_OPERATION_LABELS = {
  generate: '开始生成',
  create: '创建',
  test: '测试',
  online: '上线',
  offline: '下线',
  generation_failed: '生成失败',
  delete: '删除',
  update: '更新'
}

const RISK_RULE_BUSINESS_STAGE_LABELS = {
  expense_application: '费用申请',
  reimbursement: '费用报销'
}

export function resolveRiskRuleBusinessStage(source, rulePayload = null) {
  const configJson = readConfigJson(source)
  const metadata = rulePayload && typeof rulePayload === 'object' ? rulePayload.metadata || {} : {}
  const stage =
    normalizeText(configJson.business_stage) ||
    normalizeText(metadata.business_stage) ||
    normalizeText(rulePayload?.business_stage)
  const label =
    normalizeText(configJson.business_stage_label) ||
    normalizeText(metadata.business_stage_label) ||
    RISK_RULE_BUSINESS_STAGE_LABELS[stage]
  return {
    value: stage || 'reimbursement',
    label: label || '费用报销'
  }
}

export function resolveRiskRuleOnlineMeta(statusValue) {
  if (statusValue === 'active') {
    return { label: '已上线', tone: 'success', online: true }
  }
  if (statusValue === 'disabled') {
    return { label: '已下线', tone: 'disabled', online: false }
  }
  if (statusValue === 'generating') {
    return { label: '生成中', tone: 'info', online: false }
  }
  if (statusValue === 'failed') {
    return { label: '生成失败', tone: 'danger', online: false }
  }
  return { label: '待上线', tone: 'draft', online: false }
}

export function resolveLastOperationLabel(source, fallback = {}) {
  const configJson = readConfigJson(source)
  const operation = isPlainObject(configJson.last_operation) ? configJson.last_operation : {}
  const action = normalizeText(operation.action) || normalizeText(fallback.action) || 'create'
  const actor = normalizeText(operation.actor) || normalizeText(fallback.actor) || '系统'
  const at = normalizeText(operation.at) || normalizeText(fallback.at)
  const actionLabel = LAST_OPERATION_LABELS[action] || action
  const timeLabel = formatDateTime(at)
  return timeLabel && timeLabel !== '-' ? `${actionLabel}：${actor} · ${timeLabel}` : `${actionLabel}：${actor}`
}

export function applyRiskRuleJsonState(target, payload, apiPayload) {
  const rulePayload = isPlainObject(payload) ? payload : {}
  const metadata = rulePayload.metadata && typeof rulePayload.metadata === 'object'
    ? rulePayload.metadata
    : {}
  const apiConfig = apiPayload?.config_json && typeof apiPayload.config_json === 'object'
    ? apiPayload.config_json
    : {}
  const fullDescription =
    resolveRiskRuleDescription(rulePayload) ||
    normalizeText(apiPayload?.description) ||
    normalizeText(target.riskRuleDescription)
  const riskCategory =
    normalizeText(metadata.expense_category_label) ||
    normalizeText(apiConfig.expense_category_label) ||
    normalizeText(rulePayload.risk_category) ||
    resolveRiskRuleCategory({ ...target, risk_category: rulePayload.risk_category, config_json: rulePayload })
  const businessStage = resolveRiskRuleBusinessStage(target, rulePayload)
  const riskRuleFields = resolveRiskRuleFields(rulePayload)
  const riskRuleCreatedAt = resolveRiskRuleCreatedAt(rulePayload, target.createdAt || target.updatedAt)
  const riskRuleScoreLevel = resolveRiskRuleScoreLevel(rulePayload, apiConfig)

  const statusValue = apiPayload?.status || target.statusValue || 'draft'
  const onlineMeta = resolveRiskRuleOnlineMeta(statusValue)
  const isEnabledValue = resolveRiskRuleEnabled(target, rulePayload)

  const publisher =
    target.creator ||
    normalizeText(apiPayload?.owner) ||
    normalizeText(metadata.created_by) ||
    normalizeText(apiPayload?.recent_versions?.[0]?.created_by) ||
    '未知'

  let publishedAt = target.publishedAt || '-'
  if (apiPayload?.recent_versions) {
    const publishedVersionObj = apiPayload.recent_versions.find((item) =>
      item?.is_current || item?.version === apiPayload?.published_version
    )
    publishedAt = publishedVersionObj?.created_at
      ? formatDateTime(publishedVersionObj.created_at)
      : (apiPayload?.latest_review?.reviewed_at ? formatDateTime(apiPayload.latest_review.reviewed_at) : '-')
  } else if (apiPayload?.latest_review?.reviewed_at) {
    publishedAt = formatDateTime(apiPayload.latest_review.reviewed_at)
  }

  return {
    ...target,
    riskRuleDescription: fullDescription,
    riskRuleBusinessDescription: resolveRiskRuleBusinessDescription(rulePayload, fullDescription),
    riskRuleSubtitle: buildRiskListSubtitle(fullDescription, 48),
    riskCategory,
    businessStageValue: businessStage.value,
    businessStageLabel: businessStage.label,
    scope: riskCategory,
    riskRuleSourceRef: resolveRiskRuleSourceRef(rulePayload),
    riskRuleSeverity: riskRuleScoreLevel || resolveRiskRuleSeverity(rulePayload),
    riskRuleSeverityLabel: riskRuleScoreLevel
      ? resolveRiskRuleScoreLabel(rulePayload, apiConfig)
      : resolveRiskRuleSeverityLabel(rulePayload),
    riskRuleScore: resolveRiskRuleScore(rulePayload, apiConfig),
    riskRuleScoreLabel: resolveRiskRuleScoreLabel(rulePayload, apiConfig),
    riskRuleScoreLevel: riskRuleScoreLevel || resolveRiskRuleSeverity(rulePayload),
    riskRuleScoreDetail: resolveRiskRuleScoreDetail(rulePayload, apiConfig),
    riskRuleCreatedAt: formatDateTime(riskRuleCreatedAt),
    riskRuleAgeLabel: formatRiskRuleAge(riskRuleCreatedAt),
    riskRuleFields,
    riskRuleFieldSummary: buildRiskRuleFieldSummary(riskRuleFields),
    riskRuleFlow: resolveRiskRuleFlow(rulePayload, riskRuleFields),
    riskRuleFlowDiagramSvg: resolveRiskRuleFlowDiagramSvg({
      ...rulePayload,
      flow_diagram_svg: normalizeText(apiPayload?.flow_diagram_svg) || rulePayload?.flow_diagram_svg
    }),
    riskRuleRequiresAttachment: Boolean(
      rulePayload.requires_attachment ||
      metadata.requires_attachment ||
      apiConfig.requires_attachment ||
      target.configJson?.requires_attachment
    ),
    riskRuleSummary: {
      name: apiPayload?.name || target.name,
      evaluator: apiPayload?.evaluator || rulePayload.evaluator || '',
      ontologySignal: apiPayload?.ontology_signal || rulePayload.ontology_signal || '',
      inputs: apiPayload?.inputs || rulePayload.inputs || {},
      outcomes: apiPayload?.outcomes || rulePayload.outcomes || {}
    },
    riskRuleJsonText: JSON.stringify(rulePayload, null, 2),
    isOnlineValue: onlineMeta.online,
    isOnlineLabel: onlineMeta.label,
    isOnlineTone: onlineMeta.tone,
    isEnabledValue,
    isEnabledLabel: isEnabledValue ? '是' : '否',
    isEnabledTone: isEnabledValue ? 'success' : 'disabled',
    lastOperationLabel: resolveLastOperationLabel(target, {
      actor: publisher,
      at: riskRuleCreatedAt
    }),
    publisher,
    publishedAt
  }
}
