export const k8sPodSchema = {
  id: 'k8s-pod',
  name: 'K8s Pod',
  icon: 'Box',
  category: 'K8S 工作负载',
  description: 'Kubernetes Pod — 最小可部署单元',
  format: 'yaml',
  fileName: 'pod.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'Pod 名称',
          type: 'text',
          placeholder: 'my-pod',
          default: 'my-pod',
          required: true,
        },
        {
          key: 'namespace',
          label: '命名空间',
          type: 'text',
          placeholder: 'default',
          default: 'default',
        },
        {
          key: 'containerName',
          label: '容器名称',
          type: 'text',
          placeholder: 'main',
          default: 'main',
          required: true,
        },
        {
          key: 'image',
          label: '容器镜像',
          type: 'text',
          placeholder: 'nginx:1.24',
          default: 'nginx:1.24',
          required: true,
        },
        {
          key: 'imagePullPolicy',
          label: '镜像拉取策略',
          type: 'select',
          options: [
            { label: 'IfNotPresent (推荐)', value: 'IfNotPresent' },
            { label: 'Always', value: 'Always' },
            { label: 'Never', value: 'Never' },
          ],
          default: 'IfNotPresent',
        },
      ],
    },
    {
      title: '容器端口',
      fields: [
        {
          key: 'containerPort',
          label: '容器端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
        },
        {
          key: 'protocol',
          label: '协议',
          type: 'select',
          options: [
            { label: 'TCP', value: 'TCP' },
            { label: 'UDP', value: 'UDP' },
          ],
          default: 'TCP',
        },
      ],
    },
    {
      title: '启动命令 (可选)',
      fields: [
        {
          key: 'command',
          label: 'Command',
          type: 'text',
          placeholder: '/bin/sh',
          default: '',
          tip: '容器 ENTRYPOINT，留空则使用镜像默认值',
        },
        {
          key: 'args',
          label: 'Args',
          type: 'text',
          placeholder: '-c, echo hello',
          default: '',
          tip: '逗号分隔多个参数',
        },
      ],
    },
    {
      title: '环境变量 (可选)',
      fields: [
        {
          key: 'envVars',
          label: '环境变量',
          type: 'keyvalue',
          default: [],
          tip: '键值对，将注入为容器环境变量',
        },
      ],
    },
    {
      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: 'restartPolicy',
          label: '重启策略',
          type: 'select',
          options: [
            { label: 'Always (默认)', value: 'Always' },
            { label: 'OnFailure', value: 'OnFailure' },
            { label: 'Never', value: 'Never' },
          ],
          default: 'Always',
        },
        {
          key: 'nodeName',
          label: '指定节点',
          type: 'text',
          placeholder: 'node-1',
          default: '',
          tip: '留空则由调度器自动分配',
        },
      ],
    },
    {
      title: '标签',
      fields: [
        {
          key: 'appLabel',
          label: 'app 标签值',
          type: 'text',
          default: '',
          tip: '留空则使用 Pod 名称',
        },
        {
          key: 'versionLabel',
          label: 'version 标签',
          type: 'text',
          placeholder: 'v1',
          default: 'v1',
        },
      ],
    },
  ],
}

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 generateK8sPodYaml(config) {
  const labels = {
    app: config.appLabel || config.name,
  }
  if (config.versionLabel) {
    labels.version = config.versionLabel
  }

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

  if (config.command) {
    container.command = config.command.split(',').map(s => s.trim())
  }
  if (config.args) {
    container.args = config.args.split(',').map(s => s.trim())
  }
  if (config.envVars && config.envVars.length > 0) {
    container.env = config.envVars.map(e => ({ name: e.key, value: e.value }))
  }

  const podSpec = {
    containers: [container],
    restartPolicy: config.restartPolicy,
  }
  if (config.nodeName) {
    podSpec.nodeName = config.nodeName
  }

  const pod = {
    apiVersion: 'v1',
    kind: 'Pod',
    metadata: {
      name: config.name,
      namespace: config.namespace,
      labels,
    },
    spec: podSpec,
  }

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

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