//
//  AppUtils.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/10.
//

import Foundation
import UIKit

// 获取当前应用的包名（Bundle Identifier）
var curAppBundleIdentifier: String = {
    guard let bundleIdentifier = Bundle.main.bundleIdentifier else {
        return "未知版本"
    }
    return bundleIdentifier
}()

// 获取应用当前版本号
var curAppVersion: String = {
    guard let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else {
        return "未知版本"
    }
    return version
}()

// 获取应用构建号
var curBuildVersion: String = {
    guard let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String else {
        return "未知构建号"
    }
    return build
}()

// 获取系统版本
var curSystemVersion: String = {
    return UIDevice.current.systemVersion
}()

// 获取设备型号名称（如"iPhone 13"）
var curDeviceModelName: String = {
    var systemInfo = utsname()
    uname(&systemInfo)
    let machineMirror = Mirror(reflecting: systemInfo.machine)
    let identifier = machineMirror.children.reduce("") { identifier, element in
        guard let value = element.value as? Int8, value != 0 else { return identifier }
        return identifier + String(UnicodeScalar(UInt8(value)))
    }
    return identifier
}()

// 获取设备唯一标识符（注意：iOS 10以后无法获取真正的UDID，这里返回的是identifierForVendor）
var curDeviceId: String = {
    guard let deviceId = UIDevice.current.identifierForVendor?.uuidString else {
        return "无法获取设备ID"
    }
    return deviceId
}()

// 获取当前时区
var curTimeZone: String = {
    return TimeZone.current.identifier
}()

var curLocal: Locale {
    Locale(identifier: LNAppConfig.shared.curLang.bundleName)
}

// 获取当前时间
var curTime: TimeInterval {
    Date().timeIntervalSince1970
}

var curTimeInMicro: TimeInterval {
    curTime * 1_000
}

var curTimeInNano: TimeInterval {
    curTime * 1_000_000_000
}

func openAppSetting() {
    guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
    UIApplication.shared.open(url)
}

var isDebuggerAttached: Bool {
    var info = kinfo_proc()
    var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
    var size = MemoryLayout<kinfo_proc>.stride
    let result = sysctl(&mib, UInt32(mib.count), &info, &size, nil, 0)
    
    guard result == 0 else {
        return false
    }
    return (info.kp_proc.p_flag & P_TRACED) != 0
}
