interface ChatSDKConfig {
  code: string
  channel: string
  toolId?: string
  apiBaseUrl?: string
  mock?: boolean
  isDesktop?: boolean
}

interface ChatSDKInstance {
  speak: (text: string) => void
  stopSpeak: () => void
  destroy: () => void
}

let sdkInstance: ChatSDKInstance | null = null
let sdkLoadingPromise: Promise<void> | null = null

export async function loadChatSDK(config: ChatSDKConfig): Promise<ChatSDKInstance | null> {
  if (sdkInstance) {
    return sdkInstance
  }

  if (sdkLoadingPromise) {
    await sdkLoadingPromise
    return sdkInstance
  }

  sdkLoadingPromise = new Promise((resolve) => {
    const script = document.createElement('script')
    script.src = '/sdream-ai/sdk/index.js'
    script.onload = () => {
      try {
        const ChatSDK = (window as any).ChatSDK
        if (ChatSDK && ChatSDK.createChatSDK) {
          sdkInstance = ChatSDK.createChatSDK(config)
          console.log('[SDK] toolId:', config.toolId)
        }
      }
 catch (error) {
        console.error('[SDK] 初始化失败:', error)
      }
      resolve()
    }
    script.onerror = () => {
      console.error('[SDK] ChatSDK 脚本加载失败')
      resolve()
    }
    document.body.appendChild(script)
  })

  await sdkLoadingPromise
  return sdkInstance
}

export function getSDKInstance(): ChatSDKInstance | null {
  return sdkInstance
}

export function destroySDK(): void {
  if (sdkInstance) {
    sdkInstance.destroy()
    sdkInstance = null
  }
  sdkLoadingPromise = null
}
