import {
  buildDigitalEmployeeDetailMeta,
  buildDigitalEmployeeListMeta
} from './auditViewDigitalEmployeeModel.js'
import {
  formatDateTime,
  normalizeText,
  resolveStatusMeta
} from './auditViewModel.js'

export const DIGITAL_EMPLOYEE_EXECUTION_MODE_OPTIONS = [
  { value: '', label: '全部执行方式' },
  { value: 'timed', label: '定时执行' },
  { value: 'manual', label: '手动触发' }
]

export function resolveDigitalEmployeeStatusColor(statusValue) {
  const normalized = normalizeText(statusValue).toLowerCase()
  if (normalized === 'active') return 'var(--success)'
  if (['failed', 'error'].includes(normalized)) return '#ef4444'
  if (['disabled', 'inactive'].includes(normalized)) return '#f59e0b'
  return 'var(--theme-primary)'
}

export function buildDigitalEmployeeDetailTopBar(employee) {
  if (!employee) return null

  const meta = employee.digitalEmployee || {}
  const statusValue = normalizeText(employee.statusValue).toLowerCase()

  return {
    view: {
      title: normalizeText(employee.name) || '数字员工详情',
      desc:
        normalizeText(meta.description) ||
        normalizeText(employee.summary) ||
        '查看数字员工配置、执行计划、运行记录与源文件。'
    },
    kpis: [
      {
        label: '运行状态',
        value: normalizeText(employee.status) || (statusValue === 'active' ? '运行中' : '未运行'),
        unit: '',
        meta:
          normalizeText(meta.scheduleLabel) ||
          normalizeText(employee.scope) ||
          normalizeText(employee.executionMode) ||
          '待配置执行计划',
        trend: statusValue === 'active' ? 'up' : 'down',
        color: resolveDigitalEmployeeStatusColor(statusValue)
      }
    ]
  }
}

export function buildEmployeeListItem(asset) {
  const meta = buildDigitalEmployeeListMeta(asset)
  const statusMeta = resolveStatusMeta(asset.status)
  const displayName = meta.name || '数字员工技能'
  const executionModeValue = meta.executionMode === '定时执行' ? 'timed' : 'manual'
  const searchText = [
    displayName,
    meta.code,
    meta.summary,
    meta.owner,
    meta.scope,
    meta.executionMode,
    meta.skillCategory,
    statusMeta.label,
    meta.enabledLabel
  ]
    .map((value) => normalizeText(value).toLowerCase())
    .filter(Boolean)
    .join(' ')

  return {
    id: asset.id,
    rawCode: asset.code,
    short: displayName.slice(0, 2),
    badgeTone: 'blue',
    name: displayName,
    code: meta.code,
    summary: meta.summary,
    owner: meta.owner,
    scope: meta.scope,
    executionMode: meta.executionMode,
    executionModeValue,
    skillCategory: meta.skillCategory,
    version: asset.working_version || asset.current_version || '-',
    currentVersion: asset.current_version || '-',
    status: statusMeta.label,
    statusValue: asset.status,
    statusTone: statusMeta.tone,
    enabledLabel: meta.enabledLabel,
    enabledTone: meta.enabledTone,
    isEnabledValue: meta.enabled,
    configJson: asset.config_json || {},
    updatedAt: formatDateTime(asset.updated_at),
    updatedAtRaw: asset.updated_at || '',
    digitalEmployee: meta,
    searchText
  }
}

export function buildEmployeePlaceholder(employee) {
  return {
    ...employee,
    type: 'digitalEmployees',
    typeLabel: '数字员工',
    currentVersion: employee.currentVersion || employee.version || '-',
    workingVersion: employee.version || '-',
    markdownContent: '',
    loading: true
  }
}

export function buildEmployeeDetail(asset) {
  const meta = buildDigitalEmployeeDetailMeta({
    ...asset,
    updated_at: formatDateTime(asset.updated_at)
  })
  const statusMeta = resolveStatusMeta(asset.status)

  return {
    id: asset.id,
    type: 'digitalEmployees',
    typeLabel: '数字员工',
    rawCode: asset.code,
    short: meta.name.slice(0, 2),
    name: meta.name,
    code: meta.code,
    summary: meta.description,
    owner: meta.owner,
    reviewer: meta.reviewer,
    category: meta.category,
    scope: meta.scope,
    version: asset.working_version || asset.current_version || '-',
    currentVersion: asset.current_version || '-',
    workingVersion: asset.working_version || asset.current_version || '-',
    status: statusMeta.label,
    statusValue: asset.status,
    statusTone: statusMeta.tone,
    configJson: asset.config_json || {},
    updatedAt: formatDateTime(asset.updated_at),
    markdownContent: meta.sourceMarkdown,
    digitalEmployee: meta,
    loading: false
  }
}

export function sortEmployees(items) {
  return [...items].sort((left, right) =>
    String(right.updatedAtRaw || '').localeCompare(String(left.updatedAtRaw || ''))
  )
}

export function filterDigitalEmployees(items = [], filters = {}) {
  const searchText = normalizeText(filters.keyword).toLowerCase()
  const hasKeyword = Boolean(searchText)
  const hasStatus = Boolean(filters.selectedStatus)
  const selectedSkillCategory = normalizeText(filters.selectedSkillCategory)
  const hasSkillCategory = Boolean(selectedSkillCategory)
  const hasEnabled = Boolean(filters.selectedEnabledState)
  const hasExecutionMode = Boolean(filters.selectedExecutionMode)

  return items.filter((item) => {
    if (hasKeyword && !normalizeText(item.searchText).includes(searchText)) {
      return false
    }
    if (hasStatus && item.statusValue !== filters.selectedStatus) {
      return false
    }
    if (hasSkillCategory && normalizeText(item.skillCategory) !== selectedSkillCategory) {
      return false
    }
    if (hasEnabled && (filters.selectedEnabledState === 'enabled') !== Boolean(item.isEnabledValue)) {
      return false
    }
    if (hasExecutionMode && item.executionModeValue !== filters.selectedExecutionMode) {
      return false
    }

    return true
  })
}
