//
//  AppDelegate.swift
//  suixinkan
//
//  Created by Codex on 2026/6/26.
//

import UIKit

/// AppDelegate 承接 APNs 与微信 SDK 系统回调，SwiftUI App 入口通过 adaptor 注入。
final class AppDelegate: NSObject, UIApplicationDelegate {
    /// 主窗口引用。SwiftUI 生命周期下系统不会自动注入，但扫码等 UIKit 路径仍会读取 `delegate.window`。
    @objc var window: UIWindow?

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        syncKeyWindow()
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(syncKeyWindow),
            name: UIWindow.didBecomeKeyNotification,
            object: nil
        )
        Task { @MainActor in
            WeChatManager.shared.registerIfNeeded()
        }
        return true
    }

    /// 将 `window` 与当前 key window 保持同步，供 UIKit / SDK 通过 AppDelegate 取主窗口。
    @objc private func syncKeyWindow() {
        window = UIApplication.shared.connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .flatMap(\.windows)
            .first(where: \.isKeyWindow)
    }

    func application(
        _ app: UIApplication,
        open url: URL,
        options: [UIApplication.OpenURLOptionsKey: Any] = [:]
    ) -> Bool {
        MainActor.assumeIsolated {
            WeChatManager.shared.handleOpenURL(url)
        }
    }

    func application(
        _ application: UIApplication,
        continue userActivity: NSUserActivity,
        restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
    ) -> Bool {
        MainActor.assumeIsolated {
            WeChatManager.shared.handleContinueUserActivity(userActivity)
        }
    }

    func application(
        _ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
    ) {
        Task { @MainActor in
            PushNotificationManager.shared.handleDeviceToken(deviceToken)
        }
    }

    func application(
        _ application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: Error
    ) {
        Task { @MainActor in
            PushNotificationManager.shared.handleRegistrationError(error)
        }
    }

    func application(
        _ application: UIApplication,
        didReceiveRemoteNotification userInfo: [AnyHashable: Any],
        fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
    ) {
        let payload = PushPayload(userInfo: userInfo)
        Task { @MainActor in
            PushNotificationManager.shared.handleRemoteNotification(payload)
            completionHandler(.newData)
        }
    }

    func applicationWillTerminate(_ application: UIApplication) {
        let semaphore = DispatchSemaphore(value: 0)
        Task { @MainActor in
            await CameraTetheringSession.shutdown()
            semaphore.signal()
        }
        _ = semaphore.wait(timeout: .now() + 2)
    }
}
