export const sersyncSchema = {
  id: 'sersync',
  name: 'Sersync',
  icon: 'Refresh',
  category: '系统服务',
  description: '基于 inotify + rsync 的实时文件同步工具',
  format: 'xml',
  fileName: 'confxml.xml',
  groups: [
    {
      title: '基础配置',
      fields: [
        {
          key: 'watchPath',
          label: '监控目录',
          type: 'text',
          default: '/data/web',
          tip: '需要实时同步的本地目录',
        },
        {
          key: 'localDebug',
          label: '本地调试模式',
          type: 'switch',
          default: false,
          tip: '开启后仅记录日志不执行同步',
        },
      ],
    },
    {
      title: 'Rsync 配置',
      fields: [
        {
          key: 'rsyncCommand',
          label: 'Rsync 命令路径',
          type: 'text',
          default: '/usr/bin/rsync',
        },
        {
          key: 'rsyncArgs',
          label: 'Rsync 参数',
          type: 'text',
          default: '-avz --delete',
          tip: '常用的 rsync 同步参数',
        },
        {
          key: 'rsyncUser',
          label: 'Rsync 用户',
          type: 'text',
          default: 'root',
        },
        {
          key: 'remoteHosts',
          label: '远程主机列表',
          type: 'text',
          default: '192.168.1.101::backup 192.168.1.102::backup',
          tip: '格式: IP::模块名，多个用空格分隔',
        },
        {
          key: 'remotePassword',
          label: '密码文件路径',
          type: 'text',
          default: '/etc/rsyncd.secrets',
        },
      ],
    },
    {
      title: 'SSH 配置',
      fields: [
        {
          key: 'enableSsh',
          label: '启用 SSH 传输',
          type: 'switch',
          default: false,
          tip: '使用 SSH 代替 rsync daemon 传输',
        },
        {
          key: 'sshPort',
          label: 'SSH 端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 22,
          dependsOn: { key: 'enableSsh', value: true },
        },
      ],
    },
    {
      title: '监控配置',
      fields: [
        {
          key: 'enableMonitor',
          label: '开启 HTTP 监控',
          type: 'switch',
          default: true,
          tip: '提供 HTTP 接口查看同步状态',
        },
        {
          key: 'monitorPort',
          label: '监控端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 8008,
          dependsOn: { key: 'enableMonitor', value: true },
        },
        {
          key: 'failLog',
          label: '失败日志脚本',
          type: 'text',
          default: '/tmp/rsync_fail_log.sh',
          tip: '同步失败时执行的脚本',
        },
      ],
    },
    {
      title: '定时任务与过滤',
      fields: [
        {
          key: 'enableCron',
          label: '启用定时同步',
          type: 'switch',
          default: true,
          tip: '定时执行全量同步作为兜底',
        },
        {
          key: 'cronInterval',
          label: '定时同步间隔 (秒)',
          type: 'number',
          min: 60,
          max: 86400,
          default: 600,
          dependsOn: { key: 'enableCron', value: true },
          tip: '每隔多少秒执行一次全量同步',
        },
        {
          key: 'filterRule',
          label: '启用过滤规则',
          type: 'switch',
          default: false,
          tip: '过滤不需要同步的文件',
        },
        {
          key: 'filterExpression',
          label: '过滤表达式',
          type: 'text',
          default: '*.tmp *.temp',
          dependsOn: { key: 'filterRule', value: true },
          tip: '匹配的文件不同步，空格分隔',
        },
      ],
    },
  ],
}

