export const k8sServiceSchema = {
  id: 'k8s-service',
  name: 'K8s Service',
  icon: 'Connection',
  category: '云原生',
  description: 'Kubernetes 服务发现与负载均衡',
  format: 'yaml',
  fileName: 'service.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'serviceName',
          label: 'Service 名称',
          type: 'text',
          placeholder: 'my-app-svc',
          default: 'my-app-svc',
          required: true,
        },
        {
          key: 'namespace',
          label: '命名空间',
          type: 'text',
          placeholder: 'default',
          default: 'default',
        },
        {
          key: 'appLabel',
          label: '关联应用标签 (Selector)',
          type: 'text',
          placeholder: 'my-app',
          default: 'my-app',
          required: true,
          tip: '需匹配 Deployment 中 Pod 的 app 标签',
        },
      ],
    },
    {
      title: 'Service 类型与端口',
      fields: [
        {
          key: 'serviceType',
          label: 'Service 类型',
          type: 'select',
          options: [
            { label: 'ClusterIP - 集群内部访问', value: 'ClusterIP' },
            { label: 'NodePort - 节点端口暴露', value: 'NodePort' },
            { label: 'LoadBalancer - 云负载均衡', value: 'LoadBalancer' },
          ],
          default: 'ClusterIP',
          tip: 'ClusterIP: 仅集群内访问; NodePort: 通过节点IP+端口访问; LoadBalancer: 云厂商 LB',
        },
        {
          key: 'port',
          label: 'Service 端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
          tip: 'Service 暴露的端口',
        },
        {
          key: 'targetPort',
          label: '目标容器端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
          tip: '需与 Deployment 中容器端口一致',
        },
        {
          key: 'protocol',
          label: '协议',
          type: 'select',
          options: [
            { label: 'TCP', value: 'TCP' },
            { label: 'UDP', value: 'UDP' },
          ],
          default: 'TCP',
        },
        {
          key: 'portName',
          label: '端口名称',
          type: 'text',
          placeholder: 'http',
          default: 'http',
        },
        {
          key: 'nodePort',
          label: 'NodePort 端口',
          type: 'number',
          min: 30000,
          max: 32767,
          default: 30080,
          dependsOn: { key: 'serviceType', value: 'NodePort' },
          tip: 'NodePort 范围: 30000-32767',
        },
      ],
    },
    {
      title: '会话保持与高级选项',
      fields: [
        {
          key: 'sessionAffinity',
          label: '会话保持',
          type: 'switch',
          default: false,
          tip: '启用后同一客户端请求会转发到同一 Pod',
        },
        {
          key: 'sessionTimeout',
          label: '会话超时 (秒)',
          type: 'number',
          min: 1,
          max: 86400,
          default: 10800,
          dependsOn: { key: 'sessionAffinity', value: true },
        },
        {
          key: 'externalTrafficPolicy',
          label: '外部流量策略',
          type: 'select',
          options: [
            { label: 'Cluster - 跨节点负载均衡 (默认)', value: 'Cluster' },
            { label: 'Local - 保留源 IP', value: 'Local' },
          ],
          default: 'Cluster',
          dependsOn: { key: 'serviceType', valueNotIn: ['ClusterIP'] },
          tip: 'Local 可保留客户端真实 IP',
        },
      ],
    },
  ],
}

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 generateK8sServiceYaml(config) {
  const portSpec = {
    name: config.portName,
    port: config.port,
    targetPort: config.targetPort,
    protocol: config.protocol,
  }

  if (config.serviceType === 'NodePort') {
    portSpec.nodePort = config.nodePort
  }

  const service = {
    apiVersion: 'v1',
    kind: 'Service',
    metadata: {
      name: config.serviceName,
      namespace: config.namespace,
      labels: {
        app: config.appLabel,
      },
    },
    spec: {
      type: config.serviceType,
      selector: {
        app: config.appLabel,
      },
      ports: [portSpec],
    },
  }

  if (config.sessionAffinity) {
    service.spec.sessionAffinity = 'ClientIP'
    service.spec.sessionAffinityConfig = {
      clientIP: {
        timeoutSeconds: config.sessionTimeout,
      },
    }
  }

  if (config.serviceType !== 'ClusterIP' && config.externalTrafficPolicy) {
    service.spec.externalTrafficPolicy = config.externalTrafficPolicy
  }

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

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