import http from './http'
import storage from './storage'
import device from './device'
import identity from './identity'
import session from './session'
import queue from './queue'
import { RESERVED_EVENTS } from './constants'

/**
 * PostHog Analytics 核心类
 */
class PostHogCore {
  constructor() {
    this.initialized = false
    this.config = null
    this.debug = false
    this.superProperties = {} // 全局公共属性
  }

  /**
   * 初始化SDK
   */
  init(config) {
    if (this.initialized) {
      this._log('Already initialized')
      return this
    }

    this.config = config
    this.debug = config.debug || false

    // 初始化各模块
    http.init(config)
    device.init()
    identity.init()
    session.init(config)
    queue.init(config)

    this.initialized = true
    this._log('Initialized with config:', config)

    return this
  }

  /**
   * 开始会话（小程序启动/恢复时调用）
   */
  startSession() {
    const result = session.start()

    if (result.isNewSession) {
      this.track('session_start', {
        session_id: result.sessionId,
      })
    }

    return result
  }

  /**
   * 结束会话（小程序退出/挂起时调用）
   */
  endSession() {
    const result = session.end()

    if (result) {
      this.track('session_end', {
        session_id: result.sessionId,
        session_duration: result.duration,
      })

      // 强制刷新队列
      queue.forceFlush()
    }

    return result
  }

  /**
   * 设置用户标识（登录时调用）
   */
  identify(userId, userProperties = {}) {
    this._checkInit()

    const identifyData = identity.identify(userId, userProperties)

    // 发送$identify事件
    const event = {
      event: RESERVED_EVENTS.IDENTIFY,
      distinct_id: identifyData.distinctId,
      properties: {
        ...this._getCommonProperties(),
        ...identifyData.properties,
      },
      timestamp: new Date().toISOString(),
    }

    queue.add(event)
    this._log('User identified:', userId)

    return this
  }

  /**
   * 重置用户标识（登出时调用）
   */
  reset() {
    this._checkInit()

    identity.reset()
    session.reset()
    this.superProperties = {}

    this._log('User reset')

    return this
  }

  /**
   * 追踪事件
   */
  track(eventName, properties = {}) {
    this._checkInit()

    const event = {
      event: eventName,
      distinct_id: identity.getDistinctId(),
      properties: {
        ...this._getCommonProperties(),
        ...this.superProperties,
        ...properties,
      },
      timestamp: new Date().toISOString(),
    }

    queue.add(event)
    this._log('Event tracked:', eventName, properties)

    return this
  }

  /**
   * 追踪页面浏览
   */
  trackPageView(pagePath, pageTitle = '', properties = {}) {
    return this.track(RESERVED_EVENTS.PAGE_VIEW, {
      $current_url: pagePath,
      $title: pageTitle,
      page_path: pagePath,
      page_title: pageTitle,
      ...properties,
    })
  }

  /**
   * 追踪页面离开
   */
  trackPageLeave(pagePath, duration = 0, properties = {}) {
    return this.track(RESERVED_EVENTS.PAGE_LEAVE, {
      $current_url: pagePath,
      page_path: pagePath,
      duration: duration,
      ...properties,
    })
  }

  /**
   * 设置全局公共属性
   */
  setSuperProperties(properties) {
    this.superProperties = {
      ...this.superProperties,
      ...properties,
    }

    return this
  }

  /**
   * 清除全局公共属性
   */
  clearSuperProperties() {
    this.superProperties = {}
    return this
  }

  /**
   * 设置用户属性
   */
  setUserProperties(properties) {
    this._checkInit()

    identity.setUserProperties(properties)

    // 发送更新用户属性的事件
    this.track(RESERVED_EVENTS.IDENTIFY, {
      $set: properties,
    })

    return this
  }

  /**
   * 设置仅首次生效的用户属性
   */
  setUserPropertiesOnce(properties) {
    this._checkInit()

    this.track(RESERVED_EVENTS.IDENTIFY, {
      $set_once: properties,
    })

    return this
  }

  /**
   * 获取公共属性
   */
  _getCommonProperties() {
    const deviceProps = device.getProperties()
    const sessionInfo = session.getInfo()

    return {
      ...deviceProps,
      session_id: sessionInfo.sessionId,
      $timestamp: new Date().toISOString(),
    }
  }

  /**
   * 更新活跃时间
   */
  touch() {
    session.touch()
    return this
  }

  /**
   * 强制刷新事件队列
   */
  flush() {
    queue.flush()
    return this
  }

  /**
   * 获取当前用户ID
   */
  getDistinctId() {
    return identity.getDistinctId()
  }

  /**
   * 获取会话ID
   */
  getSessionId() {
    return session.getSessionId()
  }

  /**
   * 检查是否已初始化
   */
  _checkInit() {
    if (!this.initialized) {
      console.warn('[PostHog] SDK not initialized. Call init() first.')
    }
  }

  /**
   * 调试日志
   */
  _log(...args) {
    if (this.debug) {
      console.log('[PostHog Core]', ...args)
    }
  }

  /**
   * 销毁SDK
   */
  destroy() {
    queue.destroy()
    this.initialized = false
    this._log('Destroyed')
  }
}

// 导出单例
export default new PostHogCore()