// External release helper only. Select a visible layer-zero window of the exact owned PID.
// CoreGraphics current Apple documentation; deployment target is macOS 15+, SDK unpinned.
import CoreGraphics
import Foundation

guard CommandLine.arguments.count == 2, let expectedPID = Int(CommandLine.arguments[1]), expectedPID > 0 else { exit(2) }
for _ in 0..<40 {
    let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] ?? []
    if let window = windows.first(where: {
        ($0[kCGWindowOwnerPID as String] as? NSNumber)?.intValue == expectedPID &&
        ($0[kCGWindowLayer as String] as? NSNumber)?.intValue == 0
    }), let id = (window[kCGWindowNumber as String] as? NSNumber)?.intValue, id > 0 {
        print("{\"owner_pid\":\(expectedPID),\"window_id\":\(id)}")
        exit(0)
    }
    Thread.sleep(forTimeInterval: 0.5)
}
exit(1)
