import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { fileURLToPath } from 'node:url'

import { buildAuditDetailTopBar } from '../src/views/scripts/auditViewDetailTopBar.js'

function readSource(path) {
  return readFileSync(fileURLToPath(new URL(path, import.meta.url)), 'utf8')
}

const flowDiagram = readSource('../src/components/shared/RiskRuleFlowDiagram.vue')
const testDialog = readSource('../src/components/shared/RiskRuleTestDialog.vue')
const testDialogDisplay = readSource('../src/components/shared/riskRuleTestDialogDisplay.js')
const auditView = readSource('../src/views/AuditView.vue')
const auditRuleDialogs = readSource('../src/components/audit/AuditRuleDialogs.vue')

test('risk rule detail topbar exposes score, level, status, online and enabled kpis', () => {
  const payload = buildAuditDetailTopBar({
    usesJsonRiskRule: true,
    skill: {
      name: '差旅票据城市一致性校验',
      riskRuleSubtitle: '校验票据城市和申报目的地是否一致。',
      riskRuleScore: 72,
      riskRuleScoreLabel: '高风险',
      riskRuleScoreLevel: 'high',
      riskRuleSeverityLabel: '高风险',
      status: '已上线',
      statusTone: 'success',
      displayVersion: 'v0.1.0',
      isOnlineLabel: '已上线',
      isOnlineTone: 'success',
      isOnlineValue: true,
      publishedAt: '2026-05-30 10:00',
      isEnabledLabel: '是',
      isEnabledTone: 'success',
      isEnabledValue: true
    }
  })

  assert.equal(payload.view.title, '差旅票据城市一致性校验')
  assert.deepEqual(
    payload.kpis.map((item) => item.label),
    ['风险分', '风险等级', '规则状态', '上线状态', '启用状态']
  )
  assert.equal(payload.kpis[0].value, '72')
  assert.equal(payload.kpis[3].value, '已上线')
  assert.equal(payload.kpis[4].meta, '参与扫描')
})

test('risk rule flow detail keeps left explanation and right static diagram titles', () => {
  assert.match(flowDiagram, /class="risk-rule-flow-explainer"[\s\S]*<strong>流程解释<\/strong>/)
  assert.match(flowDiagram, /class="risk-rule-flow-visual"[\s\S]*<strong>流程图<\/strong>/)
  assert.match(flowDiagram, /grid-template-columns:\s*minmax\(260px,\s*0\.78fr\)\s*minmax\(0,\s*1\.22fr\)/)
  assert.match(flowDiagram, /class="risk-rule-section-title risk-rule-flow-visual-title"/)
  assert.doesNotMatch(flowDiagram, /<button[\s\S]*zoom/i)
})

test('risk rule test dialog shows field pipeline and revision actions are wired', () => {
  assert.match(testDialogDisplay, /title:\s*'OCR 原始字段'/)
  assert.match(testDialogDisplay, /title:\s*'Hermes 规范化字段'/)
  assert.match(testDialogDisplay, /title:\s*'执行器实际输入'/)
  assert.match(testDialog, /正在调用规则执行器识别风险/)
  assert.match(auditView, /<span>创建修订版本<\/span>/)
  assert.match(auditRuleDialogs, /riskRuleEditMode === 'revision' \? '创建修订版本' : '编辑风险规则'/)
  assert.match(auditRuleDialogs, /<span>修订原因<\/span>/)
})
