import { Client, GatewayIntentBits, Events } from 'discord.js'
import { registerHandlers } from './handlers'
import { closeConnectionsForPlatform } from '@/remote-control/shared/nova-bridge'
import { BotLogger } from '@/remote-control/shared/logger'
import { ConfigManager, type ConfigChangeEvent } from '@/remote-control/config/manager'

let client: Client | null = null
let currentToken: string = ''
let startTime: number = 0
let messagesProcessed: number = 0
let lastError: Error | null = null

export interface BotStatus {
  platform: string
  status: 'connected' | 'disconnected' | 'connecting'
  uptime?: number
  messagesProcessed: number
  error?: string
}

export async function startBot(token: string): Promise<void> {
  if (!token) {
    const msg = 'Discord Bot Token 为空，跳过启动'
    console.warn(`[Discord Bot] ${msg}`)
    BotLogger.log({ platform: 'discord', eventType: 'error', severity: 'warning', message: msg })
    return
  }

  currentToken = token

  client = new Client({
    intents: [
      GatewayIntentBits.Guilds,
      GatewayIntentBits.GuildMessages,
      GatewayIntentBits.MessageContent,
    ],
  })

  client.once(Events.ClientReady, (readyClient) => {
    startTime = Date.now()
    lastError = null
    console.log(`[Discord Bot] 已登录: ${readyClient.user.tag}`)
    BotLogger.log({
      platform: 'discord',
      eventType: 'connection',
      severity: 'info',
      message: `Discord Bot 已连接，用户名: ${readyClient.user.tag}`,
    })
  })

  client.on('error', (err) => {
    lastError = err
    console.error('[Discord Bot] 运行时错误:', err.message)
    BotLogger.log({
      platform: 'discord',
      eventType: 'error',
      severity: 'error',
      message: `Discord Bot 运行时错误: ${err.message}`,
    })
  })

  client.on('disconnect', () => {
    console.warn('[Discord Bot] 连接断开')
    BotLogger.log({
      platform: 'discord',
      eventType: 'disconnection',
      severity: 'warning',
      message: 'Discord Bot 连接断开',
    })
  })

  registerHandlers(client, () => { messagesProcessed++ })

  try {
    await client.login(token)
  } catch (err) {
    const error = err instanceof Error ? err : new Error(String(err))
    lastError = error
    client = null
    currentToken = ''
    console.error('[Discord Bot] 登录失败:', error.message)
    BotLogger.log({
      platform: 'discord',
      eventType: 'error',
      severity: 'error',
      message: `Discord Bot 登录失败: ${error.message}`,
      details: { hint: '请检查 Bot Token 是否正确，以及是否已在 Discord Developer Portal 中启用了 Bot' },
    })
    throw error
  }
}

export async function stopBot(): Promise<void> {
  closeConnectionsForPlatform('discord')
  if (client) {
    client.destroy()
    client = null
    currentToken = ''
    startTime = 0
    console.log('[Discord Bot] 已停止')
    BotLogger.log({
      platform: 'discord',
      eventType: 'disconnection',
      severity: 'info',
      message: 'Discord Bot 已停止',
    })
  }
}

export function getStatus(): BotStatus {
  return {
    platform: 'discord',
    status: client ? 'connected' : 'disconnected',
    uptime: client && startTime ? Math.floor((Date.now() - startTime) / 1000) : undefined,
    messagesProcessed,
    error: lastError?.message,
  }
}

// 监听配置变更
const configManager = ConfigManager.getInstance()
configManager.on('config-changed', async (event: ConfigChangeEvent) => {
  const { newConfig } = event
  const platformConfig = newConfig.discord

  try {
    if (platformConfig.enabled && !client) {
      await startBot(platformConfig.botToken)
    } else if (!platformConfig.enabled && client) {
      await stopBot()
    } else if (platformConfig.enabled && client) {
      if (platformConfig.botToken !== currentToken) {
        await stopBot()
        await startBot(platformConfig.botToken)
      }
    }
    lastError = null
  } catch (error) {
    lastError = error instanceof Error ? error : new Error(String(error))
    BotLogger.log({
      platform: 'discord',
      eventType: 'error',
      severity: 'error',
      message: `配置变更处理失败: ${lastError.message}`,
    })
  }
})
