// 自定义 Console 类
// 与 Vue 实例的 logger 对齐：支持按路径配置开关、输出前缀；业务逻辑中 log.xx 使用 Expression 序列化
import Expression from '../core/Expression'
import { isLogEnabled } from '@vue2-client/utils/logger'

export default class LogicConsole {
  constructor () {
    if (LogicConsole.instance) {
      return LogicConsole.instance
    }
    LogicConsole.instance = this
  }

  static getInstance () {
    if (!LogicConsole.instance) {
      LogicConsole.instance = new LogicConsole()
    }
    return LogicConsole.instance
  }

  /**
   * 带路径与配置检查的输出（供 createLogger 使用）
   * @param {string} level - 'log' | 'debug' | 'info' | 'warn' | 'error'
   * @param {string} logPath - 日志路径，如 'logic.xxx'
   * @param {*[]} args - 参数，会经 convert 序列化
   */
  _output (level, logPath, ...args) {
    if (!isLogEnabled(logPath)) return
    const prefix = `log[${logPath}]:`
    const newArgs = this.convert(args)
    const consoleMethod = console[level] || console.log
    consoleMethod(prefix, ...newArgs)
  }

  debug (...args) {
    const newArgs = this.convert(args)
    console.debug(...newArgs)
  }

  info (...args) {
    const newArgs = this.convert(args)
    console.info(...newArgs)
  }

  warn (...args) {
    const newArgs = this.convert(args)
    console.warn(...newArgs)
  }

  error (...args) {
    const newArgs = this.convert(args)
    console.error(...newArgs)
  }

  /** 与 Vue logger 一致：log 对应 console.log */
  log (...args) {
    const newArgs = this.convert(args)
    console.log(...newArgs)
  }

  /**
   * 创建带路径的 logger，与 Vue 实例的 logger 行为一致：
   * 从 logger.config.js / config.js 读取配置按路径开关，输出带 log[path]: 前缀，参数经 Expression 序列化。
   * 业务逻辑中应使用此方法传入 logicName，便于按 logic 控制日志。
   * @param {string} logPath - 日志路径，如 'logic.aiDiagnosis' 或 'logic.xxx'
   * @returns {{ log: Function, debug: Function, info: Function, warn: Function, error: Function }}
   */
  static createLogger (logPath) {
    const path = typeof logPath === 'string' && logPath ? logPath : 'logic'
    const instance = LogicConsole.getInstance()
    return {
      log: (...args) => instance._output('log', path, ...args),
      debug: (...args) => instance._output('debug', path, ...args),
      info: (...args) => instance._output('info', path, ...args),
      warn: (...args) => instance._output('warn', path, ...args),
      error: (...args) => instance._output('error', path, ...args),
    }
  }

  convert (args) {
    return args.map(obj => {
      return Expression.toJSONString(obj)
    })
  }
}
