import CoreGraphics
import Foundation

guard CommandLine.arguments.count > 1, let pid = Int32(CommandLine.arguments[1]) else {
    fputs("usage: macos_window_count <pid>\n", stderr)
    exit(2)
}

let options: CGWindowListOption = [.excludeDesktopElements, .optionOnScreenOnly]
guard let raw = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else {
    print(0)
    exit(0)
}

var count = 0
for window in raw {
    guard let owner = window[kCGWindowOwnerPID as String] as? Int32, owner == pid else {
        continue
    }
    let layer = window[kCGWindowLayer as String] as? Int ?? 0
    if layer == 0 {
        count += 1
    }
}

print(count)
