import {
  DETAIL_TITLES,
  PREVIEW_RULE_CODE,
  PREVIEW_RULE_ID,
  PREVIEW_RULE_VERSION_SPECS,
  SCENARIO_LABELS,
  VERSION_STATE_META
} from './auditViewMetadata.js'
import {
  formatRiskRuleAge,
  resolveRiskRuleFlow,
  resolveRiskRuleScore,
  resolveRiskRuleScoreDetail,
  resolveRiskRuleScoreLabel,
  resolveRiskRuleScoreLevel,
  resolveRiskRuleSeverity,
  resolveRiskRuleSeverityLabel
} from './auditViewRiskRuleModel.js'
import {
  isPlainObject,
  normalizeText,
  readConfigJson
} from './auditViewDataUtils.js'
import {
  formatDateTime,
  formatInputSummary,
  formatOutputSummary,
  formatScenarioList,
  formatSeverity,
  formatSpreadsheetChangeSummary,
  makeShort,
  resolveDiffChangeMeta,
  resolveDomainLabel,
  resolveReviewMeta,
  resolveStatusMeta,
  resolveTimelineEventMeta,
  resolveTypeKey
} from './auditViewFormatters.js'
import {
  buildDefaultRuntimeRule,
  buildMarkdownVersionContent,
  cloneJsonObject,
  extractRuntimeRuleFromMarkdown,
  extractSpreadsheetMetaFromMarkdown,
  parseRuntimeRuleText,
  resolveRuleTemplateLabel,
  resolveRuntimeRuleForVersion,
  stringifyRuntimeRule,
  stripRuntimeRuleBlock
} from './auditViewRuleContentModel.js'
import {
  buildRiskListSubtitle,
  collectRuleTagValues,
  inferFinancialRuleCategory,
  inferRiskCategoryFromCode,
  isJsonRiskRuleSource,
  isSpreadsheetRuleSource,
  normalizeExpenseTypeScenarioLabels,
  normalizeRiskScenarioCategory,
  normalizeRuleTagValue,
  readRiskRuleExpenseTypes,
  readRuleDocumentMeta,
  readScenarioItems,
  resolveRiskRuleCategory,
  resolveRiskRuleDescription,
  resolveRiskRuleSourceRef,
  resolveRuleScenarioCategory,
  resolveRuleScenarioList,
  resolveRuleTabId,
  resolveTabId,
  resolveTabMeta
} from './auditViewRuleClassifier.js'
import {
  applyRiskRuleJsonState,
  resolveRiskRuleBusinessStage,
  resolveRiskRuleEnabled,
  resolveLastOperationLabel,
  resolveRiskRuleOnlineMeta
} from './auditViewRiskRuleState.js'
import {
  buildListItem,
  buildRowMetric,
  buildRowRuntime,
  findLatestMcpCall
} from './auditViewListItemModel.js'


export {
  DETAIL_TITLES,
  DOMAIN_LABELS,
  ENABLED_STATE_OPTIONS,
  EXPENSE_RULE_BLOCK_PATTERN,
  JSON_RISK_DETAIL_MODE,
  LEGACY_RISK_SCENARIO_KEYS,
  PREVIEW_RULE_CODE,
  PREVIEW_RULE_ID,
  PREVIEW_RULE_VERSION_SPECS,
  REVIEW_META,
  RISK_SCENARIO_OPTIONS,
  RISK_SCENARIO_VALUES,
  RISK_RULE_TABLE_COLUMNS,
  RULE_SPREADSHEET_BLOCK_PATTERN,
  RULE_TABLE_COLUMNS,
  RULE_TAB_TAG_ALIASES,
  RULE_TEMPLATE_LABELS,
  SCENARIO_LABELS,
  SPREADSHEET_DETAIL_MODE,
  STATUS_META,
  STATUS_OPTIONS,
  ONLINE_STATE_OPTIONS,
  TAB_META,
  TYPE_META,
  VERSION_STATE_META
} from './auditViewMetadata.js'

export {
  isPlainObject,
  normalizeText,
  readConfigJson
} from './auditViewDataUtils.js'

