import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import path from 'node:path'

const scriptDir = path.dirname(fileURLToPath(import.meta.url))
const sourceRoot = path.resolve(scriptDir, '../src')
const evalViewDir = path.join(sourceRoot, 'views/eval')

const [
  createSource,
  taskStepSource,
  ruleStepSource,
  listSource,
  routerSource,
  apiSource,
] = await Promise.all([
  readFile(path.join(evalViewDir, 'EvalCreateView.vue'), 'utf8'),
  readFile(path.join(evalViewDir, 'create/EvalTaskSetupStep.vue'), 'utf8'),
  readFile(path.join(evalViewDir, 'create/EvalRuleSetupStep.vue'), 'utf8'),
  readFile(path.join(evalViewDir, 'EvalView.vue'), 'utf8'),
  readFile(path.join(sourceRoot, 'router/index.ts'), 'utf8'),
  readFile(path.join(sourceRoot, 'api/modules/eval.ts'), 'utf8'),
])

function extractRouteBlock(source, routePath) {
  const pathPattern = new RegExp(`path:\\s*['"]${routePath.replaceAll('/', '\\/')}['"]`)
  const pathIndex = source.search(pathPattern)
  assert.notEqual(pathIndex, -1, `未找到路由 ${routePath}`)

  const openBrace = source.lastIndexOf('{', pathIndex)
  assert.notEqual(openBrace, -1, `路由 ${routePath} 缺少左花括号`)

  let depth = 0
  for (let index = openBrace; index < source.length; index += 1) {
    if (source[index] === '{') depth += 1
    if (source[index] === '}') depth -= 1
    if (depth === 0) return source.slice(openBrace + 1, index)
  }

  assert.fail(`路由 ${routePath} 缺少右花括号`)
}

const createDimensionRoute = extractRouteBlock(routerSource, 'model-eval/dimension/create')
assert.match(
  createDimensionRoute,
  /redirect:\s*['"]\/model-eval\/create['"]/,
  '独立创建维度入口必须收敛到新建评测向导',
)
assert.doesNotMatch(
  createDimensionRoute,
  /DimensionCreateView/,
  '独立创建维度路由不应继续加载旧创建页',
)

const editDimensionRoute = extractRouteBlock(routerSource, 'model-eval/dimension/:id/edit')
assert.match(
  editDimensionRoute,
  /DimensionCreateView\.vue/,
  '编辑维度路由必须继续复用 DimensionCreateView.vue',
)

const dimensionTabStart = listSource.indexOf('<!-- 评测维度 -->')
assert.notEqual(dimensionTabStart, -1, '评测列表缺少维度标签页')
const dimensionTabSource = listSource.slice(dimensionTabStart)
assert.doesNotMatch(dimensionTabSource, /create-text=["']添加维度["']/, '维度标签页不应保留“添加维度”按钮')
assert.doesNotMatch(dimensionTabSource, /@create=["']handleCreateClick["']/, '维度标签页不应保留独立创建事件')

assert.match(
  apiSource,
  /createDimension\s*=\s*\([^)]*\)\s*=>\s*[\s\S]*?post<\{\s*id:\s*string\s*\|\s*number\s*\}>\(['"]\/dimension['"]\s*,\s*data\)/,
  'createDimension 必须声明返回包含 string | number 类型 id',
)

assert.match(createSource, /EvalTaskSetupStep/, '向导缺少任务配置子组件')
assert.match(createSource, /EvalRuleSetupStep/, '向导缺少评测规则子组件')
assert.match(
  createSource,
  /任务配置[\s\S]*?评测规则/,
  '评测创建向导必须按“任务配置、评测规则”定义两个步骤',
)
assert.match(createSource, /currentStep\s*=\s*ref\(0\)/, '评测创建向导缺少当前步骤状态')
assert.match(createSource, /class=["']custom-wizard-steps["']/, '评测向导未复用数据处理的自定义步骤条结构')
assert.match(createSource, /class=["']step-connector["']/, '评测向导步骤条缺少连接线')
assert.match(createSource, /:aria-current=/, '步骤条缺少当前步骤的可访问性绑定')
assert.match(createSource, /currentStep === index \? 'step' : undefined/, '步骤条当前步骤语义不正确')
assert.doesNotMatch(createSource, /<el-steps\b|<el-step\b/, '评测向导不应继续使用 Element Plus 默认步骤条')
assert.match(
  createSource,
  /<EvalTaskSetupStep[\s\S]*?v-if=["'][^"']*currentStep[^"']*0[^"']*["']/,
  '任务配置子组件没有绑定第一步',
)
assert.match(
  createSource,
  /<EvalRuleSetupStep[\s\S]*?v-else/,
  '评测规则子组件没有绑定第二步',
)

assert.match(taskStepSource, /prop=["']dataset_id["']/, '数据集字段缺少表单校验标识')
assert.match(
  `${createSource}\n${taskStepSource}`,
  /data_source[\s\S]*?dataset[\s\S]*?dataset_id/,
  '选择评测数据集时必须校验 dataset_id',
)

assert.match(createSource, /['"]baseline['"]/, '向导缺少基线评测分支')
assert.match(
  `${createSource}\n${ruleStepSource}`,
  /已有维度|existing/,
  '评测规则步骤缺少使用已有维度的分支',
)
assert.match(
  `${createSource}\n${ruleStepSource}`,
  /新建(?:评测)?(?:维度|规则)|create/,
  '评测规则步骤缺少新建维度的分支',
)

assert.match(
  createSource,
  /await\s+createDimension\([\s\S]*?await\s+startEval\(/,
  '最终提交必须先创建新维度，再使用维度 id 启动评测',
)
assert.match(
  createSource,
  /createdDimension(?:\.value)?\.id|createdDimensionId|dimensionResult\.id/,
  '启动评测前必须读取新建维度返回的 id',
)
assert.match(
  createSource,
  /eval_type[\s\S]*?baseline[\s\S]*?(?:dimension_id|createDimension)/,
  '基线评测必须有明确的不创建自定义维度分支',
)
assert.match(
  createSource,
  /ruleMode[\s\S]*?['"]existing['"]/,
  '已有维度模式必须有独立的提交分支',
)

assert.match(createSource, /:loading=["']submitting["']/, '最终提交按钮缺少 loading 状态')
assert.match(createSource, /:disabled=["'][^"']*submitting/, '提交期间必须禁用重复操作')
assert.match(createSource, /class=["'][^"']*wizard-footer/, '评测向导缺少统一底部操作栏')
assert.match(
  createSource,
  /\.wizard-footer\s*\{[\s\S]*?display:\s*flex[\s\S]*?justify-content:\s*flex-end/,
  '底部操作栏必须保持企业表单常用的右对齐布局',
)

console.log('评测创建向导回归检查通过')
