import * as lark from '@larksuiteoapi/node-sdk'
import { createEventHandler } 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: lark.Client | null = null
let wsClient: lark.WSClient | null = null
let currentAppId: string = ''
let currentAppSecret: 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(appId: string, appSecret: string): Promise<void> {
  if (!appId || !appSecret) {
    const msg = '飞书 App ID 或 App Secret 为空，跳过启动'
    console.warn(`[Lark Bot] ${msg}`)
    BotLogger.log({ platform: 'lark', eventType: 'error', severity: 'warning', message: msg })
    return
  }

  // 幂等检查：如果已有活跃连接且凭据未变，直接跳过
  if (wsClient && currentAppId === appId && currentAppSecret === appSecret) {
    console.log('[Lark Bot] 已有活跃连接，跳过重复启动')
    return
  }

  // 如果已有旧连接（凭据变更），先停止
  if (wsClient) {
    console.log('[Lark Bot] 凭据已变更，先停止旧连接')
    await stopBot()
  }

  currentAppId = appId
  currentAppSecret = appSecret

  try {
    client = new lark.Client({ appId, appSecret })

    wsClient = new lark.WSClient({
      appId,
      appSecret,
      loggerLevel: lark.LoggerLevel.info,
    })

    const eventHandler = createEventHandler(client, () => { messagesProcessed++ })

    wsClient.start({
      eventDispatcher: new lark.EventDispatcher({}).register({
        'im.message.receive_v1': eventHandler,
      }),
    })

    startTime = Date.now()
    lastError = null
    console.log('[Lark Bot] 已启动，等待消息...')
    BotLogger.log({
      platform: 'lark',
      eventType: 'connection',
      severity: 'info',
      message: '飞书 Bot 已启动',
    })
  } catch (err) {
    const error = err instanceof Error ? err : new Error(String(err))
    lastError = error
    client = null
    wsClient = null
    currentAppId = ''
    currentAppSecret = ''
    console.error('[Lark Bot] 启动失败:', error.message)
    BotLogger.log({
      platform: 'lark',
      eventType: 'error',
      severity: 'error',
      message: `飞书 Bot 启动失败: ${error.message}`,
      details: { hint: '请检查 App ID 和 App Secret 是否正确' },
    })
    throw error
  }
}

export async function stopBot(): Promise<void> {
  closeConnectionsForPlatform('lark')
  if (wsClient) {
    wsClient.close()
    wsClient = null
    client = null
    currentAppId = ''
    currentAppSecret = ''
    startTime = 0
    console.log('[Lark Bot] 已停止')
    BotLogger.log({
      platform: 'lark',
      eventType: 'disconnection',
      severity: 'info',
      message: '飞书 Bot 已停止',
    })
  }
}

export function getStatus(): BotStatus {
  return {
    platform: 'lark',
    status: wsClient ? 'connected' : 'disconnected',
    uptime: wsClient && 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.lark

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