/**
 * Audit 审计日志插件
 * 记录所有操作日志，支持日志查询和统计
 */

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

class AuditPlugin extends Plugin {
  constructor(config = {}) {
    super()
    this.name = 'audit'
    this.version = '1.0.0'
    this.description = '审计日志插件，记录工具调用、技能执行、错误信息等操作历史'
    this.priority = 20
    this.system = true 

    this.config = {
      maxLogs: config.maxLogs || 1000,
      retentionDays: config.retentionDays || 30,
      logDir: config.logDir || '.agent/logs'
    }

    this._framework = null
    this._logs = []
    this._logIdCounter = 0
  }

  install(framework) {
    this._framework = framework

    // 监听框架事件
    // tool:call 和 tool-call 两种格式都监听（兼容不同来源）
    framework.on('tool:call', (data) => this._log('tool_call', data))
    framework.on('tool-call', (data) => this._log('tool_call', data))
    framework.on('tool:result', (data) => this._log('tool_result', data))
    framework.on('tool:error', (data) => this._log('tool_error', data))
    framework.on('agent:message', (data) => this._log('agent_message', data))

    return this
  }

  start(framework) {
    // 注册审计查询工具
    framework.registerTool({
      name: 'audit_query',
      description: '查询审计日志',
      inputSchema: z.object({
        type: z.string().optional().describe('日志类型: tool_call, tool_result, tool_error, agent_message'),
        limit: z.number().optional().describe('返回数量限制，默认 50'),
        offset: z.number().optional().describe('偏移量，默认 0')
      }),
      execute: async (args) => {
        let logs = this._logs

        if (args.type) {
          logs = logs.filter(log => log.type === args.type)
        }

        const offset = args.offset || 0
        const limit = args.limit || 50

        return {
          success: true,
          logs: logs.slice(-limit - offset, logs.length - offset),
          total: logs.length,
          offset,
          limit
        }
      }
    })

    framework.registerTool({
      name: 'audit_stats',
      description: '获取审计统计信息',
      inputSchema: z.object({}),
      execute: async () => {
        const stats = this.getStats()
        return {
          success: true,
          stats
        }
      }
    })

    framework.registerTool({
      name: 'audit_export',
      description: '导出审计日志',
      inputSchema: z.object({
        format: z.string().optional().describe('导出格式: json (默认), csv'),
        type: z.string().optional().describe('日志类型过滤'),
        startDate: z.string().optional().describe('开始日期 ISO 格式'),
        endDate: z.string().optional().describe('结束日期 ISO 格式')
      }),
      execute: async (args) => {
        const result = this.exportLogs(args)
        return {
          success: true,
          count: result.logs.length,
          data: result.logs
        }
      }
    })

    return this
  }

  /**
   * 记录日志
   * @private
   */
  _log(type, data) {
    const log = {
      id: ++this._logIdCounter,
      type,
      data,
      timestamp: new Date()
    }

    this._logs.push(log)

    // 限制日志数量
    if (this._logs.length > this.config.maxLogs) {
      this._logs = this._logs.slice(-this.config.maxLogs)
    }

    return log
  }

  /**
   * 获取统计信息
   */
  getStats() {
    const counts = {}
    for (const log of this._logs) {
      counts[log.type] = (counts[log.type] || 0) + 1
    }

    return {
      total: this._logs.length,
      maxLogs: this.config.maxLogs,
      counts,
      oldest: this._logs.length > 0 ? this._logs[0].timestamp : null,
      newest: this._logs.length > 0 ? this._logs[this._logs.length - 1].timestamp : null
    }
  }

  /**
   * 导出日志
   */
  exportLogs(options = {}) {
    let logs = [...this._logs]

    // 按类型过滤
    if (options.type) {
      logs = logs.filter(log => log.type === options.type)
    }

    // 按日期过滤
    if (options.startDate) {
      const start = new Date(options.startDate)
      logs = logs.filter(log => log.timestamp >= start)
    }

    if (options.endDate) {
      const end = new Date(options.endDate)
      logs = logs.filter(log => log.timestamp <= end)
    }

    return { logs }
  }

  /**
   * 手动记录日志
   */
  log(type, data) {
    return this._log(type, data)
  }

  reload(framework) {
    this._framework = framework
  }

  uninstall(framework) {
    this._logs = []
    this._framework = null
  }
}

module.exports = AuditPlugin