export const lvsSchema = {
  id: 'lvs',
  name: 'LVS',
  icon: 'Connection',
  category: '高可用',
  description: 'Linux Virtual Server，基于 IP 层的四层负载均衡',
  format: 'conf',
  fileName: 'lvs-dr.conf',
  groups: [
    {
      title: '虚拟服务配置',
      fields: [
        {
          key: 'vip',
          label: '虚拟 IP (VIP)',
          type: 'text',
          default: '192.168.1.100',
          required: true,
          tip: '对外提供服务的虚拟 IP',
        },
        {
          key: 'vipPort',
          label: '虚拟服务端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
        },
        {
          key: 'protocol',
          label: '协议',
          type: 'select',
          options: [
            { label: 'TCP', value: 'tcp' },
            { label: 'UDP', value: 'udp' },
            { label: 'FTP', value: 'ftp' },
          ],
          default: 'tcp',
        },
        {
          key: 'scheduler',
          label: '调度算法',
          type: 'select',
          options: [
            { label: 'wrr - 加权轮询', value: 'wrr' },
            { label: 'wlc - 加权最少连接 (推荐)', value: 'wlc' },
            { label: 'lc - 最少连接', value: 'lc' },
            { label: 'sh - 源地址哈希', value: 'sh' },
            { label: 'dh - 目标地址哈希', value: 'dh' },
            { label: 'rr - 轮询', value: 'rr' },
          ],
          default: 'wrr',
        },
        {
          key: 'drMode',
          label: '转发模式',
          type: 'select',
          options: [
            { label: 'DR - 直接路由 (推荐)', value: 'dr' },
            { label: 'NAT - 网络地址转换', value: 'nat' },
            { label: 'TUN - IP 隧道', value: 'tun' },
          ],
          default: 'dr',
        },
      ],
    },
    {
      title: 'Real Server 1',
      fields: [
        {
          key: 'realServer1',
          label: '真实服务器 1 IP',
          type: 'text',
          default: '192.168.1.10',
        },
        {
          key: 'realServer1Port',
          label: '端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
        },
        {
          key: 'realServer1Weight',
          label: '权重',
          type: 'number',
          min: 0,
          max: 256,
          default: 1,
        },
      ],
    },
    {
      title: 'Real Server 2',
      fields: [
        {
          key: 'realServer2',
          label: '真实服务器 2 IP',
          type: 'text',
          default: '192.168.1.11',
        },
        {
          key: 'realServer2Port',
          label: '端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
        },
        {
          key: 'realServer2Weight',
          label: '权重',
          type: 'number',
          min: 0,
          max: 256,
          default: 1,
        },
      ],
    },
    {
      title: 'Real Server 3 (可选)',
      fields: [
        {
          key: 'enableRealServer3',
          label: '启用第三台服务器',
          type: 'switch',
          default: false,
        },
        {
          key: 'realServer3',
          label: '真实服务器 3 IP',
          type: 'text',
          default: '192.168.1.12',
          dependsOn: { key: 'enableRealServer3', value: true },
        },
        {
          key: 'realServer3Port',
          label: '端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
          dependsOn: { key: 'enableRealServer3', value: true },
        },
        {
          key: 'realServer3Weight',
          label: '权重',
          type: 'number',
          min: 0,
          max: 256,
          default: 1,
          dependsOn: { key: 'enableRealServer3', value: true },
        },
      ],
    },
    {
      title: '健康检查',
      fields: [
        {
          key: 'enableHealthCheck',
          label: '启用健康检查',
          type: 'switch',
          default: true,
        },
        {
          key: 'healthCheckType',
          label: '检查类型',
          type: 'select',
          options: [
            { label: 'TCP 端口检查', value: 'tcp' },
            { label: 'HTTP GET 检查', value: 'http' },
          ],
          default: 'tcp',
          dependsOn: { key: 'enableHealthCheck', value: true },
        },
        {
          key: 'healthCheckUrl',
          label: '检查 URL 路径',
          type: 'text',
          default: '/health',
          dependsOn: { key: 'healthCheckType', value: 'http' },
        },
        {
          key: 'healthCheckPort',
          label: '检查端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 80,
          dependsOn: { key: 'healthCheckType', value: 'http' },
        },
      ],
    },
  ],
}

