/**
 * System Info Plugin - 获取系统信息插件
 * 提供 CPU、内存、操作系统、磁盘、网络等系统信息查询功能
 */

const { Plugin } = require('../../../src/core/plugin-base')
const { z } = require('zod')
const os = require('os')
const { execSync } = require('child_process')

class SystemInfoPlugin extends Plugin {
  constructor(config = {}) {
    super()
    this.name = 'system-info'
    this.version = '1.0.0'
    this.description = '获取系统信息插件 - 提供 CPU、内存、操作系统、磁盘、网络等系统信息查询功能'
    this.priority = 10
  }

  install(framework) {
    super.install(framework)
    this._registerTools()
    return this
  }

  _registerTools() {
    const framework = this._framework

    // 获取简略系统信息
    framework.registerTool({
      name: 'get_basic_info',
      description: '获取简略系统信息，包括主机名、操作系统、平台、架构、运行时间等基本信息',
      inputSchema: z.object({}),
      execute: async (args, framework) => {
        const uptime = os.uptime()
        const uptimeStr = this.formatUptime(uptime)
        
        return {
          success: true,
          data: {
            hostname: os.hostname(),
            platform: os.platform(),
            osType: os.type(),
            osRelease: os.release(),
            arch: os.arch(),
            nodeVersion: process.version,
            processUptime: uptimeStr,
            totalMemory: this.formatBytes(os.totalmem()),
            cpuCount: os.cpus().length,
            cpuModel: os.cpus()[0]?.model || 'Unknown'
          }
        }
      }
    })

    // 获取 CPU 详细信息
    framework.registerTool({
      name: 'get_cpu_info',
      description: '获取 CPU 详细信息，包括每个核心的频率、使用率等',
      inputSchema: z.object({}),
      execute: async (args, framework) => {
        const cpus = os.cpus()
        const cpuInfo = cpus.map((cpu, index) => ({
          core: index,
          model: cpu.model,
          speed: `${cpu.speed} MHz`,
          times: {
            user: this.formatMs(cpu.times.user),
            nice: this.formatMs(cpu.times.nice),
            sys: this.formatMs(cpu.times.sys),
            idle: this.formatMs(cpu.times.idle),
            irq: this.formatMs(cpu.times.irq)
          }
        }))

        // 计算平均 CPU 使用率
        const avgUsage = this.calculateCpuUsage(cpus)
        
        return {
          success: true,
          data: {
            cpuCount: cpus.length,
            totalCores: cpus.length,
            averageUsage: avgUsage,
            cores: cpuInfo
          }
        }
      }
    })

    // 获取内存信息
    framework.registerTool({
      name: 'get_memory_info',
      description: '获取内存使用信息，包括总内存、已用内存、可用内存、使用率等',
      inputSchema: z.object({}),
      execute: async (args, framework) => {
        const totalMem = os.totalmem()
        const freeMem = os.freemem()
        const usedMem = totalMem - freeMem
        const usagePercent = ((usedMem / totalMem) * 100).toFixed(2)

        return {
          success: true,
          data: {
            total: this.formatBytes(totalMem),
            free: this.formatBytes(freeMem),
            used: this.formatBytes(usedMem),
            usagePercent: `${usagePercent}%`,
            details: {
              totalBytes: totalMem,
              freeBytes: freeMem,
              usedBytes: usedMem
            }
          }
        }
      }
    })

    // 获取网络接口信息
    framework.registerTool({
      name: 'get_network_info',
      description: '获取网络接口信息，包括 IP 地址、MAC 地址、网络类型等',
      inputSchema: z.object({}),
      execute: async (args, framework) => {
        const interfaces = os.networkInterfaces()
        const networkInfo = {}

        for (const [name, addrs] of Object.entries(interfaces)) {
          const addrList = addrs.map(addr => ({
            address: addr.address,
            family: addr.family,
            mac: addr.mac,
            internal: addr.internal,
            netmask: addr.netmask
          }))
          networkInfo[name] = addrList
        }

        return {
          success: true,
          data: {
            interfaces: networkInfo,
            hostname: os.hostname()
          }
        }
      }
    })

    // 获取磁盘信息
    framework.registerTool({
      name: 'get_disk_info',
      description: '获取磁盘使用信息，包括各磁盘的总容量、已用空间、可用空间、使用率',
      inputSchema: z.object({
        platform: z.enum(['windows', 'linux', 'darwin', 'auto']).optional().describe('操作系统平台，auto 为自动检测')
      }),
      execute: async (args, framework) => {
        const diskInfo = []
        const currentPlatform = args.platform === 'auto' ? os.platform() : (args.platform || os.platform())

        try {
          if (currentPlatform === 'win32') {
            // Windows 系统
            const output = execSync('wmic logicaldisk get size,freespace,caption', { encoding: 'utf8', timeout: 5000 })
            const lines = output.trim().split('\n').slice(1)
            
            for (const line of lines) {
              const parts = line.trim().split(/\s+/)
              if (parts.length >= 3) {
                const caption = parts[0]
                const freeSpace = parseInt(parts[1]) || 0
                const size = parseInt(parts[2]) || 0
                const used = size - freeSpace
                const usagePercent = size > 0 ? ((used / size) * 100).toFixed(2) : 0
                
                diskInfo.push({
                  filesystem: caption,
                  total: this.formatBytes(size),
                  used: this.formatBytes(used),
                  free: this.formatBytes(freeSpace),
                  usagePercent: `${usagePercent}%`,
                  details: {
                    totalBytes: size,
                    usedBytes: used,
                    freeBytes: freeSpace
                  }
                })
              }
            }
          } else if (currentPlatform === 'linux') {
            // Linux 系统
            const output = execSync('df -B1 --output=source,size,used,avail -x tmpfs -x devtmpfs -x squashfs 2>/dev/null || df -B1', { encoding: 'utf8', timeout: 5000 })
            const lines = output.trim().split('\n').slice(1)
            
            for (const line of lines) {
              const parts = line.trim().split(/\s+/)
              if (parts.length >= 4) {
                const filesystem = parts[0]
                const size = parseInt(parts[1]) || 0
                const used = parseInt(parts[2]) || 0
                const free = parseInt(parts[3]) || 0
                const usagePercent = size > 0 ? ((used / size) * 100).toFixed(2) : 0
                
                // 过滤掉虚拟文件系统
                if (!filesystem.startsWith('/dev') && !filesystem.startsWith('/sys') && !filesystem.startsWith('/proc')) {
                  continue
                }
                
                diskInfo.push({
                  filesystem,
                  total: this.formatBytes(size),
                  used: this.formatBytes(used),
                  free: this.formatBytes(free),
                  usagePercent: `${usagePercent}%`,
                  details: {
                    totalBytes: size,
                    usedBytes: used,
                    freeBytes: free
                  }
                })
              }
            }
          } else if (currentPlatform === 'darwin') {
            // macOS 系统
            const output = execSync('df -B1', { encoding: 'utf8', timeout: 5000 })
            const lines = output.trim().split('\n').slice(1)
            
            for (const line of lines) {
              const parts = line.trim().split(/\s+/)
              if (parts.length >= 6) {
                const filesystem = parts[0]
                const size = parseInt(parts[1]) || 0
                const used = parseInt(parts[2]) || 0
                const free = parseInt(parts[3]) || 0
                const usagePercent = size > 0 ? ((used / size) * 100).toFixed(2) : 0
                
                diskInfo.push({
                  filesystem,
                  total: this.formatBytes(size),
                  used: this.formatBytes(used),
                  free: this.formatBytes(free),
                  usagePercent: `${usagePercent}%`,
                  details: {
                    totalBytes: size,
                    usedBytes: used,
                    freeBytes: free
                  }
                })
              }
            }
          }
        } catch (error) {
          return {
            success: false,
            error: `获取磁盘信息失败: ${error.message}`,
            data: []
          }
        }

        return {
          success: true,
          platform: currentPlatform,
          data: diskInfo
        }
      }
    })

    // 获取完整系统信息（综合）
    framework.registerTool({
      name: 'get_full_system_info',
      description: '获取完整的系统信息，包括 CPU、内存、磁盘、网络等所有信息',
      inputSchema: z.object({}),
      execute: async (args, framework) => {
        const uptime = os.uptime()
        
        // CPU 信息
        const cpus = os.cpus()
        const avgUsage = this.calculateCpuUsage(cpus)
        
        // 内存信息
        const totalMem = os.totalmem()
        const freeMem = os.freemem()
        const usedMem = totalMem - freeMem
        const memUsagePercent = ((usedMem / totalMem) * 100).toFixed(2)
        
        // 网络信息
        const networkInterfaces = os.networkInterfaces()
        
        // 磁盘信息
        let diskInfo = []
        try {
          const diskResult = await framework.callTool('get_disk_info', {})
          diskInfo = diskResult.data || []
        } catch (e) {
          diskInfo = []
        }

        return {
          success: true,
          data: {
            system: {
              hostname: os.hostname(),
              platform: os.platform(),
              osType: os.type(),
              osRelease: os.release(),
              arch: os.arch(),
              nodeVersion: process.version,
              uptime: this.formatUptime(uptime)
            },
            cpu: {
              count: cpus.length,
              model: cpus[0]?.model || 'Unknown',
              averageUsage: avgUsage,
              speed: `${cpus[0]?.speed || 'N/A'} MHz`
            },
            memory: {
              total: this.formatBytes(totalMem),
              free: this.formatBytes(freeMem),
              used: this.formatBytes(usedMem),
              usagePercent: `${memUsagePercent}%`
            },
            disk: diskInfo,
            network: {
              interfacesCount: Object.keys(networkInterfaces).length,
              interfaces: Object.keys(networkInterfaces)
            }
          }
        }
      }
    })
  }