export {
  formatDateTime,
  formatInputSummary,
  formatOutputSummary,
  formatScenarioList,
  formatSeverity,
  formatSpreadsheetChangeSummary,
  makeShort,
  resolveDiffChangeMeta,
  resolveDomainLabel,
  resolveReviewMeta,
  resolveStatusMeta,
  resolveTimelineEventMeta,
  resolveTypeKey
} from './auditViewFormatters.js'

export {
  buildDefaultRuntimeRule,
  buildMarkdownVersionContent,
  cloneJsonObject,
  extractRuntimeRuleFromMarkdown,
  extractSpreadsheetMetaFromMarkdown,
  parseRuntimeRuleText,
  resolveRuleTemplateLabel,
  resolveRuntimeRuleForVersion,
  stringifyRuntimeRule,
  stripRuntimeRuleBlock
} from './auditViewRuleContentModel.js'

export {
  buildRiskListSubtitle,
  collectRuleTagValues,
  inferFinancialRuleCategory,
  inferRiskCategoryFromCode,
  isJsonRiskRuleSource,
  isSpreadsheetRuleSource,
  normalizeExpenseTypeScenarioLabels,
  normalizeRiskScenarioCategory,
  normalizeRuleTagValue,
  readRiskRuleExpenseTypes,
  readRuleDocumentMeta,
  readScenarioItems,
  resolveRiskRuleCategory,
  resolveRiskRuleDescription,
  resolveRiskRuleSourceRef,
  resolveRuleScenarioCategory,
  resolveRuleScenarioList,
  resolveRuleTabId,
  resolveTabId,
  resolveTabMeta
} from './auditViewRuleClassifier.js'

export {
  applyRiskRuleJsonState,
  resolveRiskRuleBusinessStage,
  resolveRiskRuleEnabled,
  resolveRiskRuleOnlineMeta
} from './auditViewRiskRuleState.js'

export {
  buildListItem,
  buildRowMetric,
  buildRowRuntime,
  findLatestMcpCall
} from './auditViewListItemModel.js'

export function buildPreviewSpreadsheetMeta(spec) {
  return {
    file_name: spec.fileName,
    storage_key: `preview/agent-assets/${PREVIEW_RULE_ID}/${spec.version}/${encodeURIComponent(spec.fileName)}`,
    mime_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    size_bytes: 82416,
    checksum: `preview-${spec.version.replace(/\./g, '-')}`,
    updated_at: spec.updatedAt,
    updated_by: spec.updatedBy,
    source: spec.source
  }
}

export function buildPreviewSpreadsheetVersionMarkdown(spec) {
  const metadata = buildPreviewSpreadsheetMeta(spec)
  return [
    '# 公司差旅费报销规则',
    '',
    '## 规则载体',
    '',
    '- 页面状态：前端预览',
    `- 当前规则版本：\`${spec.version}\``,
    `- 表格文件：\`${spec.fileName}\``,
    `- 最近更新人：${spec.updatedBy}`,
    `- 最近更新时间：${spec.updatedAt}`,
    '',
    '## 说明',
    '',
    '- 当前环境暂无真实规则文件，先用于展示 Excel 规则详情页布局。',
    '- 真实上传、编辑与版本回写逻辑会在接好正式数据后启用。',
    '',
    '```rule-spreadsheet',
    JSON.stringify(metadata, null, 2),
    '```'
  ].join('\n')
}