export function generateLvsConf(config) {
  const lines = []
  lines.push(`#!/bin/bash`)
  lines.push(`# LVS 配置脚本 (ipvsadm 命令) - 由 ConfTemplate 生成`)
  lines.push(`# 生成时间: ${new Date().toLocaleString('zh-CN')}`)
  lines.push(`# 转发模式: ${config.drMode.toUpperCase()}`)
  lines.push(``)
  lines.push(`# 清除现有规则`)
  lines.push(`ipvsadm -C`)
  lines.push(``)

  // Add VIP
  const modeFlag = config.drMode === 'nat' ? '-m' : config.drMode === 'tun' ? '-i' : '-g'
  lines.push(`# 添加虚拟服务`)
  lines.push(`#   VIP: ${config.vip}:${config.vipPort}`)
  lines.push(`#   协议: ${config.protocol.toUpperCase()}`)
  lines.push(`#   调度算法: ${config.scheduler}`)
  lines.push(`ipvsadm -A -t ${config.vip}:${config.vipPort} -s ${config.scheduler}`)
  lines.push(``)

  // Add real servers
  lines.push(`# 添加真实服务器`)
  lines.push(`# Real Server 1: ${config.realServer1}:${config.realServer1Port} (weight=${config.realServer1Weight})`)
  lines.push(`ipvsadm -a -t ${config.vip}:${config.vipPort} -r ${config.realServer1}:${config.realServer1Port} -w ${config.realServer1Weight} ${modeFlag}`)
  lines.push(``)
  lines.push(`# Real Server 2: ${config.realServer2}:${config.realServer2Port} (weight=${config.realServer2Weight})`)
  lines.push(`ipvsadm -a -t ${config.vip}:${config.vipPort} -r ${config.realServer2}:${config.realServer2Port} -w ${config.realServer2Weight} ${modeFlag}`)
  lines.push(``)

  if (config.enableRealServer3) {
    lines.push(`# Real Server 3: ${config.realServer3}:${config.realServer3Port} (weight=${config.realServer3Weight})`)
    lines.push(`ipvsadm -a -t ${config.vip}:${config.vipPort} -r ${config.realServer3}:${config.realServer3Port} -w ${config.realServer3Weight} ${modeFlag}`)
    lines.push(``)
  }

  lines.push(`# 查看当前规则`)
  lines.push(`ipvsadm -Ln`)
  lines.push(``)

  // Health check script
  if (config.enableHealthCheck) {
    lines.push(`# ============================================================`)
    lines.push(`# 健康检查脚本 (保存为 /etc/lvs/check_real_server.sh)`)
    lines.push(`# ============================================================`)
    lines.push(`cat > /etc/lvs/check_real_server.sh << 'HEALTHCHECK_EOF'`)
    lines.push(`#!/bin/bash`)
    lines.push(`# LVS 健康检查脚本`)
    lines.push(`VIP="${config.vip}"`)
    lines.push(`VPORT="${config.vipPort}"`)
    lines.push(``)

    const servers = [
      { ip: config.realServer1, port: config.realServer1Port, weight: config.realServer1Weight },
      { ip: config.realServer2, port: config.realServer2Port, weight: config.realServer2Weight },
    ]
    if (config.enableRealServer3) {
      servers.push({ ip: config.realServer3, port: config.realServer3Port, weight: config.realServer3Weight })
    }

    for (let i = 0; i < servers.length; i++) {
      const rs = servers[i]
      lines.push(`# Check Real Server ${i + 1}: ${rs.ip}`)
      if (config.healthCheckType === 'tcp') {
        lines.push(`if nc -z -w 3 ${rs.ip} ${rs.port} > /dev/null 2>&1; then`)
      } else {
        lines.push(`if curl -s -o /dev/null -w "%{http_code}" http://${rs.ip}:${config.healthCheckPort}${config.healthCheckUrl} | grep -q "200"; then`)
      }
      lines.push(`    # Server ${rs.ip} is UP`)
      lines.push(`    ipvsadm -a -t $VIP:$VPORT -r ${rs.ip}:${rs.port} -w ${rs.weight} ${modeFlag} 2>/dev/null`)
      lines.push(`else`)
      lines.push(`    # Server ${rs.ip} is DOWN, removing from pool`)
      lines.push(`    ipvsadm -d -t $VIP:$VPORT -r ${rs.ip}:${rs.port} 2>/dev/null`)
      lines.push(`fi`)
      lines.push(``)
    }

    lines.push(`HEALTHCHECK_EOF`)
    lines.push(`chmod +x /etc/lvs/check_real_server.sh`)
    lines.push(``)
    lines.push(`# 添加 crontab 定时检查 (每 10 秒)`)
    lines.push(`# */1 * * * * /etc/lvs/check_real_server.sh`)
    lines.push(`# */1 * * * * sleep 10 && /etc/lvs/check_real_server.sh`)
    lines.push(`# */1 * * * * sleep 20 && /etc/lvs/check_real_server.sh`)
    lines.push(`# */1 * * * * sleep 30 && /etc/lvs/check_real_server.sh`)
    lines.push(`# */1 * * * * sleep 40 && /etc/lvs/check_real_server.sh`)
    lines.push(`# */1 * * * * sleep 50 && /etc/lvs/check_real_server.sh`)
  }

  return lines.join('\n')
}
