#import <AdSupport/ASIdentifierManager.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h> // iOS 14及以上需要
#import <UIKit/UIKit.h>

extern "C" {

    // 获取IDFA的函数
    const char* _GetIDFA() {
        // 检查iOS版本
        if (@available(iOS 14, *)) {
            // 检查当前追踪授权状态。注意：实际请求权限的弹窗应在合适时机主动调用，这里仅获取当前状态下的IDFA。
            ATTrackingManagerAuthorizationStatus status = [ATTrackingManager trackingAuthorizationStatus];
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                // 用户已授权
                NSString *idfaString = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
                return strdup([idfaString UTF8String]);
            } else {
                // 用户未授权、拒绝或受限
                NSLog(@"用户未授权广告追踪。状态: %ld", (long)status);
                return strdup("");
            }
        } else {
            // Fallback on earlier versions - iOS 14以下版本
            if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
                NSString *idfaString = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
                return strdup([idfaString UTF8String]);
            } else {
                NSLog(@"用户限制了广告追踪。");
                return strdup("");
            }
        }
    }

    // 请求追踪权限的函数 (应在C#端选择合适的时机调用，例如用户点击同意隐私协议后)
    void _RequestTrackingPermission() {
        if (@available(iOS 14, *)) {
            [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                // 此回调在用户做出选择后执行
                NSString *idfaString = @"";
                if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                    idfaString = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
                }
                // 可以使用UnitySendMessage将结果异步回传给Unity
                // UnitySendMessage("GameObjectName", "MethodName", [idfaString UTF8String]);
            }];
        } else {
            // iOS 13或更低版本，无需请求权限，直接检查isAdvertisingTrackingEnabled
            // 这里可以不做处理，或者也通过UnitySendMessage通知Unity
        }
    }

    // 获取IDFV的函数
    const char* _GetIDFV() {
        NSString *idfvString = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        if (idfvString) {
            return strdup([idfvString UTF8String]);
        } else {
            return strdup("");
        }
    }
}