import { MockSimulatorDebugLogger, type MockSimulatorDebugLogLevel } from '../engine/debug/mockSimulatorDebugLogger'

const DEBUG_MOCK_CHANNEL_ID_STORAGE_KEY = 'cmr.debug.mockChannelId.v1'
const DEBUG_MOCK_AUTO_CONNECT_STORAGE_KEY = 'cmr.debug.autoConnectMockSources.v1'
const DEBUG_MOCK_LOG_URL_STORAGE_KEY = 'cmr.debug.logBridgeUrl.v1'
const DEFAULT_DEBUG_LOG_URL = 'wss://gs.gotomars.xyz/debug-log'

let globalMockDebugLogger: MockSimulatorDebugLogger | null = null

function ensureLogger(): MockSimulatorDebugLogger {
  if (!globalMockDebugLogger) {
    globalMockDebugLogger = new MockSimulatorDebugLogger()
  }
  return globalMockDebugLogger
}

export function loadStoredMockChannelIdForGlobalDebug(): string {
  try {
    const value = wx.getStorageSync(DEBUG_MOCK_CHANNEL_ID_STORAGE_KEY)
    if (typeof value === 'string' && value.trim().length > 0) {
      return value.trim()
    }
  } catch (_error) {
    // Ignore storage read failures and fall back to default.
  }
  return 'default'
}

export function loadMockAutoConnectEnabledForGlobalDebug(): boolean {
  try {
    return wx.getStorageSync(DEBUG_MOCK_AUTO_CONNECT_STORAGE_KEY) === true
  } catch (_error) {
    return false
  }
}

export function loadStoredMockDebugLogBridgeUrl(): string {
  try {
    const value = wx.getStorageSync(DEBUG_MOCK_LOG_URL_STORAGE_KEY)
    if (typeof value === 'string' && value.trim().length > 0) {
      return value.trim()
    }
  } catch (_error) {
    // Ignore storage read failures and fall back to default.
  }
  return DEFAULT_DEBUG_LOG_URL
}

export function persistStoredMockDebugLogBridgeUrl(url: string) {
  try {
    wx.setStorageSync(DEBUG_MOCK_LOG_URL_STORAGE_KEY, url)
  } catch (_error) {
    // Ignore storage write failures.
  }
}

export function syncGlobalMockDebugBridgeFromStorage(): void {
  const logger = ensureLogger()
  logger.setChannelId(loadStoredMockChannelIdForGlobalDebug())
  logger.setUrl(loadStoredMockDebugLogBridgeUrl())
  logger.setEnabled(loadMockAutoConnectEnabledForGlobalDebug())
}

export function setGlobalMockDebugBridgeChannelId(channelId: string): void {
  const logger = ensureLogger()
  logger.setChannelId(channelId)
}

export function setGlobalMockDebugBridgeEnabled(enabled: boolean): void {
  const logger = ensureLogger()
  logger.setEnabled(enabled)
}

export function setGlobalMockDebugBridgeUrl(url: string): void {
  const logger = ensureLogger()
  logger.setUrl(url)
}

export function emitGlobalMockDebugLog(
  scope: string,
  level: MockSimulatorDebugLogLevel,
  message: string,
  payload?: Record<string, unknown>,
): void {
  const logger = ensureLogger()
  logger.log(scope, level, message, payload)
}