export function createPreviewRuleDetailPayload() {
  const recentVersions = PREVIEW_RULE_VERSION_SPECS.map((spec, index) => ({
    id: `${PREVIEW_RULE_ID}-version-${index + 1}`,
    asset_id: PREVIEW_RULE_ID,
    version: spec.version,
    content: buildPreviewSpreadsheetVersionMarkdown(spec),
    content_type: 'markdown',
    change_note: spec.note,
    created_by: spec.updatedBy,
    created_at: spec.updatedAt,
    is_current: spec.isCurrent
  }))
  const currentSpec = PREVIEW_RULE_VERSION_SPECS[0]
  const currentMeta = buildPreviewSpreadsheetMeta(currentSpec)

  return {
    id: PREVIEW_RULE_ID,
    asset_type: 'rule',
    code: PREVIEW_RULE_CODE,
    name: '公司差旅费报销规则',
    description: '前端预览态：先展示 Excel 规则详情页布局、版本卡片和编辑入口位置。',
    domain: 'expense',
    scenario_json: ['差旅'],
    owner: '财务制度管理组',
    reviewer: '顾承宇',
    status: 'active',
    current_version: currentSpec.version,
    published_version: currentSpec.version,
    working_version: currentSpec.version,
    config_json: {
      severity: 'medium',
      enabled: true,
      tag: '基础规则',
      detail_mode: 'spreadsheet',
      runtime_kind: 'travel_policy',
      scenario_category: '差旅',
      ai_review_category: '差旅',
      rule_template_label: '差旅报销 Excel 模板',
      rule_document: {
        ...currentMeta,
        asset_version: currentSpec.version
      }
    },
    created_at: '2026-05-10T11:10:00Z',
    updated_at: currentSpec.updatedAt,
    current_version_content: recentVersions[0].content,
    current_version_content_type: 'markdown',
    current_version_change_note: currentSpec.note,
    recent_versions: recentVersions,
    latest_review: {
      id: `${PREVIEW_RULE_ID}-review-1`,
      asset_id: PREVIEW_RULE_ID,
      version: currentSpec.version,
      reviewer: '顾承宇',
      review_status: 'approved',
      review_note: '当前为页面预览态，先确认布局与交互位置。',
      reviewed_at: '2026-05-17T10:00:00Z',
      created_at: '2026-05-17T10:00:00Z'
    }
  }
}

export function buildPreviewRuleListItem() {
  const payload = createPreviewRuleDetailPayload()
  return {
    ...buildListItem(payload),
    isPreviewMock: true
  }
}

export function buildPreviewRuleDetail() {
  const detail = buildDetailViewModel(createPreviewRuleDetailPayload(), [])
  return {
    ...detail,
    isPreviewMock: true
  }
}

export function buildHistory(recentVersions = [], source) {
  const currentRuntimeRule = cloneJsonObject(readConfigJson(source).runtime_rule)

  return recentVersions.map((item) => {
    const rawContent = typeof item.content === 'string' ? item.content : ''
    return {
      version: item.version,
      note: item.change_note || '无版本说明',
      time: formatDateTime(item.created_at),
      content: rawContent,
      markdownContent: stripRuntimeRuleBlock(rawContent),
      runtimeRule: resolveRuntimeRuleForVersion(
        source,
        rawContent,
        item.is_current ? currentRuntimeRule : null
      ),
      spreadsheetMeta: extractSpreadsheetMetaFromMarkdown(rawContent),
      contentType: item.content_type,
      createdBy: item.created_by,
      isCurrent: Boolean(item.is_current),
      isPublished: Boolean(item.is_published),
      isWorking: Boolean(item.is_working),
      lifecycleState: item.lifecycle_state || 'history',
      lifecycleMeta: VERSION_STATE_META[item.lifecycle_state] || VERSION_STATE_META.history
    }
  })
}





export function buildRuleFields(detail) {
  const ruleDocument = readRuleDocumentMeta(detail)
  const ruleScenarioCategory = resolveRuleScenarioCategory(detail)
  return [
    { label: '规则编码', value: detail.code },
    {
      label: '明细载体',
      value: isSpreadsheetRuleSource(detail) ? 'Excel 表格' : 'Markdown / JSON'
    },
    ...(ruleDocument
      ? [
          {
            label: '关联文件',
            value: normalizeText(ruleDocument.file_name) || '未上传'
          }
        ]
      : []),
    {
      label: '模板键',
      value: normalizeText(detail.config_json?.rule_template_key) || '未指定'
    },
    { label: '业务域', value: resolveDomainLabel(detail.domain) },
    {
      label: '运行时类型',
      value: normalizeText(detail.config_json?.runtime_kind) || 'policy_rule_draft'
    },
    { label: '适用场景', value: ruleScenarioCategory || '通用' },
    { label: '线上版本', value: detail.published_version || '-' },
    { label: '工作版本', value: detail.working_version || detail.current_version || '-' }
  ]
}

