export const tomcatSchema = {
  id: 'tomcat',
  name: 'Tomcat',
  icon: 'Monitor',
  category: '代理与Web',
  description: 'Apache Tomcat Java 应用服务器',
  format: 'xml',
  fileName: 'server.xml',
  groups: [
    {
      title: '基础配置',
      fields: [
        {
          key: 'port',
          label: 'Server 关闭端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 8005,
          tip: '用于接收关闭命令的端口',
        },
        {
          key: 'shutdown',
          label: '关闭命令',
          type: 'text',
          default: 'SHUTDOWN',
        },
        {
          key: 'httpPort',
          label: 'HTTP 连接端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 8080,
        },
        {
          key: 'ajpPort',
          label: 'AJP 连接端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 8009,
          tip: 'Apache 通过 AJP 协议连接 Tomcat',
        },
        {
          key: 'enableAjp',
          label: '启用 AJP 连接器',
          type: 'switch',
          default: false,
        },
      ],
    },
    {
      title: '连接器配置',
      fields: [
        {
          key: 'maxThreads',
          label: '最大线程数',
          type: 'number',
          min: 10,
          max: 4096,
          default: 200,
          tip: '处理请求的最大线程数',
        },
        {
          key: 'minSpareThreads',
          label: '最小空闲线程',
          type: 'number',
          min: 1,
          max: 200,
          default: 10,
        },
        {
          key: 'connectionTimeout',
          label: '连接超时 (毫秒)',
          type: 'number',
          min: 0,
          max: 120000,
          default: 20000,
        },
        {
          key: 'maxConnections',
          label: '最大连接数',
          type: 'number',
          min: 1,
          max: 100000,
          default: 10000,
        },
        {
          key: 'enableCompression',
          label: '开启压缩',
          type: 'switch',
          default: false,
        },
        {
          key: 'compressionMinSize',
          label: '压缩最小体积 (字节)',
          type: 'number',
          min: 0,
          max: 10240,
          default: 2048,
          dependsOn: { key: 'enableCompression', value: true },
        },
        {
          key: 'compressibleMimeType',
          label: '压缩 MIME 类型',
          type: 'text',
          default: 'text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json',
          dependsOn: { key: 'enableCompression', value: true },
        },
      ],
    },
    {
      title: 'HTTPS / SSL',
      fields: [
        {
          key: 'enableSsl',
          label: '开启 HTTPS',
          type: 'switch',
          default: false,
        },
        {
          key: 'httpsPort',
          label: 'HTTPS 端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 8443,
          dependsOn: { key: 'enableSsl', value: true },
        },
        {
          key: 'keystoreFile',
          label: 'Keystore 文件路径',
          type: 'text',
          placeholder: '/etc/tomcat/keystore.jks',
          default: '/etc/tomcat/keystore.jks',
          dependsOn: { key: 'enableSsl', value: true },
          required: true,
        },
        {
          key: 'keystorePass',
          label: 'Keystore 密码',
          type: 'text',
          placeholder: 'changeit',
          default: 'changeit',
          dependsOn: { key: 'enableSsl', value: true },
        },
        {
          key: 'sslProtocol',
          label: 'SSL 协议',
          type: 'select',
          options: [
            { label: 'TLS (推荐)', value: 'TLS' },
            { label: 'TLSv1.2', value: 'TLSv1.2' },
            { label: 'TLSv1.2 + TLSv1.3', value: 'TLSv1.2,TLSv1.3' },
          ],
          default: 'TLS',
          dependsOn: { key: 'enableSsl', value: true },
        },
      ],
    },
    {
      title: 'Engine 与 Host',
      fields: [
        {
          key: 'defaultHost',
          label: '默认主机名',
          type: 'text',
          default: 'localhost',
        },
        {
          key: 'appBase',
          label: '应用部署目录',
          type: 'text',
          default: 'webapps',
          tip: '相对于 CATALINA_BASE',
        },
        {
          key: 'unpackWARs',
          label: '自动解压 WAR',
          type: 'switch',
          default: true,
        },
        {
          key: 'autoDeploy',
          label: '自动部署',
          type: 'switch',
          default: true,
          tip: '检测到新 WAR 自动部署',
        },
        {
          key: 'deployOnStartup',
          label: '启动时自动部署',
          type: 'switch',
          default: true,
        },
      ],
    },
    {
      title: 'JVM 内存',
      fields: [
        {
          key: 'enableJvmArgs',
          label: '自定义 JVM 参数',
          type: 'switch',
          default: false,
          tip: '设置 JAVA_OPTS 环境变量',
        },
        {
          key: 'xms',
          label: '初始堆内存 (-Xms)',
          type: 'select',
          options: [
            { label: '256m', value: '256m' },
            { label: '512m', value: '512m' },
            { label: '1g', value: '1g' },
            { label: '2g', value: '2g' },
            { label: '4g', value: '4g' },
          ],
          default: '512m',
          dependsOn: { key: 'enableJvmArgs', value: true },
        },
        {
          key: 'xmx',
          label: '最大堆内存 (-Xmx)',
          type: 'select',
          options: [
            { label: '512m', value: '512m' },
            { label: '1g', value: '1g' },
            { label: '2g', value: '2g' },
            { label: '4g', value: '4g' },
            { label: '8g', value: '8g' },
          ],
          default: '1g',
          dependsOn: { key: 'enableJvmArgs', value: true },
        },
        {
          key: 'metaspaceSize',
          label: 'Metaspace 大小',
          type: 'select',
          options: [
            { label: '128m', value: '128m' },
            { label: '256m', value: '256m' },
            { label: '512m', value: '512m' },
          ],
          default: '256m',
          dependsOn: { key: 'enableJvmArgs', value: true },
        },
        {
          key: 'gcType',
          label: 'GC 算法',
          type: 'select',
          options: [
            { label: 'G1GC (推荐 JDK9+)', value: '-XX:+UseG1GC' },
            { label: 'ZGC (推荐 JDK15+)', value: '-XX:+UseZGC' },
            { label: 'ParallelGC', value: '-XX:+UseParallelGC' },
            { label: 'CMS (JDK8)', value: '-XX:+UseConcMarkSweepGC' },
          ],
          default: '-XX:+UseG1GC',
          dependsOn: { key: 'enableJvmArgs', value: true },
        },
      ],
    },
    {
      title: '日志与安全',
      fields: [
        {
          key: 'accessLogEnabled',
          label: '开启访问日志',
          type: 'switch',
          default: true,
        },
        {
          key: 'accessLogPattern',
          label: '日志格式',
          type: 'select',
          options: [
            { label: 'common - 通用日志格式', value: 'common' },
            { label: 'combined - 组合日志格式 (推荐)', value: 'combined' },
            { label: '详细格式 (含响应时间)', value: '%h %l %u %t "%r" %s %b %D "%{Referer}i" "%{User-Agent}i"' },
          ],
          default: 'combined',
          dependsOn: { key: 'accessLogEnabled', value: true },
        },
        {
          key: 'enableManager',
          label: '启用 Manager 应用',
          type: 'switch',
          default: false,
          tip: '生产环境建议通过 CI/CD 部署，禁用 Manager',
        },
        {
          key: 'enableHostManager',
          label: '启用 Host Manager',
          type: 'switch',
          default: false,
        },
      ],
    },
  ],
}

