import { isElectron } from '@/utils/electronBridge'

const HOST_LIST_MIN_COUNT_KEY = 'host_list_dialog_min_count'
const HOST_LIST_GATE_ENABLED_SESSION_KEY = 'host_list_dialog_gate_enabled_session'
const HOST_LIST_GATE_STATE_SESSION_KEY = 'host_list_dialog_gate_state_session'
const HOST_LIST_MONITOR_INTERVAL_MS = 30000

let monitorTimer = null
let syncPromise = null

function getElectronAPI() {
  if (typeof window === 'undefined') return null
  return window.electronAPI || null
}

function getGateEnabled() {
  if (typeof window === 'undefined') return false
  return sessionStorage.getItem(HOST_LIST_GATE_ENABLED_SESSION_KEY) === 'true'
}

function getLowerLimit() {
  if (typeof window === 'undefined') return 5
  const raw = Number(localStorage.getItem(HOST_LIST_MIN_COUNT_KEY))
  return Number.isFinite(raw) && raw >= 0 ? raw : 5
}

function getPersistedGateState() {
  if (typeof window === 'undefined') return null
  const raw = sessionStorage.getItem(HOST_LIST_GATE_STATE_SESSION_KEY)
  if (raw === 'true') return true
  if (raw === 'false') return false
  return null
}

function persistGateState(value) {
  if (typeof window === 'undefined') return
  if (value === null || value === undefined) {
    sessionStorage.removeItem(HOST_LIST_GATE_STATE_SESSION_KEY)
    return
  }

  sessionStorage.setItem(HOST_LIST_GATE_STATE_SESSION_KEY, String(value))
}

function getFilteredHostCount(hosts, filters) {
  const excludedLevels = Array.isArray(filters?.hostsLevelList) ? filters.hostsLevelList : []
  const minOnlineFans = Number(filters?.minOnlineFans) || 0
  const maxOnlineFans = Number(filters?.maxOnlineFans) || 0

  return hosts.filter((host) => {
    if (filters?.gold === false && host.invitationType === 2) return false
    if (filters?.ordinary === false && host.invitationType === 1) return false

    if (minOnlineFans > 0 && host.onlineFans !== undefined && host.onlineFans < minOnlineFans) {
      return false
    }

    if (maxOnlineFans > 0 && host.onlineFans !== undefined && host.onlineFans > maxOnlineFans) {
      return false
    }

    if (excludedLevels.length > 0 && host.hostsLevel && excludedLevels.includes(host.hostsLevel)) {
      return false
    }

    return true
  }).length
}

export async function syncHostListGateDecision(forceSync = false) {
  if (!isElectron()) return
  if (!getGateEnabled()) return
  if (syncPromise) return syncPromise

  const electronAPI = getElectronAPI()
  if (!electronAPI?.getAutomationConfig || !electronAPI?.loadAnchorData || !electronAPI?.tk?.controlCheckTask) {
    return
  }

  syncPromise = (async () => {
    const config = await electronAPI.getAutomationConfig()
    const hosts = await electronAPI.loadAnchorData()
    const filters = config?.filters || {}
    const hostCount = getFilteredHostCount(hosts || [], filters)
    const upperLimit = Number(filters.maxAnchorCount)
    const lowerLimit = getLowerLimit()
    const lastGateState = getPersistedGateState()

    let nextState = null

    if (Number.isFinite(upperLimit) && upperLimit >= 0 && hostCount >= upperLimit) {
      nextState = false
    } else if (Number.isFinite(lowerLimit) && lowerLimit >= 0 && hostCount < lowerLimit) {
      nextState = true
    } else if (lastGateState !== null) {
      nextState = lastGateState
    } else if (forceSync) {
      nextState = true
    }

    if (nextState === null) return
    if (!forceSync && lastGateState === nextState) return

    const result = await electronAPI.tk.controlCheckTask({
      isRunning: Boolean(nextState),
      model: true
    })

    if (result?.success === false) {
      console.error('[HostListGateMonitor] controlCheckTask 调用失败:', result.error)
      return
    }

    persistGateState(nextState)
    console.log('[HostListGateMonitor] 门控状态已更新:', nextState, '当前数量:', hostCount)
  })().catch((error) => {
    console.error('[HostListGateMonitor] 同步门控状态失败:', error)
  }).finally(() => {
    syncPromise = null
  })

  return syncPromise
}

export function ensureHostListGateMonitorRunning() {
  if (!isElectron()) return
  if (monitorTimer) return

  monitorTimer = setInterval(() => {
    if (!getGateEnabled()) {
      stopHostListGateMonitor()
      return
    }

    void syncHostListGateDecision()
  }, HOST_LIST_MONITOR_INTERVAL_MS)
}

export function stopHostListGateMonitor() {
  if (!monitorTimer) return
  clearInterval(monitorTimer)
  monitorTimer = null
}