  // 格式化字节数
  formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化毫秒
  formatMs(ms) {
    return `${(ms / 1000).toFixed(2)}s`
  }

  // 格式化运行时间
  formatUptime(seconds) {
    const days = Math.floor(seconds / 86400)
    const hours = Math.floor((seconds % 86400) / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = Math.floor(seconds % 60)
    
    const parts = []
    if (days > 0) parts.push(`${days} 天`)
    if (hours > 0) parts.push(`${hours} 小时`)
    if (minutes > 0) parts.push(`${minutes} 分钟`)
    if (secs > 0 || parts.length === 0) parts.push(`${secs} 秒`)
    
    return parts.join(' ')
  }

  // 计算 CPU 使用率
  calculateCpuUsage(cpus) {
    let totalIdle = 0
    let totalTick = 0
    
    cpus.forEach(cpu => {
      for (const type in cpu.times) {
        totalTick += cpu.times[type]
      }
      totalIdle += cpu.times.idle
    })
    
    const idle = totalIdle / cpus.length
    const total = totalTick / cpus.length
    const usage = ((total - idle) / total * 100).toFixed(2)
    
    return `${usage}%`
  }

  uninstall(framework) {
    // 清理资源
    this._framework = null
  }
}

module.exports =SystemInfoPlugin
