export const k8sStatefulSetSchema = {
  id: 'k8s-statefulset',
  name: 'K8s StatefulSet',
  icon: 'Box',
  category: 'K8S 工作负载',
  description: 'Kubernetes 有状态应用部署控制器，支持稳定网络标识和持久存储',
  format: 'yaml',
  fileName: 'statefulset.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'StatefulSet 名称',
          type: 'text',
          placeholder: 'my-statefulset',
          default: 'my-statefulset',
          required: true,
        },
        {
          key: 'namespace',
          label: '命名空间',
          type: 'text',
          placeholder: 'default',
          default: 'default',
        },
        {
          key: 'appName',
          label: '应用名称',
          type: 'text',
          placeholder: 'my-app',
          default: 'my-app',
          required: true,
          tip: '用作 selector 和 label 的 app 值',
        },
        {
          key: 'image',
          label: '容器镜像',
          type: 'text',
          placeholder: 'nginx:1.24',
          default: 'nginx:1.24',
          required: true,
        },
        {
          key: 'replicas',
          label: '副本数',
          type: 'number',
          min: 1,
          max: 100,
          default: 3,
        },
      ],
    },
    {
      title: '网络与服务',
      fields: [
        {
          key: 'containerPort',
          label: '容器端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
        },
        {
          key: 'serviceName',
          label: 'Headless Service 名称',
          type: 'text',
          placeholder: 'my-service',
          default: 'my-service',
          required: true,
          tip: '必须已存在的 Headless Service',
        },
      ],
    },
    {
      title: '持久存储',
      fields: [
        {
          key: 'volumeClaimEnabled',
          label: '启用 PVC',
          type: 'switch',
          default: true,
          tip: '为每个 Pod 创建独立的 PersistentVolumeClaim',
        },
        {
          key: 'storageClassName',
          label: 'StorageClass',
          type: 'text',
          placeholder: 'standard',
          default: 'standard',
          dependsOn: { key: 'volumeClaimEnabled', value: true },
        },
        {
          key: 'storageSize',
          label: '存储大小',
          type: 'text',
          placeholder: '10Gi',
          default: '10Gi',
          dependsOn: { key: 'volumeClaimEnabled', value: true },
        },
        {
          key: 'pvcAccessMode',
          label: '访问模式',
          type: 'select',
          options: [
            { label: 'ReadWriteOnce', value: 'ReadWriteOnce' },
            { label: 'ReadWriteMany', value: 'ReadWriteMany' },
            { label: 'ReadOnlyMany', value: 'ReadOnlyMany' },
          ],
          default: 'ReadWriteOnce',
          dependsOn: { key: 'volumeClaimEnabled', value: true },
        },
      ],
    },
    {
      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' },
            { label: '2', value: '2' },
          ],
          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' },
            { label: '4', value: '4' },
          ],
          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' },
            { label: '1Gi', value: '1Gi' },
          ],
          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' },
            { label: '2Gi', value: '2Gi' },
          ],
          default: '256Mi',
        },
      ],
    },
    {
      title: '更新策略',
      fields: [
        {
          key: 'updateStrategy',
          label: '更新策略',
          type: 'select',
          options: [
            { label: 'RollingUpdate - 滚动更新 (推荐)', value: 'RollingUpdate' },
            { label: 'OnDelete - 手动删除触发', value: 'OnDelete' },
          ],
          default: 'RollingUpdate',
        },
        {
          key: 'partition',
          label: 'Partition',
          type: 'number',
          min: 0,
          max: 100,
          default: 0,
          tip: '仅更新序号 >= partition 的 Pod',
          dependsOn: { key: 'updateStrategy', value: '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 generateK8sStatefulSetYaml(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 volumeMounts = []
  const volumeClaimTemplates = []

  if (config.volumeClaimEnabled) {
    volumeMounts.push({ name: 'data', mountPath: '/data' })
    volumeClaimTemplates.push({
      metadata: { name: 'data' },
      spec: {
        accessModes: [config.pvcAccessMode],
        storageClassName: config.storageClassName,
        resources: { requests: { storage: config.storageSize } },
      },
    })
  }

  if (volumeMounts.length > 0) {
    container.volumeMounts = volumeMounts
  }

  const statefulset = {
    apiVersion: 'apps/v1',
    kind: 'StatefulSet',
    metadata: {
      name: config.name,
      namespace: config.namespace,
      labels,
    },
    spec: {
      replicas: config.replicas,
      serviceName: config.serviceName,
      selector: { matchLabels: { app: config.appName } },
      updateStrategy: config.updateStrategy === 'RollingUpdate'
        ? { type: 'RollingUpdate', rollingUpdate: { partition: config.partition } }
        : { type: 'OnDelete' },
      template: {
        metadata: { labels },
        spec: { containers: [container] },
      },
    },
  }

  if (volumeClaimTemplates.length > 0) {
    statefulset.spec.volumeClaimTemplates = volumeClaimTemplates
  }

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

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