export function buildMcpFields(detail, latestCall) {
  const content = detail.current_version_content || {}
  return [
    { label: '服务编码', value: detail.code },
    { label: '调用地址', value: normalizeText(detail.config_json?.endpoint) || '未配置' },
    { label: '鉴权方式', value: normalizeText(content.auth_mode) || '未配置' },
    {
      label: '最近调用',
      value: latestCall ? `${latestCall.toolCall.status} / ${formatDateTime(latestCall.run.started_at)}` : '暂无调用记录'
    }
  ]
}

export function buildFields(detail, typeKey, latestCall) {
  if (typeKey === 'rules') {
    return buildRuleFields(detail)
  }
  if (typeKey === 'mcp') {
    return buildMcpFields(detail, latestCall)
  }
  return []
}

export function buildPromptSections(detail, typeKey) {
  const content = detail.current_version_content || {}

  if (typeKey === 'mcp') {
    return [
      {
        title: '服务类型',
        intent: '协议说明',
        content: normalizeText(content.service_type) || '未配置服务类型。'
      },
      {
        title: '鉴权方式',
        intent: '安全要求',
        content: normalizeText(content.auth_mode) || '未配置鉴权方式。'
      },
      {
        title: '降级策略',
        intent: '失败处理',
        content: normalizeText(content.degrade_strategy) || '未配置降级策略。'
      }
    ]
  }

  return []
}

export function buildOutputRules(detail, typeKey) {
  const content = detail.current_version_content || {}

  if (typeKey === 'rules') {
    if (isSpreadsheetRuleSource(detail)) {
      return [
        '规则详情页以内联 Excel 表格作为主载体，管理员可直接编辑当前版本。',
        '上传新的 Excel 文件后，会自动生成新的规则版本快照。',
        '切换到历史版本时仅支持预览，不允许直接覆盖历史版本。',
        '规则表发生变更后，仍需完成审核才能再次正式上线。'
      ]
    }
    return [
      '规则使用固定模板落 Markdown，并配套维护 runtime_rule JSON。',
      '保存 Markdown 或 JSON 都会生成新版本快照。',
      '未审核通过的规则版本不能正式上线。',
      '版本切换当前只影响前端展示内容，不会直接回滚后端版本。'
    ]
  }

  if (typeKey === 'mcp') {
    return [
      `服务地址：${normalizeText(detail.config_json?.endpoint) || '未配置'}`,
      `鉴权方式：${normalizeText(content.auth_mode) || '未配置'}`,
      `降级策略：${normalizeText(content.degrade_strategy) || '未配置'}`
    ]
  }

  return []
}

export function buildTests(detail, typeKey, latestCall) {
  if (typeKey === 'rules') {
    const reviewMeta = resolveReviewMeta(detail.latest_review?.review_status)
    return [
      {
        name: '审核状态',
        input: detail.latest_review?.version || detail.current_version || '暂无版本',
        result: reviewMeta.label,
        tone: reviewMeta.tone
      },
      {
        name: '上线状态',
        input: detail.current_version || '暂无版本',
        result: resolveStatusMeta(detail.status).label,
        tone: resolveStatusMeta(detail.status).tone
      }
    ]
  }

  if (typeKey === 'mcp') {
    return [
      {
        name: '最近调用状态',
        input: latestCall?.run?.run_id || '暂无调用',
        result: latestCall?.toolCall?.status || '未记录',
        tone: latestCall?.toolCall?.status === 'failed' ? 'danger' : 'success'
      },
      {
        name: '最近调用耗时',
        input: latestCall?.toolCall?.tool_name || '暂无调用',
        result:
          typeof latestCall?.toolCall?.duration_ms === 'number'
            ? `${latestCall.toolCall.duration_ms} ms`
            : '未记录',
        tone: 'success'
      }
    ]
  }

  return []
}

