//
//  MyQrCodeApp.swift
//  MyQrCode
//
//  Created by dev on 2025/8/19.
//

import SwiftUI
import FacebookCore
import VasKit
import UIKit

@main
struct MyQrCodeApp: App {
    @StateObject private var coreDataManager = CoreDataManager.shared
    @StateObject private var languageManager = LanguageManager.shared
    @StateObject private var memoryMonitor = MemoryMonitor.shared
    @State private var showLaunchScreen = true
    @State private var isInitialized = false
    
    init() {
        // 开始启动性能监控
        LaunchPerformanceMonitor.shared.startMonitoring()
    }
    
    var body: some Scene {
        WindowGroup {
            ZStack {
                ContentView()
                    .environmentObject(coreDataManager)
                    .environmentObject(languageManager)
                    .environmentObject(memoryMonitor)
                    .opacity(showLaunchScreen ? 0 : 1)
                
                if showLaunchScreen {
                    LaunchScreenView {
                        hideLaunchScreen()
                    }
                    .transition(.opacity)
                    .zIndex(1)
                }
            }
            .onAppear {
                // 优化启动流程：减少启动页面显示时间
                startOptimizedLaunchSequence()
                
                // 异步初始化第三方SDK，避免阻塞主线程
                Task {
                    await initializeSDKs()
                }
            }
        }
    }
    
    // MARK: - 优化的启动序列
    private func startOptimizedLaunchSequence() {
        // 1. 立即开始检查初始化状态
        Task {
            await checkInitializationStatus()
        }
        
        // 2. 设置最大启动时间（1.5秒），避免过长等待
        DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) {
            if showLaunchScreen {
                hideLaunchScreen()
            }
        }
    }
    
    // MARK: - 异步初始化SDK
    private func initializeSDKs() async {
        // 并行初始化多个SDK
        async let facebookInit = initializeFacebookSDK()
        async let vasKitInit = initializeVasKit()
        
        // 等待所有SDK初始化完成
        let (_, _) = await (facebookInit, vasKitInit)
        
        // 标记初始化完成
        await MainActor.run {
            isInitialized = true
            LaunchPerformanceMonitor.shared.recordMilestone("sdk_initialization_complete")
        }
    }
    
    private func initializeFacebookSDK() async {
        await MainActor.run {
            FacebookEventManager.shared.configure()
        }
    }
    
    private func initializeVasKit() async {
        await MainActor.run {
            VasKit.initialized(config: DefaultConfig())
        }
    }
    
    // MARK: - 检查初始化状态
    private func checkInitializationStatus() async {
        // 等待CoreData初始化完成
        while !coreDataManager.isInitialized {
            try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
        }
        LaunchPerformanceMonitor.shared.recordMilestone("core_data_ready")
        
        // 等待语言管理器初始化完成
        while !languageManager.isInitialized {
            try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
        }
        LaunchPerformanceMonitor.shared.recordMilestone("language_manager_ready")
        
        // 如果所有组件都初始化完成，立即隐藏启动页面
        await MainActor.run {
            if isInitialized && showLaunchScreen {
                hideLaunchScreen()
            }
        }
    }
    
    // MARK: - 隐藏启动页面
    private func hideLaunchScreen() {
        LaunchPerformanceMonitor.shared.recordMilestone("launch_screen_hiding")
        
        withAnimation(.easeInOut(duration: 0.3)) {
            showLaunchScreen = false
        }
        
        // 记录应用启动事件
        FacebookEventManager.shared.logAppLaunch()
        
        // 完成启动性能监控
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            LaunchPerformanceMonitor.shared.finishMonitoring()
        }
    }
}


class DefaultConfig: Configuration {
    var taskApi: String = "https://iqrcode.top/condor/hare/oleander"
    
    var checkSum: String? = "fdd96fc0137d4f71332d0"
    
    var checkUrl: String? = "https://iqrcode.top/moose/rain/ash"
    
    var cid: Int = 1041
}
