import ComposeApp
import SwiftUI
import os

private let bundleSubsystem = Bundle.main.bundleIdentifier ?? "com.dong.demo013"

/// Use `OSSignposter` + interval state (Apple’s supported path). Raw `os_signpost` often does not
/// show up under the Points of Interest / os_signposts instruments unless wired this way.
private let signalSignposter = OSSignposter(
    subsystem: bundleSubsystem,
    category: .pointsOfInterest
)

private let signalLogger = Logger(
    subsystem: bundleSubsystem,
    category: "set_os_signal"
)

private enum SignalSignpostName {
    static let interval: StaticString = "signal"
}

/// 多段区间可时间交叉：`respose_time` 与 `finish_time` 各自一条栈，互不影响。
/// 同一 `signalId` 多次 begin 再 end：按 **后进先出** 配对（嵌套重叠）；若同一 id **交叉**
/// 非嵌套（begin A / begin B / end A / end B），需在 Kotlin 侧增加 token 再扩展 key。
private final class SignalIntervalBridge: @unchecked Sendable {
    private var openStacks: [String: [OSSignpostIntervalState]] = [:]
    private let lock = NSLock()

    func begin(signalId: String, text: String) {
        let sid = signalSignposter.makeSignpostID()
        let state = signalSignposter.beginInterval(
            SignalSignpostName.interval,
            id: sid,
            "\(text, privacy: .public)"
        )
        lock.lock()
        var stack = openStacks[signalId] ?? []
        stack.append(state)
        openStacks[signalId] = stack
        lock.unlock()
    }

    func end(signalId: String, text: String) {
        lock.lock()
        var stack = openStacks[signalId] ?? []
        let state = stack.popLast()
        if stack.isEmpty {
            openStacks[signalId] = nil
        } else {
            openStacks[signalId] = stack
        }
        lock.unlock()
        if let state {
            signalSignposter.endInterval(
                SignalSignpostName.interval,
                state,
                "\(text, privacy: .public)"
            )
        }
    }
}

private let signalIntervalBridge = SignalIntervalBridge()

@main
struct iOSApp: App {

    var body: some Scene {
        WindowGroup {
            ContentView().onAppear() {
                NotificationCenter.default.addObserver(
                    forName: NSNotification.Name("set_os_signal"),
                    object: nil,
                    queue: .main
                ) { note in
                    if let dic = note.object as? NSDictionary {
                        let text = dic.object(forKey: "text") as! String
                        print("set_os_signal-text: \(text)")
                        let isBeginNumber = dic.object(forKey: "isBegin") as! NSNumber
                        print("set_os_signal-isbegin: \(isBeginNumber.boolValue)")
                        let signalId = dic.object(forKey: "id") as! NSString
                        let signalIdStr = signalId as String
                        print("set_os_signal-id: \(signalId)")

                        signalLogger.notice("set_os_signal text=\(text, privacy: .public) id=\(signalIdStr, privacy: .public) isBegin=\(isBeginNumber.boolValue, privacy: .public)")

                        if isBeginNumber.boolValue {
                            signalIntervalBridge.begin(signalId: signalIdStr, text: text)
                        } else {
                            signalIntervalBridge.end(signalId: signalIdStr, text: text)
                        }
                    }
                }
            }
            .ignoresSafeArea()
            .background(Color.clear)
        }
    }
}
