export const k8sJobSchema = {
  id: 'k8s-job',
  name: 'K8s Job',
  icon: 'Box',
  category: 'K8S 工作负载',
  description: 'Kubernetes Job — 运行一次性批处理任务',
  format: 'yaml',
  fileName: 'job.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'Job 名称',
          type: 'text',
          placeholder: 'my-job',
          default: 'my-job',
          required: true,
        },
        {
          key: 'namespace',
          label: '命名空间',
          type: 'text',
          placeholder: 'default',
          default: 'default',
        },
        {
          key: 'image',
          label: '容器镜像',
          type: 'text',
          placeholder: 'busybox:latest',
          default: 'busybox:latest',
          required: true,
        },
        {
          key: 'command',
          label: 'Command',
          type: 'text',
          placeholder: 'echo hello',
          default: 'echo hello',
          required: true,
          tip: '容器启动命令',
        },
      ],
    },
    {
      title: '执行控制',
      fields: [
        {
          key: 'backoffLimit',
          label: '重试次数上限',
          type: 'number',
          min: 0,
          max: 100,
          default: 6,
          tip: '失败后最多重试次数',
        },
        {
          key: 'completions',
          label: '完成数量',
          type: 'number',
          min: 1,
          max: 100,
          default: 1,
          tip: '需要成功完成的 Pod 数',
        },
        {
          key: 'parallelism',
          label: '并行度',
          type: 'number',
          min: 1,
          max: 100,
          default: 1,
          tip: '同时运行的 Pod 数',
        },
        {
          key: 'activeDeadlineSeconds',
          label: '超时时间 (秒)',
          type: 'number',
          min: 0,
          max: 86400,
          default: 0,
          tip: '0 表示不限制超时',
        },
      ],
    },
    {
      title: '重启与清理',
      fields: [
        {
          key: 'restartPolicy',
          label: '重启策略',
          type: 'select',
          options: [
            { label: 'Never (推荐)', value: 'Never' },
            { label: 'OnFailure', value: 'OnFailure' },
          ],
          default: 'Never',
        },
        {
          key: 'ttlSecondsAfterFinished',
          label: '自动清理 (秒)',
          type: 'number',
          min: 0,
          max: 86400,
          default: 0,
          tip: '完成后自动删除 Job，0 表示保留',
        },
      ],
    },
  ],
}

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 generateK8sJobYaml(config) {
  const container = {
    name: config.name,
    image: config.image,
    command: config.command.split(' '),
  }

  const job = {
    apiVersion: 'batch/v1',
    kind: 'Job',
    metadata: {
      name: config.name,
      namespace: config.namespace,
    },
    spec: {
      backoffLimit: config.backoffLimit,
      completions: config.completions,
      parallelism: config.parallelism,
      template: {
        spec: {
          containers: [container],
          restartPolicy: config.restartPolicy,
        },
      },
    },
  }

  if (config.activeDeadlineSeconds > 0) {
    job.spec.activeDeadlineSeconds = config.activeDeadlineSeconds
  }

  if (config.ttlSecondsAfterFinished > 0) {
    job.spec.ttlSecondsAfterFinished = config.ttlSecondsAfterFinished
  }

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

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