//
//  NetworkMonitor.swift
//  ylgamehall
//
//  NWPathMonitor 的最简 wrap：提供 currentCode 同步快照 + onChange 事件回调。
//  用于 AppDataWriter.writeNetwork(_:) 拿首次值 + 变化重写 app_network.js。
//  详见 docs/H5-Native-Implementation-Design.md §7.5 / §8.4。
//

import Foundation
import Network

/// `app_getnetwork` 的语义码（与 msext 沿用）：
/// 1 = 无网，2 = WiFi，3 = 蜂窝
@MainActor
public final class NetworkMonitor {

    public static let shared = NetworkMonitor()

    public private(set) var currentCode: Int = 2

    /// 网络变化回调。每次状态变化时主线程触发。
    public var onChange: (@MainActor (Int) -> Void)?

    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "ylgamehall.networkmonitor", qos: .utility)
    private var started = false

    public init() {}

    public func start() {
        guard !started else { return }
        started = true
        monitor.pathUpdateHandler = { [weak self] path in
            let code: Int = {
                if path.status != .satisfied { return 1 }
                if path.usesInterfaceType(.wifi) { return 2 }
                return 3
            }()
            Task { @MainActor in
                guard let self else { return }
                self.currentCode = code
                self.onChange?(code)
            }
        }
        monitor.start(queue: queue)
    }
}