export function generateSersyncXml(config) {
  const lines = []
  lines.push(`<?xml version="1.0" encoding="UTF-8"?>`)
  lines.push(`<!-- Sersync 配置文件 - 由 ConfTemplate 生成 -->`)
  lines.push(`<!-- 生成时间: ${new Date().toLocaleString('zh-CN')} -->`)
  lines.push(`<head>`)
  lines.push(`  <host hostip="localhost" port="8008"></host>`)
  lines.push(`  <filter start="false">`)

  if (config.filterRule && config.filterExpression) {
    const expressions = config.filterExpression.split(/\s+/).filter(Boolean)
    for (const expr of expressions) {
      lines.push(`    <exclude expression="${expr}"></exclude>`)
    }
  }

  lines.push(`  </filter>`)
  lines.push(`  <inotify start="true">`)
  lines.push(`    <delete start="true"/>`)
  lines.push(`    <createFolder start="true"/>`)
  lines.push(`    <createFile start="false"/>`)
  lines.push(`    <closeWrite start="true"/>`)
  lines.push(`    <moveFrom start="true"/>`)
  lines.push(`    <moveTo start="true"/>`)
  lines.push(`    <attrib start="false"/>`)
  lines.push(`    <modify start="false"/>`)
  lines.push(`  </inotify>`)
  lines.push(`  <sersync>`)
  lines.push(`    <localpath watch="${config.watchPath}">`)

  // 解析远程主机列表
  const hosts = config.remoteHosts.split(/\s+/).filter(Boolean)
  for (const host of hosts) {
    if (config.enableSsh) {
      const parts = host.split('::')
      const ip = parts[0]
      const remotePath = parts[1] || '/data/backup'
      lines.push(`      <remote ip="${ip}" name="${remotePath}"/>`)
    } else {
      const parts = host.split('::')
      const ip = parts[0]
      const module = parts[1] || 'backup'
      lines.push(`      <remote ip="${ip}" name="${module}"/>`)
    }
  }

  lines.push(`    </localpath>`)
  lines.push(`    <rsync>`)
  lines.push(`      <commonParams params="${config.rsyncArgs}"/>`)

  if (config.enableSsh) {
    lines.push(`      <ssh start="true" port="${config.sshPort}"/>`)
  }

  lines.push(`      <userDefinedPort start="false" port="874"/><!-- rsync daemon 端口 -->`)
  lines.push(`      <auth start="${config.rsyncUser ? 'true' : 'false'}" users="${config.rsyncUser}" passwordfile="${config.remotePassword}"/>`)
  lines.push(`      <userDefinedPort start="false" port="874"/>`)
  lines.push(`      <timeout start="true" time="1000"/><!-- timeout in ms -->`)
  lines.push(`    </rsync>`)

  if (config.enableMonitor) {
    lines.push(`    <failLog path="${config.failLog}" timeToExecute="60"/><!-- 每60秒检查一次失败日志 -->`)
  } else {
    lines.push(`    <failLog path="${config.failLog}" timeToExecute="60"/>`)
  }

  if (config.enableCron) {
    lines.push(`    <crontab start="true" schedule="${Math.floor(config.cronInterval / 60)}"><!-- 分钟 -->`)
    lines.push(`      <crontabfilter start="false">`)
    if (config.filterRule && config.filterExpression) {
      const expressions = config.filterExpression.split(/\s+/).filter(Boolean)
      for (const expr of expressions) {
        lines.push(`        <exclude expression="${expr}"></exclude>`)
      }
    }
    lines.push(`      </crontabfilter>`)
    lines.push(`    </crontab>`)
  } else {
    lines.push(`    <crontab start="false" schedule="600">`)
    lines.push(`      <crontabfilter start="false">`)
    lines.push(`      </crontabfilter>`)
    lines.push(`    </crontab>`)
  }

  lines.push(`    <plugin start="false" name="command"/>`)
  lines.push(`  </sersync>`)
  lines.push(`  <plugin name="command">`)
  lines.push(`    <param prefix="/bin/sh" suffix="" ignoreError="true"/>`)
  lines.push(`    <filter start="false">`)
  lines.push(`      <include expression="(.*)\.php"/>`)
  lines.push(`      <include expression="(.*)\.sh"/>`)
  lines.push(`    </filter>`)
  lines.push(`  </plugin>`)
  lines.push(`  <plugin name="socket">`)
  lines.push(`    <localpath watch="/opt/tongbu">`)
  lines.push(`      <deshost ip="192.168.1.101" port="8009"/>`)
  lines.push(`    </localpath>`)
  lines.push(`  </plugin>`)
  lines.push(`</head>`)

  return lines.join('\n')
}
