import { contentCleaner } from '@/utils/contentCleaner'
import { request } from '@/utils/request'

// 内容清洗质量监控
export const cleanMonitor = {
  // 清洗并记录质量
  cleanAndMonitor(content, chapterId) {
    const startTime = Date.now()
    const originalLength = content.length
    
    // 执行清洗
    const cleanedContent = contentCleaner.clean(content)
    const cleanedLength = cleanedContent.length
    
    // 计算清洗指标
    const metrics = {
      chapterId,
      originalLength,
      cleanedLength,
      reductionRate: (originalLength - cleanedLength) / originalLength,
      timeCost: Date.now() - startTime,
      timestamp: new Date().toISOString()
    }
    
    // 记录到本地
    this.logLocal(metrics)
    
    // 异步上报到服务器
    this.reportMetrics(metrics)
    
    return cleanedContent
  },
  
  // 本地日志记录
  logLocal(metrics) {
    const logs = uni.getStorageSync('cleanLogs') || []
    logs.push(metrics)
    
    // 最多保留100条记录
    if (logs.length > 100) {
      logs.shift()
    }
    
    uni.setStorageSync('cleanLogs', logs)
  },
  
  // 上报到服务器
  async reportMetrics(metrics) {
    try {
      await request({
        url: '/monitor/clean',
        method: 'POST',
        data: metrics,
        headers: {
          'Content-Type': 'application/json'
        }
      })
    } catch (e) {
      console.error('清洗指标上报失败', e)
    }
  },
  
  // 获取本地日志
  getLocalLogs() {
    return uni.getStorageSync('cleanLogs') || []
  }
}