export function generateTomcatServerXml(config) {
  const lines = []
  lines.push(`<?xml version="1.0" encoding="UTF-8"?>`)
  lines.push(`<!-- Tomcat Server 配置文件 - 由 ConfTemplate 生成 -->`)
  lines.push(`<!-- 生成时间: ${new Date().toLocaleString('zh-CN')} -->`)
  lines.push(`<Server port="${config.port}" shutdown="${config.shutdown}">`)
  lines.push(``)
  lines.push(`  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />`)
  lines.push(`  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />`)
  lines.push(`  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />`)
  lines.push(`  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />`)
  lines.push(`  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />`)
  lines.push(``)
  lines.push(`  <GlobalNamingResources>`)
  lines.push(`    <Resource name="UserDatabase" auth="Container"`)
  lines.push(`              type="org.apache.catalina.UserDatabase"`)
  lines.push(`              description="User database"`)
  lines.push(`              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"`)
  lines.push(`              pathname="conf/tomcat-users.xml" />`)
  lines.push(`  </GlobalNamingResources>`)
  lines.push(``)
  lines.push(`  <Service name="Catalina">`)
  lines.push(``)

  // HTTP Connector
  lines.push(`    <!-- HTTP 连接器 -->`)
  lines.push(`    <Connector port="${config.httpPort}"`)
  lines.push(`               protocol="HTTP/1.1"`)
  lines.push(`               connectionTimeout="${config.connectionTimeout}"`)
  lines.push(`               maxThreads="${config.maxThreads}"`)
  lines.push(`               minSpareThreads="${config.minSpareThreads}"`)
  lines.push(`               maxConnections="${config.maxConnections}"`)
  lines.push(`               redirectPort="${config.enableSsl ? config.httpsPort : 8443}"`)
  lines.push(`               URIEncoding="UTF-8"`)

  if (config.enableCompression) {
    lines.push(`               compression="on"`)
    lines.push(`               compressionMinSize="${config.compressionMinSize}"`)
    lines.push(`               compressibleMimeType="${config.compressibleMimeType}"`)
  }

  lines.push(`               />`)
  lines.push(``)

  // AJP Connector
  if (config.enableAjp) {
    lines.push(`    <!-- AJP 连接器 -->`)
    lines.push(`    <Connector port="${config.ajpPort}"`)
    lines.push(`               protocol="AJP/1.3"`)
    lines.push(`               redirectPort="${config.enableSsl ? config.httpsPort : 8443}"`)
    lines.push(`               secretRequired="false"`)
    lines.push(`               />`)
    lines.push(``)
  }

  // HTTPS Connector
  if (config.enableSsl) {
    lines.push(`    <!-- HTTPS 连接器 -->`)
    lines.push(`    <Connector port="${config.httpsPort}"`)
    lines.push(`               protocol="org.apache.coyote.http11.Http11NioProtocol"`)
    lines.push(`               maxThreads="${config.maxThreads}"`)
    lines.push(`               SSLEnabled="true"`)
    lines.push(`               scheme="https"`)
    lines.push(`               secure="true">`)
    lines.push(`      <SSLHostConfig>`)
    lines.push(`        <Certificate certificateKeystoreFile="${config.keystoreFile}"`)
    lines.push(`                     certificateKeystorePassword="${config.keystorePass}"`)
    lines.push(`                     type="RSA" />`)
    lines.push(`      </SSLHostConfig>`)
    lines.push(`    </Connector>`)
    lines.push(``)
  }

  lines.push(`    <Engine name="Catalina" defaultHost="${config.defaultHost}">`)
  lines.push(``)
  lines.push(`      <Realm className="org.apache.catalina.realm.LockOutRealm">`)
  lines.push(`        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"`)
  lines.push(`               resourceName="UserDatabase"/>`)
  lines.push(`      </Realm>`)
  lines.push(``)
  lines.push(`      <Host name="${config.defaultHost}"`)
  lines.push(`            appBase="${config.appBase}"`)
  lines.push(`            unpackWARs="${config.unpackWARs}"`)
  lines.push(`            autoDeploy="${config.autoDeploy}"`)
  lines.push(`            deployOnStartup="${config.deployOnStartup}">`)
  lines.push(``)

  if (config.accessLogEnabled) {
    lines.push(`        <Valve className="org.apache.catalina.valves.AccessLogValve"`)
    lines.push(`               directory="logs"`)
    lines.push(`               prefix="localhost_access_log"`)
    lines.push(`               suffix=".txt"`)
    lines.push(`               pattern="${config.accessLogPattern}" />`)
  }

  lines.push(`      </Host>`)
  lines.push(`    </Engine>`)
  lines.push(`  </Service>`)
  lines.push(`</Server>`)

  // JVM args as comment
  if (config.enableJvmArgs) {
    lines.push(``)
    lines.push(`<!-- ======================== JVM 参数 (设置为 JAVA_OPTS 环境变量) ======================== -->`)
    lines.push(`<!--`)
    lines.push(`JAVA_OPTS="-Xms${config.xms} -Xmx${config.xmx} \\`)
    lines.push(`  -XX:MetaspaceSize=${config.metaspaceSize} -XX:MaxMetaspaceSize=${config.metaspaceSize} \\`)
    lines.push(`  ${config.gcType} \\`)
    lines.push(`  -Djava.awt.headless=true \\`)
    lines.push(`  -Dfile.encoding=UTF-8"`)
    lines.push(`-->`)
  }

  return lines.join('\n')
}