export function buildTools(detail, typeKey, latestCall) {
  const content = detail.current_version_content || {}

  if (typeKey === 'mcp') {
    return [
      {
        name: normalizeText(content.service_type) || '未配置服务类型',
        scope: '服务类型',
        mode: 'MCP',
        tone: 'active'
      },
      {
        name: normalizeText(content.auth_mode) || '未配置鉴权方式',
        scope: '鉴权',
        mode: '安全',
        tone: 'safe'
      },
      {
        name: latestCall?.run?.run_id || '暂无调用记录',
        scope: '最近 Run',
        mode: latestCall?.toolCall?.status || '未执行',
        tone: latestCall?.toolCall?.status === 'failed' ? 'danger' : 'active'
      }
    ]
  }

  return []
}

export function buildPublishDescription(detail, typeKey) {
  if (typeKey === 'rules') {
    if (detail.published_version && detail.working_version && detail.published_version !== detail.working_version) {
      return '当前存在尚未上线的工作版本，系统运行仍以线上版本为准。'
    }
    if (detail.status === 'active') {
      return '当前规则线上版本已生效，仍可继续保存新的工作版本并重新走审核。'
    }
    return '当前规则需要先完成审核，再调用上线接口正式激活。'
  }

  return DETAIL_TITLES[typeKey]?.publishDesc || ''
}

