import Foundation
import UIKit

// MARK: - 启动性能监控器
class LaunchPerformanceMonitor {
    static let shared = LaunchPerformanceMonitor()
    
    private var startTime: CFAbsoluteTime = 0
    private var milestones: [String: CFAbsoluteTime] = [:]
    
    private init() {}
    
    // MARK: - 启动性能监控
    
    /// 开始监控启动性能
    func startMonitoring() {
        startTime = CFAbsoluteTimeGetCurrent()
        milestones["app_launch_start"] = startTime
        print("🚀 启动性能监控开始: \(startTime)")
    }
    
    /// 记录启动里程碑
    func recordMilestone(_ name: String) {
        let currentTime = CFAbsoluteTimeGetCurrent()
        milestones[name] = currentTime
        
        if let startTime = milestones["app_launch_start"] {
            let elapsed = currentTime - startTime
            print("📊 启动里程碑 [\(name)]: \(String(format: "%.3f", elapsed))s")
        }
    }
    
    /// 完成启动监控
    func finishMonitoring() {
        let endTime = CFAbsoluteTimeGetCurrent()
        milestones["app_launch_complete"] = endTime
        
        if let startTime = milestones["app_launch_start"] {
            let totalTime = endTime - startTime
            print("✅ 启动完成，总耗时: \(String(format: "%.3f", totalTime))s")
            
            // 分析各阶段耗时
            analyzeLaunchPhases()
        }
    }
    
    /// 分析启动各阶段耗时
    private func analyzeLaunchPhases() {
        let sortedMilestones = milestones.sorted { $0.value < $1.value }
        
        print("\n📈 启动阶段分析:")
        for i in 0..<sortedMilestones.count - 1 {
            let current = sortedMilestones[i]
            let next = sortedMilestones[i + 1]
            let duration = next.value - current.value
            
            print("  • \(current.key) → \(next.key): \(String(format: "%.3f", duration))s")
        }
        
        // 检查是否有耗时过长的阶段
        checkPerformanceIssues()
    }
    
    /// 检查性能问题
    private func checkPerformanceIssues() {
        let sortedMilestones = milestones.sorted { $0.value < $1.value }
        
        for i in 0..<sortedMilestones.count - 1 {
            let current = sortedMilestones[i]
            let next = sortedMilestones[i + 1]
            let duration = next.value - current.value
            
            if duration > 0.5 { // 超过500ms的阶段
                print("⚠️  性能警告: \(current.key) → \(next.key) 耗时 \(String(format: "%.3f", duration))s")
            }
        }
    }
    
    /// 获取启动总耗时
    func getTotalLaunchTime() -> Double {
        guard let startTime = milestones["app_launch_start"],
              let endTime = milestones["app_launch_complete"] else {
            return 0
        }
        return endTime - startTime
    }
    
    /// 获取特定阶段耗时
    func getPhaseDuration(from startMilestone: String, to endMilestone: String) -> Double? {
        guard let start = milestones[startMilestone],
              let end = milestones[endMilestone] else {
            return nil
        }
        return end - start
    }
}

// MARK: - 启动阶段常量
extension LaunchPerformanceMonitor {
    enum LaunchPhase: String, CaseIterable {
        case appDidFinishLaunching = "app_did_finish_launching"
        case coreDataInitialized = "core_data_initialized"
        case languageManagerInitialized = "language_manager_initialized"
        case memoryMonitorInitialized = "memory_monitor_initialized"
        case facebookSDKInitialized = "facebook_sdk_initialized"
        case vasKitInitialized = "vas_kit_initialized"
        case contentViewAppeared = "content_view_appeared"
        case launchScreenHidden = "launch_screen_hidden"
        case appFullyReady = "app_fully_ready"
    }
}
