export const k8sCronJobSchema = {
  id: 'k8s-cronjob',
  name: 'K8s CronJob',
  icon: 'Box',
  category: 'K8S 工作负载',
  description: 'Kubernetes CronJob — 定时调度批处理任务',
  format: 'yaml',
  fileName: 'cronjob.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'CronJob 名称',
          type: 'text',
          placeholder: 'my-cronjob',
          default: 'my-cronjob',
          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: 'schedule',
          label: 'Cron 表达式',
          type: 'text',
          placeholder: '0 * * * *',
          default: '0 * * * *',
          required: true,
          tip: '标准 cron 格式: 分 时 日 月 周',
        },
        {
          key: 'concurrencyPolicy',
          label: '并发策略',
          type: 'select',
          options: [
            { label: 'Allow - 允许并发', value: 'Allow' },
            { label: 'Replace - 替换上一个', value: 'Replace' },
            { label: 'Forbid - 禁止并发', value: 'Forbid' },
          ],
          default: 'Allow',
        },
        {
          key: 'suspend',
          label: '暂停调度',
          type: 'switch',
          default: false,
          tip: '暂停后不再创建新的 Job',
        },
      ],
    },
    {
      title: '历史与清理',
      fields: [
        {
          key: 'successfulJobsHistoryLimit',
          label: '成功 Job 保留数',
          type: 'number',
          min: 0,
          max: 10,
          default: 3,
        },
        {
          key: 'failedJobsHistoryLimit',
          label: '失败 Job 保留数',
          type: 'number',
          min: 0,
          max: 10,
          default: 1,
        },
      ],
    },
    {
      title: 'Job 配置',
      fields: [
        {
          key: 'restartPolicy',
          label: '重启策略',
          type: 'select',
          options: [
            { label: 'OnFailure (推荐)', value: 'OnFailure' },
            { label: 'Never', value: 'Never' },
          ],
          default: 'OnFailure',
        },
        {
          key: 'backoffLimit',
          label: '重试次数上限',
          type: 'number',
          min: 0,
          max: 100,
          default: 6,
        },
      ],
    },
  ],
}

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

  const cronjob = {
    apiVersion: 'batch/v1',
    kind: 'CronJob',
    metadata: {
      name: config.name,
      namespace: config.namespace,
    },
    spec: {
      schedule: config.schedule,
      concurrencyPolicy: config.concurrencyPolicy,
      successfulJobsHistoryLimit: config.successfulJobsHistoryLimit,
      failedJobsHistoryLimit: config.failedJobsHistoryLimit,
      suspend: config.suspend || undefined,
      jobTemplate: {
        spec: {
          backoffLimit: config.backoffLimit,
          template: {
            spec: {
              containers: [container],
              restartPolicy: config.restartPolicy,
            },
          },
        },
      },
    },
  }

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

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