//
//  AppDelegate.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/6.
//

import UIKit
import CocoaLumberjackSwift
import Firebase
import GoogleSignIn

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        setupLogger()
        setupFirebase()
        setupAdjust()
        LNNetworkMonitor.startMonitoring()
        
        _ = LNProfileManager.shared
        _ = LNIMManager.shared
        _ = LNGameMateManager.shared
        _ = LNPurchaseManager.shared
        _ = RechargeManager.shared
        _ = LNLocationManager.shared
        _ = LNRelationManager.shared
        _ = LNDeeplinkManager.shared
        _ = LNKeyboardManager.shared
        _ = LNConfigManager.shared
        _ = LNOrderManager.shared
        _ = LNRoomManager.shared
        _ = LNGiftManager.shared
        
        LNEventDeliver.notifyAppLaunchFinished()
        
        if let url = launchOptions?[.url] as? URL {
            LNDeeplinkManager.shared.handleDeepLink(url)
        }
        reportLanguage()
        requestNotificationPermissions()
        
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
}

extension AppDelegate {
    @objc func businessID() -> Int32 {
        LNIMManager.shared.offlinePushAppId
    }
    
    @objc func onRemoteNotificationReceived(_ notice: String?) -> Bool {
        false
    }
}

extension AppDelegate {
    private func reportLanguage() {
        LNProfileManager.shared.reportCurrentLanguage(code: LNAppConfig.shared.curLang.languageCode) { _ in }
    }
}

extension AppDelegate {
    private func setupFirebase() {
#if DEBUG
        let plistName = "GoogleService-Info-Debug"
#else
        let plistName = "GoogleService-Info-Release"
#endif
        let plistPath = Bundle.main.path(forResource: plistName, ofType: "plist")!
        let options = FirebaseOptions(contentsOfFile: plistPath)
        FirebaseApp.configure(options: options!)
    }
    
    private func setupLogger() {
#if DEBUG // 只在 Debug 模式打印到终端
        let logger = DDOSLogger.sharedInstance
        logger.logFormatter = LNLoggerFormater()
        DDLog.add(logger)
#endif
        
        let fileLogger = DDFileLogger()
        fileLogger.logFormatter = LNLoggerFormater()
        fileLogger.rollingFrequency = 24 * 60 * 60 // 1 天轮转
        fileLogger.logFileManager.maximumNumberOfLogFiles = 7 // 最多保存 7 个文件
        fileLogger.maximumFileSize = 5 * 1024 * 1024 // 5M 最大限制
        DDLog.add(fileLogger)
        
        Log.i("\n\n\n\n==================== App Start ====================")
        Log.i("version: \(curAppVersion)")
        Log.i("buildVersion: \(curBuildVersion)")
        Log.i("OS: \(curSystemVersion)")
        Log.i("Env: \(LNAppConfig.shared.curEnv.text)")
        Log.i("==================== \(curTime.formattedFullDateWithTime()) ====================")
    }
    
    private func setupAdjust() {
        let token = "fbze46mdkxds"
        let env: String
        let logLevel: ADJLogLevel
        if LNAppConfig.shared.curEnv == .test {
            env = ADJEnvironmentSandbox
            logLevel = .verbose
        } else {
            env = ADJEnvironmentProduction
            logLevel = .suppress
        }
        let config = ADJConfig(appToken: token, environment: env)
        config?.logLevel = logLevel
        config?.externalDeviceId = curDeviceId
        config?.enableCostDataInAttribution()
//        config?.delegate = self
        Adjust.initSdk(config)
    }
    
    private func requestNotificationPermissions() {
        // 请求通知权限（可根据需求调整，如添加 sound/badge 等）
        LNPermissionHelper.requestNotificationAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if let error = error {
                Log.e("请求推送权限失败: \(error.localizedDescription)")
                return
            }

            if granted {
                Log.i("用户已授予推送权限")
                // 权限获取成功后，注册远程推送
                UIApplication.shared.registerForRemoteNotifications()
            } else {
                Log.i("用户拒绝了推送权限")
            }
        }
    }
}
