export type ServerSelectionEntry = { id: number | string } | number | string

function coerceServerId(value: unknown): number | null {
  if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
    return Math.trunc(value)
  }
  if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
    const n = Number(value.trim())
    return Number.isFinite(n) && n > 0 ? n : null
  }
  return null
}

/** Normalize v-data-table selection (Vuetify 4 modelValue: IDs, strings, or row objects). */
export function normalizeServerIds(selected: ServerSelectionEntry[]): number[] {
  const ids: number[] = []
  for (const item of selected) {
    const raw = typeof item === 'object' && item !== null && 'id' in item ? item.id : item
    const id = coerceServerId(raw)
    if (id !== null) ids.push(id)
  }
  return [...new Set(ids)]
}

export interface BatchAgentResultItem {
  server_id: number
  server_name: string
  success: boolean
  stdout?: string
  error?: string
  message?: string
}

export interface ServerNameSource {
  id: number
  name?: string | null
  domain?: string | null
}

/** Same label order as backend _batch_server_display_name. */
export function serverDisplayLabel(source: ServerNameSource | null | undefined): string {
  if (!source) return '未知服务器'
  const name = (source.name || '').trim()
  if (name) return name
  const domain = (source.domain || '').trim()
  if (domain) return domain
  return '未知服务器'
}

export function buildServerNameLookup(sources: ServerNameSource[]): Map<number, string> {
  const map = new Map<number, string>()
  for (const s of sources) {
    if (!s?.id) continue
    map.set(s.id, serverDisplayLabel(s))
  }
  return map
}

/** Fill missing API server_name from the list the user selected (table only stores IDs). */
export function enrichBatchAgentResults(
  results: BatchAgentResultItem[],
  lookup: Map<number, string>,
): BatchAgentResultItem[] {
  return results.map((row) => {
    const raw = row as BatchAgentResultItem & { serverName?: string }
    const fromApi = (raw.server_name || raw.serverName || '').trim()
    const fromList = lookup.get(row.server_id)?.trim()
    return {
      ...row,
      server_name: fromApi || fromList || '未知服务器',
    }
  })
}

export function countBatchSuccess(results: BatchAgentResultItem[] | undefined): number {
  return (results || []).filter(r => r.success).length
}
