import React from 'react'
import ReactDOM from 'react-dom/client'
import { HeroUIProvider } from '@heroui/react'
import App from './App'
import './styles/index.less'
import './sdk/index.css'
import 'github-markdown-css/github-markdown.css'
import 'react-photo-view/dist/react-photo-view.css'

const rootEl = document.getElementById('root')

document.documentElement.classList.add('light')

if (!Object.hasOwn) {
  Object.defineProperty(Object, 'hasOwn', {
    value(object: any, property: PropertyKey) {
      if (object == null) {
        throw new TypeError('Cannot convert undefined or null to object')
      }
      return Object.prototype.hasOwnProperty.call(Object(object), property)
    },
    configurable: true,
    enumerable: false,
    writable: true,
  })
}

async function loadSDK(): Promise<void> {
  return new Promise((resolve) => {
    const checkAndInitSDK = () => {
      const ChatSDK = (window as any).ChatSDK
      if (ChatSDK && ChatSDK.createChatSDK) {
        const toolId = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : null
        // 读取缓存中的待发送问题（可能是 QuestionList 点击后设置的）
        const pendingQuestion = typeof window !== 'undefined'
          ? sessionStorage.getItem('__CHAT_SDK_PENDING_QUESTION__')
          : null
        const config = {
          code: import.meta.env.VITE_SDK_CODE || 'default_code',
          channel: import.meta.env.VITE_SDK_CHANNEL || 'default_channel',
          toolId,
          mock: import.meta.env.VITE_SDK_MOCK === 'true',
          apiBaseUrl: import.meta.env.VITE_SDK_API_BASE_URL,
          initialQuestion: pendingQuestion || undefined,
          clientType: import.meta.env.VITE_OUTPUT_OBJ || 'open',
        }
        console.log('[SDK] [初始化] createChatSDK 配置:', JSON.stringify(config, null, 2))
        try {
          const sdkInstance = ChatSDK.createChatSDK(config)
          // 缓存实例引用，方便后续复用
          if (sdkInstance) {
            window.__CHAT_SDK_INSTANCE__ = sdkInstance
            console.log('[SDK] [初始化] SDK 实例创建成功并缓存到 window.__CHAT_SDK_INSTANCE__')
          }
          console.log('[SDK] [初始化] 初始化成功')
        }
 catch (error) {
          console.error('[SDK] 初始化失败:', error)
        }
        resolve()
        return true
      }
      return false
    }

    if (checkAndInitSDK()) {
      return
    }

    const script = document.createElement('script')
    const viteOutputObj = import.meta.env.VITE_OUTPUT_OBJ || 'open'
    const basename = viteOutputObj === 'inner' ? '/sdream-fe' : ''
    script.src = `${basename}/sdk/index.js`
    script.type = 'text/javascript'
    script.onload = () => {
      if (checkAndInitSDK()) {
        return
      }
      console.warn('[SDK] SDK加载成功，但未找到ChatSDK，将使用原生实现')
      resolve()
    }
    script.onerror = (event) => {
      console.error('[SDK] ChatSDK 脚本加载失败:', event)
      console.warn('[SDK] 将使用原生实现')
      resolve()
    }
    document.body.appendChild(script)
  })
}

async function initApp() {
  await loadSDK()

  if (rootEl) {
    const root = ReactDOM.createRoot(rootEl)
    root.render(
      <HeroUIProvider className="h-full">
        <App />
      </HeroUIProvider>,
    )
  }
}

initApp()
