import { App, LogLevel } from '@slack/bolt'
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 app: App | null = null
let currentBotToken: string = ''
let currentAppToken: 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(botToken: string, appToken: string): Promise<void> {
  // Trim tokens to avoid ERR_INVALID_CHAR in HTTP headers
  botToken = botToken.trim()
  appToken = appToken.trim()

  if (!botToken || !appToken) {
    const msg = 'Slack Bot Token 或 App Token 为空，跳过启动'
    console.warn(`[Slack Bot] ${msg}`)
    BotLogger.log({ platform: 'slack', eventType: 'error', severity: 'warning', message: msg })
    return
  }

  // Idempotent check
  if (app && currentBotToken === botToken && currentAppToken === appToken) {
    console.log('[Slack Bot] 已有活跃连接，跳过重复启动')
    return
  }

  // Stop old connection if credentials changed
  if (app) {
    console.log('[Slack Bot] 凭据已变更，先停止旧连接')
    await stopBot()
  }

  currentBotToken = botToken
  currentAppToken = appToken

  try {
    app = new App({
      token: botToken,
      socketMode: true,
      appToken,
      logLevel: LogLevel.INFO,
    })

    registerHandlers(app, botToken, () => { messagesProcessed++ })

    await app.start()

    startTime = Date.now()
    lastError = null
    console.log('[Slack Bot] 已启动，等待消息...')
    BotLogger.log({
      platform: 'slack',
      eventType: 'connection',
      severity: 'info',
      message: 'Slack Bot 已启动 (Socket Mode)',
    })
  } catch (err) {
    const error = err instanceof Error ? err : new Error(String(err))
    lastError = error
    app = null
    currentBotToken = ''
    currentAppToken = ''
    console.error('[Slack Bot] 启动失败:', error.message)
    BotLogger.log({
      platform: 'slack',
      eventType: 'error',
      severity: 'error',
      message: `Slack Bot 启动失败: ${error.message}`,
      details: { hint: '请检查 Bot Token 和 App Token 是否正确，以及是否已启用 Socket Mode' },
    })
    throw error
  }
}

export async function stopBot(): Promise<void> {
  closeConnectionsForPlatform('slack')
  if (app) {
    await app.stop()
    app = null
    currentBotToken = ''
    currentAppToken = ''
    startTime = 0
    console.log('[Slack Bot] 已停止')
    BotLogger.log({
      platform: 'slack',
      eventType: 'disconnection',
      severity: 'info',
      message: 'Slack Bot 已停止',
    })
  }
}

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

// Listen for config changes
const configManager = ConfigManager.getInstance()
configManager.on('config-changed', async (event: ConfigChangeEvent) => {
  const { newConfig } = event
  const platformConfig = newConfig.slack

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