//
//  PerformanceMonitor.swift
//  LotteryTracker
//
//  Created by aaa on 2026/1/22.
//

import Foundation

class PerformanceMonitor {
    static let shared = PerformanceMonitor()
    
    private var timers: [String: TimeInterval] = [:]
    private var memoryUsage: [String: UInt64] = [:]
    
    private init() {}
    
    // 开始计时
    func startTimer(_ name: String) {
        timers[name] = Date().timeIntervalSince1970
    }
    
    // 结束计时并返回耗时
    @discardableResult
    func stopTimer(_ name: String) -> TimeInterval {
        guard let startTime = timers[name] else { return 0 }
        let endTime = Date().timeIntervalSince1970
        let duration = endTime - startTime
        timers.removeValue(forKey: name)
        
        print("⏱️ [\(name)] 耗时: \(String(format: "%.3f", duration))秒")
        return duration
    }
    
    // 记录内存使用
    func recordMemoryUsage(_ name: String) {
        var info = mach_task_basic_info()
        var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4
        
        let kerr = withUnsafeMutablePointer(to: &info) {
            $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
                task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
            }
        }
        
        if kerr == KERN_SUCCESS {
            let memoryUsage = info.resident_size
            self.memoryUsage[name] = memoryUsage
            print("💾 [\(name)] 内存使用: \(memoryUsage / 1024 / 1024) MB")
        }
    }
    
    // 性能测试
    func runPerformanceTest(operation: () -> Void, name: String = "测试") {
        startTimer(name)
        recordMemoryUsage("\(name)_开始")
        
        operation()
        
        stopTimer(name)
        recordMemoryUsage("\(name)_结束")
    }
}

// 调试日志
func debugLog(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
    #if DEBUG
    let fileName = (file as NSString).lastPathComponent
    print("🐛 [\(fileName):\(line)] \(function) - \(message)")
    #endif
}

// 安全执行
func safeExecute<T>(_ operation: () throws -> T, errorMessage: String = "操作失败") -> T? {
    do {
        return try operation()
    } catch {
        debugLog("\(errorMessage): \(error)")
        return nil
    }
}
