import { appConnectionManager, isAppConnected, getAppHeaderInfo } from './appConnectionManager.js'
import { connectApplication, parseAccessOrigin, parseHeader, setHttpHeaders, isInApp } from './appBridge.js'

/**
 * 优化的APP连接工具
 * 避免重复连接，提升性能
 */
export const useOptimizedAppConnection = () => {
  // 优化的连接方法
  const connectToAppOptimized = async (router, options = {}) => {
    const {
      fetchDataCallback = null,
      onConnectionSuccess = null,
      onConnectionFailed = null
    } = options

    console.group('🔗 Optimized APP Connection')
    console.debug('🚀 Starting connection check...')

    // 检查是否在APP环境中
    if (!isInApp()) {
      console.debug('🌐 Browser environment - skipping APP connection')
      if (fetchDataCallback) {
        await fetchDataCallback()
      }
      console.groupEnd()
      return { success: true, fromCache: false }
    }

    // 检查是否已经连接且有效
    if (isAppConnected()) {
      console.debug('✅ Using existing valid connection')
      const headerInfo = getAppHeaderInfo()
      
      if (fetchDataCallback) {
        await fetchDataCallback()
      }
      if (onConnectionSuccess) {
        onConnectionSuccess(headerInfo)
      }
      
      console.groupEnd()
      return { success: true, fromCache: true, headerInfo }
    }

    // 检查是否有进行中的连接
    if (appConnectionManager.isConnecting()) {
      console.debug('⏳ Waiting for existing connection...')
      try {
        await appConnectionManager.getConnectionPromise()
        const headerInfo = getAppHeaderInfo()
        
        if (fetchDataCallback) {
          await fetchDataCallback()
        }
        if (onConnectionSuccess) {
          onConnectionSuccess(headerInfo)
        }
        
        console.groupEnd()
        return { success: true, fromCache: true, headerInfo }
      } catch (error) {
        console.error('❌ Existing connection failed:', error)
        if (onConnectionFailed) {
          onConnectionFailed(error)
        }
        console.groupEnd()
        return { success: false, error }
      }
    }

    // 建立新连接
    console.debug('📱 Establishing new APP connection...')
    const connectionPromise = new Promise((resolve, reject) => {
      connectApplication(async (access) => {
        try {
          const result = parseAccessOrigin(access)

          if (result.success) {
            const headerInfo = parseHeader(result.data)
            await setHttpHeaders(headerInfo)
            
            // 更新连接状态
            appConnectionManager.setConnected(headerInfo)
            
            console.debug('🎉 New connection established')
            
            if (fetchDataCallback) {
              await fetchDataCallback()
            }
            if (onConnectionSuccess) {
              onConnectionSuccess(headerInfo)
            }
            
            resolve({ success: true, fromCache: false, headerInfo })
          } else {
            console.error('❌ Failed to parse access:', result.error)
            appConnectionManager.reset()
            
            if (router) {
              router.push({ path: '/not_app', query: { message: result.error }})
            }
            if (onConnectionFailed) {
              onConnectionFailed(new Error(result.error))
            }
            
            reject(new Error(result.error))
          }
        } catch (error) {
          console.error('❌ Connection process failed:', error)
          appConnectionManager.reset()
          
          if (onConnectionFailed) {
            onConnectionFailed(error)
          }
          
          reject(error)
        }
      })
    })

    appConnectionManager.setConnecting(connectionPromise)
    
    try {
      const result = await connectionPromise
      console.groupEnd()
      return result
    } catch (error) {
      console.groupEnd()
      return { success: false, error }
    }
  }

  // 重置连接
  const resetConnection = () => {
    appConnectionManager.reset()
  }

  // 检查连接状态
  const checkConnectionStatus = () => {
    return {
      isConnected: isAppConnected(),
      isConnecting: appConnectionManager.isConnecting(),
      headerInfo: getAppHeaderInfo()
    }
  }

  return {
    connectToAppOptimized,
    resetConnection,
    checkConnectionStatus,
    isAppConnected,
    getAppHeaderInfo
  }
}
