// K8s ConfigMap Schema - 由 ConfTemplate 生成
// 生成时间: 自动生成

export const k8sConfigMapSchema = {
  id: 'k8s-configmap',
  name: 'K8s ConfigMap',
  icon: 'Settings',
  category: '云原生',
  description: 'Kubernetes 配置映射，存储键值对配置数据',
  format: 'yaml',
  fileName: 'configmap.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'ConfigMap 名称',
          type: 'text',
          placeholder: 'my-config',
          default: 'my-config',
          required: true,
          tip: '将用作 ConfigMap 的 metadata.name',
        },
        {
          key: 'namespace',
          label: '命名空间',
          type: 'text',
          placeholder: 'default',
          default: 'default',
        },
      ],
    },
    {
      title: '数据配置',
      fields: [
        {
          key: 'dataType',
          label: '数据类型',
          type: 'select',
          options: [
            { label: '字面量 (Literal)', value: 'literal' },
            { label: '环境变量注入 (EnvFrom)', value: 'envFrom' },
            { label: '文件挂载 (File)', value: 'file' },
          ],
          default: 'literal',
          tip: '决定 ConfigMap 数据的使用方式',
        },
        {
          key: 'dataKey',
          label: '数据键名',
          type: 'text',
          placeholder: 'app.conf',
          default: 'app.conf',
          required: true,
          tip: 'ConfigMap 中的键名，如配置文件名或环境变量名',
        },
        {
          key: 'dataValue',
          label: '数据值',
          type: 'textarea',
          placeholder: 'key1=value1\nkey2=value2',
          default: 'key1=value1\nkey2=value2',
          required: true,
          tip: '键值对，每行一个，格式 key=value',
        },
      ],
    },
    {
      title: '挂载配置',
      fields: [
        {
          key: 'mountAsVolume',
          label: '作为 Volume 挂载',
          type: 'switch',
          default: true,
          tip: '是否将 ConfigMap 挂载为容器内的文件',
        },
        {
          key: 'mountPath',
          label: '挂载路径',
          type: 'text',
          placeholder: '/etc/config',
          default: '/etc/config',
          dependsOn: { key: 'mountAsVolume', value: true },
          tip: '容器内挂载目录路径',
        },
      ],
    },
  ],
}

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 generateK8sConfigMapYaml(config) {
  const data = {}
  if (config.dataValue) {
    const lines = config.dataValue.split('\n').filter(line => line.trim())
    for (const line of lines) {
      const eqIdx = line.indexOf('=')
      if (eqIdx > 0) {
        const k = line.substring(0, eqIdx).trim()
        const v = line.substring(eqIdx + 1).trim()
        data[k] = v
      } else {
        data[config.dataKey || 'data'] = line.trim()
      }
    }
  } else {
    data[config.dataKey || 'data'] = ''
  }

  const configmap = {
    apiVersion: 'v1',
    kind: 'ConfigMap',
    metadata: {
      name: config.name,
      namespace: config.namespace,
    },
    data,
  }

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

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