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

export const k8sNetworkPolicySchema = {
  id: 'k8s-networkpolicy',
  name: 'K8s NetworkPolicy',
  icon: 'ShieldAlert',
  category: '云原生',
  description: 'Kubernetes 网络策略，控制 Pod 的入站和出站流量',
  format: 'yaml',
  fileName: 'networkpolicy.yaml',
  groups: [
    {
      title: '基础信息',
      fields: [
        {
          key: 'name',
          label: 'NetworkPolicy 名称',
          type: 'text',
          placeholder: 'my-network-policy',
          default: 'my-network-policy',
          required: true,
          tip: '将用作 NetworkPolicy 的 metadata.name',
        },
        {
          key: 'namespace',
          label: '命名空间',
          type: 'text',
          placeholder: 'default',
          default: 'default',
        },
      ],
    },
    {
      title: 'Pod 选择器',
      fields: [
        {
          key: 'podSelectorLabelKey',
          label: '选择器标签键',
          type: 'text',
          placeholder: 'app',
          default: 'app',
          tip: '用于匹配 Pod 的标签键',
        },
        {
          key: 'podSelectorLabelValue',
          label: '选择器标签值',
          type: 'text',
          placeholder: 'myapp',
          default: 'myapp',
          tip: '用于匹配 Pod 的标签值',
        },
      ],
    },
    {
      title: '策略类型',
      fields: [
        {
          key: 'policyTypes',
          label: '策略类型',
          type: 'select',
          options: [
            { label: '仅入站 (Ingress)', value: 'Ingress' },
            { label: '仅出站 (Egress)', value: 'Egress' },
            { label: '双向 (Ingress + Egress)', value: 'Both' },
          ],
          default: 'Both',
          tip: '控制入站、出站或双向流量',
        },
      ],
    },
    {
      title: '入站规则 (Ingress)',
      fields: [
        {
          key: 'ingressFrom',
          label: '允许来源',
          type: 'text',
          placeholder: '10.0.0.0/8 或 namespace label',
          default: '',
          tip: 'IP CIDR 或命名空间标签，留空则允许所有来源',
        },
        {
          key: 'ingressPorts',
          label: '允许端口',
          type: 'text',
          placeholder: '80,443',
          default: '',
          tip: '逗号分隔的端口号列表',
        },
      ],
    },
    {
      title: '出站规则 (Egress)',
      fields: [
        {
          key: 'egressTo',
          label: '允许目标',
          type: 'text',
          placeholder: '10.0.0.0/8 或 namespace label',
          default: '',
          tip: 'IP CIDR 或命名空间标签，留空则允许所有目标',
        },
        {
          key: 'egressPorts',
          label: '允许端口',
          type: 'text',
          placeholder: '53,443',
          default: '',
          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 generateK8sNetworkPolicyYaml(config) {
  const labelKey = config.podSelectorLabelKey || 'app'
  const labelValue = config.podSelectorLabelValue || 'myapp'

  const np = {
    apiVersion: 'networking.k8s.io/v1',
    kind: 'NetworkPolicy',
    metadata: {
      name: config.name,
      namespace: config.namespace,
    },
    spec: {
      podSelector: {
        matchLabels: { [labelKey]: labelValue },
      },
      policyTypes: [],
    },
  }

  // Determine policy types
  if (config.policyTypes === 'Both') {
    np.spec.policyTypes = ['Ingress', 'Egress']
  } else {
    np.spec.policyTypes = [config.policyTypes]
  }

  // Ingress rules
  if (np.spec.policyTypes.includes('Ingress')) {
    const ingressRule = {}
    if (config.ingressFrom) {
      const from = config.ingressFrom.split(',').map(f => f.trim()).filter(Boolean)
      ingressRule.from = from.map(f => {
        if (f.includes('/')) {
          return { ipBlock: { cidr: f } }
        }
        return { namespaceSelector: { matchLabels: { name: f } } }
      })
    }
    if (config.ingressPorts) {
      const ports = config.ingressPorts.split(',').map(p => parseInt(p.trim())).filter(p => !isNaN(p))
      if (ports.length > 0) {
        ingressRule.ports = ports.map(p => ({ port: p, protocol: 'TCP' }))
      }
    }
    if (Object.keys(ingressRule).length > 0) {
      np.spec.ingress = [ingressRule]
    }
  }

  // Egress rules
  if (np.spec.policyTypes.includes('Egress')) {
    const egressRule = {}
    if (config.egressTo) {
      const to = config.egressTo.split(',').map(t => t.trim()).filter(Boolean)
      egressRule.to = to.map(t => {
        if (t.includes('/')) {
          return { ipBlock: { cidr: t } }
        }
        return { namespaceSelector: { matchLabels: { name: t } } }
      })
    }
    if (config.egressPorts) {
      const ports = config.egressPorts.split(',').map(p => parseInt(p.trim())).filter(p => !isNaN(p))
      if (ports.length > 0) {
        egressRule.ports = ports.map(p => ({ port: p, protocol: 'TCP' }))
      }
    }
    if (Object.keys(egressRule).length > 0) {
      np.spec.egress = [egressRule]
    }
  }

  const header = `# K8s NetworkPolicy - 由 ConfTemplate 生成
# 生成时间: ${new Date().toLocaleString('zh-CN')}
# 部署命令: kubectl apply -f ${config.fileName || 'networkpolicy.yaml'}
# 注意: 需要 CNI 插件支持 NetworkPolicy (如 Calico, Cilium)
`

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