//
//  KeyboardApi.swift
//  AiKeyboard
//
//  Created by Destiny on 2025/4/28.
//

import Foundation
import UIKit
import AdSupport
import AppTrackingTransparency

enum NetworkEnvironment {
    case local
    case dev
    case prod
}

struct KeyboardApi {
    
    static let env: NetworkEnvironment = .local
    
    static let localUrl = "http://192.168.10.113:8880"
    
    static let devUrl = "http://42.193.245.11"
    
    static let prodUrl = "https://project-api.atmob.com"
    
    static func getBaseUrl() -> String {
        
        switch KeyboardApi.env {
        case .local:
            return KeyboardApi.localUrl
        case .dev:
            return KeyboardApi.devUrl
        case .prod:
            return KeyboardApi.prodUrl
        }
    }
    
    static var params: [String:Any] = [
        "channelName":"appstore",
        "idfa":"",
        "idfv":"",
        "packageName":"com.qihuan.zhuiaijianpan",
        "appPlatform":2,
        "appVersionName":"1.0.0",
        "appVersionCode":100,
        "authToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aWQiOiI1MWNkNGQzYTkyNmYyMGJlIiwicHJqIjoicHJvamVjdF9rZXlib2FyZCIsInByZCI6ImNvbS5xaWh1YW4uemh1aWFpamlhbnBhbiIsInBrZyI6ImNvbS5xaWh1YW4uemh1aWFpamlhbnBhbiIsInBsZiI6MiwiZGlkIjoiZjMxODEyYzc5OTVjNDJiYmJlZDg2N2FhYzE2Nzg2YTIiLCJyZWciOjE3NDU4OTY1ODkwMDAsInNpZCI6Ijg2NmUyYTRhZjE3ODRmODA4N2NlYTg4ZDdiOWViYjcwIiwidWlkIjoiZmNkZmI5ZmE4NzFiNGRlOWI5ZTc0NTMxODAxZWE3YjUiLCJsb2ciOjEsImV4cCI6MTc2MTU0NTkyMCwiaWF0IjoxNzQ1OTk3NTIwLCJpc3MiOiJkZXYifQ.LWbuvY42U_f0bRd6uiILORU7j9910UyYLNAzuwx1l4qQNc3PblylB28OvhVw38IhbVSEYa6teW1prkG2XkGxs1roEqhJ1kuoT-16scz8UJPfr3dvsO_Xl-m4jip4ThhR8pJWIRVaIrOpQhLuQO38VSeQKDOR_HR1LonHmPY"
    ]
    
    static func updateAppVersionName(appVersionName: String) {
        params["appVersionName"] = appVersionName
    }
    
    static func updateAppVersionCode(appVersionCode: Int) {
        params["appVersionCode"] = appVersionCode
    }
    
    static func updateIDFV(idfv: String) {
        params["idfv"] = idfv
    }
    
    static func updateIDFA(idfa: String) {
        params["idfa"] = idfa
    }
    
    // 初始化基本参数
    static func initParams() {
        
        // 获取版本号
        if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            debugPrint("App Version: \(appVersion)")
            KeyboardApi.updateAppVersionName(appVersionName: appVersion)
            
            let array = appVersion.components(separatedBy: ".")
            var appVersionCode = ""
            for i in array {
                appVersionCode.append(i)
            }
            if appVersionCode.count < 3 {
                appVersionCode.append("0")
            }
            KeyboardApi.updateAppVersionCode(appVersionCode: Int(appVersionCode) ?? 100)
        } else {
            debugPrint("Unable to retrieve app version")
        }
        
        // 获取 设置uuid 并更新
        if let uuid = UIDevice.current.identifierForVendor?.uuidString {
            KeyboardApi.updateIDFV(idfv: uuid)
            debugPrint("IDFV ID: \(uuid)")
        } else {
            debugPrint("获取 IDFV ID 参数失败")
        }
        
        // 获取idfa
        initIDFA()
    }
    
    // 初始化idfa
    static func initIDFA() {
        
        DispatchQueue.global().asyncAfter(deadline: .now() + 0.1){
            if #available(iOS 14.0, *) {
                // 用户请求授权获得IDFA权限
                ATTrackingManager.requestTrackingAuthorization { status in
                    
                    if status == .authorized {
                        
                        debugPrint("授权成功")
                        // 用户已授权
                        let idfa = ASIdentifierManager.shared().advertisingIdentifier
                        debugPrint("IDFA: \(idfa.uuidString)")
                        KeyboardApi.updateIDFA(idfa: idfa.uuidString)
                    } else {
                        
                        debugPrint("无法获取idfa")
                    }
                    
                  
                }
            } else {
                
                // 检查用户是否授权应用使用广告标识符
                if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                    // 获取 IDFA
                    let idfa = ASIdentifierManager.shared().advertisingIdentifier
                    KeyboardApi.updateIDFA(idfa: idfa.uuidString)
                    debugPrint("IDFA: \(idfa)")
                } else {
                    debugPrint("用户拒绝广告追踪")
                }
            }
        }
    }
}

extension KeyboardApi {
    
    // 获取键盘人设列表
    static let character_list = "/project/keyboard/v1/character/list"
    
    // 获取键盘列表
    static let keyboard_list = "/project/keyboard/v1/keyboard/list"
    
    // 选择键盘
    static let keyboard_choose = "/project/keyboard/v1/keyboard/choose"
    
    // 获取开场白列表
    static let prologue_list = "/project/keyboard/v1/keyboard/prologue/list"
    
    // 获取用户信息
    static let user_info = "/project/keyboard/v1/user/info"
}

extension KeyboardApi {
    
    // 超会回
    static let chat_super_reply = "/project/keyboard/v1/chat/superReply"
    
    // 超会说
    static let chat_super_speak = "/project/keyboard/v1/chat/superSpeak"
    
    // 开场白
    static let chat_super_prologue = "/project/keyboard/v1/chat/prologue"
}
