export const k8sDaemonSetSchema = {
  id: 'k8s-daemonset',
  name: 'K8s DaemonSet',
  icon: 'Box',
  category: 'K8S 工作负载',
  description: 'Kubernetes 守护进程集 — 在每个节点上运行一个 Pod 副本',
  format: 'yaml',
  fileName: 'daemonset.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'DaemonSet 名称',
          type: 'text',
          placeholder: 'my-daemonset',
          default: 'my-daemonset',
          required: true,
        },
        {
          key: 'namespace',
          label: '命名空间',
          type: 'text',
          placeholder: 'default',
          default: 'default',
        },
        {
          key: 'appName',
          label: '应用名称',
          type: 'text',
          placeholder: 'my-app',
          default: 'my-app',
          required: true,
        },
        {
          key: 'image',
          label: '容器镜像',
          type: 'text',
          placeholder: 'fluentd:latest',
          default: 'fluentd:latest',
          required: true,
        },
        {
          key: 'containerPort',
          label: '容器端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 8080,
        },
      ],
    },
    {
      title: '资源限制',
      fields: [
        {
          key: 'cpuRequest',
          label: 'CPU Requests',
          type: 'select',
          options: [
            { label: '50m', value: '50m' },
            { label: '100m', value: '100m' },
            { label: '200m', value: '200m' },
            { label: '500m', value: '500m' },
            { label: '1', value: '1' },
          ],
          default: '100m',
        },
        {
          key: 'cpuLimit',
          label: 'CPU Limits',
          type: 'select',
          options: [
            { label: '200m', value: '200m' },
            { label: '500m', value: '500m' },
            { label: '1', value: '1' },
            { label: '2', value: '2' },
          ],
          default: '500m',
        },
        {
          key: 'memoryRequest',
          label: 'Memory Requests',
          type: 'select',
          options: [
            { label: '64Mi', value: '64Mi' },
            { label: '128Mi', value: '128Mi' },
            { label: '256Mi', value: '256Mi' },
            { label: '512Mi', value: '512Mi' },
          ],
          default: '128Mi',
        },
        {
          key: 'memoryLimit',
          label: 'Memory Limits',
          type: 'select',
          options: [
            { label: '128Mi', value: '128Mi' },
            { label: '256Mi', value: '256Mi' },
            { label: '512Mi', value: '512Mi' },
            { label: '1Gi', value: '1Gi' },
          ],
          default: '256Mi',
        },
      ],
    },
    {
      title: '节点调度',
      fields: [
        {
          key: 'hostNetwork',
          label: '使用主机网络',
          type: 'switch',
          default: false,
          tip: 'Pod 将使用宿主机网络命名空间',
        },
        {
          key: 'tolerationsEnabled',
          label: '添加 Toleration',
          type: 'switch',
          default: false,
          tip: '允许在有污点的节点上运行',
        },
        {
          key: 'tolerationKey',
          label: 'Toleration Key',
          type: 'text',
          placeholder: 'node-role.kubernetes.io/master',
          default: '',
          dependsOn: { key: 'tolerationsEnabled', value: true },
        },
        {
          key: 'tolerationValue',
          label: 'Toleration Value',
          type: 'text',
          placeholder: '',
          default: '',
          dependsOn: { key: 'tolerationsEnabled', value: true },
        },
      ],
    },
    {
      title: '更新策略',
      fields: [
        {
          key: 'updateStrategy',
          label: '更新策略',
          type: 'select',
          options: [
            { label: 'RollingUpdate - 滚动更新 (推荐)', value: 'RollingUpdate' },
            { label: 'OnDelete - 手动删除触发', value: 'OnDelete' },
          ],
          default: 'RollingUpdate',
        },
      ],
    },
  ],
}

function toYaml(obj, indent = 0) {
  const lines = []
  const prefix = '  '.repeat(indent)

  for (const [key, value] of Object.entries(obj)) {
    if (value === null || value === undefined || value === '') continue

    if (Array.isArray(value)) {
      lines.push(`${prefix}${key}:`)
      for (const item of value) {
        if (typeof item === 'object' && item !== null) {
          const entries = Object.entries(item).filter(([, v]) => v !== null && v !== undefined && v !== '')
          if (entries.length === 0) continue
          const first = entries[0]
          lines.push(`${prefix}  - ${first[0]}: ${first[1]}`)
          for (let i = 1; i < entries.length; i++) {
            lines.push(`${prefix}    ${entries[i][0]}: ${entries[i][1]}`)
          }
        } else {
          lines.push(`${prefix}  - ${item}`)
        }
      }
    } else if (typeof value === 'object') {
      lines.push(`${prefix}${key}:`)
      lines.push(toYaml(value, indent + 1))
    } else {
      lines.push(`${prefix}${key}: ${value}`)
    }
  }

  return lines.join('\n')
}

export function generateK8sDaemonSetYaml(config) {
  const labels = { app: config.appName }

  const container = {
    name: config.appName,
    image: config.image,
    ports: [{ containerPort: config.containerPort, name: 'http' }],
    resources: {
      requests: { cpu: config.cpuRequest, memory: config.memoryRequest },
      limits: { cpu: config.cpuLimit, memory: config.memoryLimit },
    },
  }

  const podSpec = {
    containers: [container],
  }

  if (config.hostNetwork) {
    podSpec.hostNetwork = true
  }

  if (config.tolerationsEnabled && config.tolerationKey) {
    const toleration = { key: config.tolerationKey, operator: 'Exists', effect: 'NoSchedule' }
    if (config.tolerationValue) {
      toleration.operator = 'Equal'
      toleration.value = config.tolerationValue
    }
    podSpec.tolerations = [toleration]
  }

  const daemonset = {
    apiVersion: 'apps/v1',
    kind: 'DaemonSet',
    metadata: {
      name: config.name,
      namespace: config.namespace,
      labels,
    },
    spec: {
      selector: { matchLabels: { app: config.appName } },
      updateStrategy: config.updateStrategy === 'RollingUpdate'
        ? { type: 'RollingUpdate', rollingUpdate: { maxUnavailable: 1 } }
        : { type: 'OnDelete' },
      template: {
        metadata: { labels },
        spec: podSpec,
      },
    },
  }

  const header = `# K8s DaemonSet - 由 ConfTemplate 生成\n# 生成时间: ${new Date().toLocaleString('zh-CN')}\n# 部署命令: kubectl apply -f ${config.fileName || 'daemonset.yaml'}\n`

  return header + '\n' + toYaml(daemonset)
}