export function buildDetailViewModel(detail, runs) {
  const typeKey = resolveTypeKey(detail.asset_type)
  const tabId = resolveTabId(detail, typeKey) || typeKey
  if (!typeKey || !tabId) {
    return null
  }
  const tabMeta = resolveTabMeta(tabId, typeKey)
  const latestCall = typeKey === 'mcp' ? findLatestMcpCall(runs, detail.code) : null
  const configJson = readConfigJson(detail)
  const statusMeta = resolveStatusMeta(detail.status)
  const reviewMeta = resolveReviewMeta(detail.latest_review?.review_status)
  const history = buildHistory(detail.recent_versions || [], detail)
  const previewVersion = history.find((item) => item.isWorking) || history[0] || null
  const usesSpreadsheetRule = typeKey === 'rules' && isSpreadsheetRuleSource(detail)
  const usesJsonRiskRule = typeKey === 'rules' && isJsonRiskRuleSource(detail)
  const ruleDocument = readRuleDocumentMeta(detail)
  const previewRawMarkdown =
    detail.current_version_content_type === 'markdown'
      ? String(previewVersion?.content ?? detail.current_version_content ?? '')
      : ''
  const previewRuntimeRule = resolveRuntimeRuleForVersion(
    detail,
    previewRawMarkdown,
    previewVersion?.runtimeRule || configJson.runtime_rule
  )
  const previewMarkdown = stripRuntimeRuleBlock(previewRawMarkdown)
  const titles = DETAIL_TITLES[typeKey]
  const previewChangeNote = previewVersion?.note || detail.current_version_change_note || '无版本说明'
  const ruleTemplateKey = normalizeText(configJson.rule_template_key || previewRuntimeRule.template_key)
  const ruleTemplateLabel = normalizeText(configJson.rule_template_label) || resolveRuleTemplateLabel(ruleTemplateKey)
  const runtimeKind = normalizeText(configJson.runtime_kind || previewRuntimeRule.kind) || 'policy_rule_draft'
  const ruleScenarioCategory = typeKey === 'rules' ? resolveRuleScenarioCategory(detail, tabId) : ''
  const ruleScenarioList = typeKey === 'rules' ? resolveRuleScenarioList(detail, tabId) : []
  const isEnabledValue = usesJsonRiskRule ? resolveRiskRuleEnabled(detail) : true
  const generationStatus = normalizeText(configJson.generation_status || detail.status)
  const riskRuleGenerationFailed = usesJsonRiskRule && (detail.status === 'failed' || generationStatus === 'failed')
  const riskRuleGenerationBusy = usesJsonRiskRule && (detail.status === 'generating' || generationStatus === 'generating')
  const riskRuleCreator =
    normalizeText(detail.owner) ||
    normalizeText(detail.recent_versions?.[0]?.created_by) ||
    '未知'
  const onlineMeta = resolveRiskRuleOnlineMeta(detail.status)
  const businessStage = usesJsonRiskRule
    ? resolveRiskRuleBusinessStage(detail)
    : { value: '', label: '' }

  const initialRiskRuleScore = resolveRiskRuleScore(configJson, configJson)
  const initialRiskRuleScoreLevel = resolveRiskRuleScoreLevel(configJson, configJson)
  const initialRiskRuleSeverity = initialRiskRuleScoreLevel || resolveRiskRuleSeverity(configJson)
  const detailName = detail.name
  const detailCode = detail.code
  const detailSummary = usesJsonRiskRule ? buildRiskListSubtitle(detail.description) : detail.description
  const detailOwner = detail.owner
  const detailReviewer = detail.reviewer || detail.latest_review?.reviewer || '待分配'
  const detailCategory = resolveDomainLabel(detail.domain)
  const detailScope = typeKey === 'rules' ? ruleScenarioCategory || '通用' : formatScenarioList(detail.scenario_json)
  const detailEnabledValue = isEnabledValue
  const detailEnabledLabel = isEnabledValue ? '是' : '否'
  const detailEnabledTone = isEnabledValue ? 'success' : 'disabled'

  return {
    id: detail.id,
    tabId,
    type: typeKey,
    typeLabel: tabMeta.typeLabel,
    short: makeShort(detailName),
    name: detailName,
    code: detailCode,
    rawCode: detail.code,
    summary: detailSummary,
    listSubtitle: normalizeText(detailSummary),
    owner: detailOwner,
    reviewer: detailReviewer,
    category: detailCategory,
    scope: detailScope,
    businessStageValue: businessStage.value,
    businessStageLabel: businessStage.label,
    version: detail.working_version || detail.current_version || '-',
    currentVersion: detail.current_version || '-',
    publishedVersion: detail.published_version || '-',
    workingVersion: detail.working_version || detail.current_version || '-',
    displayVersion: previewVersion?.version || detail.working_version || detail.current_version || '-',
    status: statusMeta.label,
    statusValue: detail.status,
    statusTone: statusMeta.tone,
    hitRate: buildRowMetric(detail, typeKey),
    createdAt: detail.created_at,
    updatedAt: formatDateTime(detail.updated_at),
    badgeTone: tabMeta.badgeTone,
    configJson,
    usesSpreadsheetRule,
    usesJsonRiskRule,
    riskRuleJsonText: '{}',
    riskRuleSummary: null,
    riskRuleDescription: '',
    riskRuleBusinessDescription: '',
    riskRuleSubtitle: usesJsonRiskRule ? buildRiskListSubtitle(detail.description) : '',
    riskRuleSourceRef: '',
    riskRuleSeverity: initialRiskRuleSeverity,
    riskRuleScore: initialRiskRuleScore,
    riskRuleScoreLevel: initialRiskRuleScoreLevel || initialRiskRuleSeverity,
    riskRuleScoreDetail: resolveRiskRuleScoreDetail(configJson, configJson),
    riskRuleSeverityLabel: initialRiskRuleScoreLevel
      ? resolveRiskRuleScoreLabel(configJson, configJson)
      : resolveRiskRuleSeverityLabel(configJson),
    riskRuleScoreLabel: resolveRiskRuleScoreLabel(configJson, configJson),
    riskRuleCreatedAt: formatDateTime(detail.created_at),
    riskRuleAgeLabel: formatRiskRuleAge(detail.created_at),
    isOnlineValue: onlineMeta.online,
    isOnlineLabel: onlineMeta.label,
    isOnlineTone: onlineMeta.tone,
    isEnabledValue: detailEnabledValue,
    isEnabledLabel: detailEnabledLabel,
    isEnabledTone: detailEnabledTone,
    publisher:
      detail.status === 'active'
        ? normalizeText(detail.published_by) ||
          detail.latest_review?.reviewer ||
          detail.reviewer ||
          (detail.recent_versions && detail.recent_versions[0]?.created_by) ||
          '系统管理员'
        : riskRuleCreator,
    creator: riskRuleCreator,
    publishedAt:
      history.find((item) => item.isPublished || item.lifecycleState === 'published')?.time ||
      (detail.published_at ? formatDateTime(detail.published_at) : '') ||
      (detail.latest_review?.reviewed_at ? formatDateTime(detail.latest_review.reviewed_at) : '-'),
    lastOperationLabel: resolveLastOperationLabel(detail, {
      actor: riskRuleCreator,
      at: detail.created_at
    }),
    lastOperationTone: onlineMeta.tone,
    riskRuleFields: [],
    riskRuleFieldSummary: '未识别字段',
    riskRuleFlow: resolveRiskRuleFlow({}, []),
    riskRuleFlowDiagramSvg: normalizeText(configJson.flow_diagram_svg),
    riskRuleRequiresAttachment: Boolean(configJson.requires_attachment),
    riskRuleGenerationStatus: generationStatus,
    riskRuleGenerationFailed,
    riskRuleGenerationBusy,
    riskRuleGenerationError: normalizeText(configJson.generation_error),
    latestTestSummary: detail.latest_test_summary || detail.latestTestSummary || null,
    riskCategory: typeKey === 'rules' ? ruleScenarioCategory : '',
    ruleDocument,
    scenarioList: typeKey === 'rules' && ruleScenarioList.length
      ? ruleScenarioList
      : Array.isArray(detail.scenario_json)
        ? [...detail.scenario_json]
        : [],
    markdownContent: previewMarkdown,
    runtimeRuleText: stringifyRuntimeRule(previewRuntimeRule),
    ruleTemplateKey,
    ruleTemplateLabel,
    runtimeKind,
    currentVersionContentType: detail.current_version_content_type,
    currentVersionChangeNote: detail.current_version_change_note || '无版本说明',
    displayVersionChangeNote: previewChangeNote,
    reviewStatusLabel: reviewMeta.label,
    reviewStatusTone: reviewMeta.tone,
    reviewStatusValue: detail.latest_review?.review_status || '',
    reviewTimeLabel: formatDateTime(detail.latest_review?.reviewed_at),
    reviewNote: detail.latest_review?.review_note || '',
    latestCall,
    fields: buildFields(detail, typeKey, latestCall),
    promptSections:
      typeKey === 'rules' ? [] : buildPromptSections(detail, typeKey),
    outputRules: buildOutputRules(detail, typeKey),
    tests: buildTests(detail, typeKey, latestCall),
    triggers:
      typeKey === 'rules'
        ? [ruleScenarioCategory || '通用']
        : detail.scenario_json?.length
          ? detail.scenario_json.map((item) => SCENARIO_LABELS[item] || item)
          : ['未配置场景'],
    tools:
      typeKey === 'rules'
        ? [
            {
              name: detail.latest_review?.reviewer || '待分配审核人',
              scope: '审核负责人',
              mode: reviewMeta.label,
              tone: reviewMeta.tone
            },
            {
              name: detail.published_version || '暂无版本',
              scope: '线上版本',
              mode: '正式生效',
              tone: 'safe'
            },
            {
              name: detail.working_version || detail.current_version || '暂无版本',
              scope: '工作版本',
              mode: detail.current_version_change_note || '无版本说明',
              tone: 'safe'
            }
          ]
        : buildTools(detail, typeKey, latestCall),
    history,
    configTitle: titles.configTitle,
    configDesc: titles.configDesc,
    detailTitle: titles.detailTitle,
    detailDesc: titles.detailDesc,
    outputTitle: titles.outputTitle,
    outputDesc: titles.outputDesc,
    ruleListTitle: titles.ruleListTitle,
    checkListTitle: titles.checkListTitle,
    triggerTitle: titles.triggerTitle,
    triggerDesc: titles.triggerDesc,
    toolTitle: titles.toolTitle,
    toolDesc: titles.toolDesc,
    historyTitle: titles.historyTitle,
    historyDesc: titles.historyDesc,
    publishTitle: titles.publishTitle,
    publishDesc: buildPublishDescription(detail, typeKey),
    publishMeta:
      typeKey === 'rules'
        ? `最近保存：${formatDateTime(detail.updated_at)}`
        : `最近更新：${formatDateTime(detail.updated_at)}`,
    publishState: statusMeta.label,
    latestReviewVersion: detail.latest_review?.version || detail.current_version || '-',
    loading: false
  }
}
