// windows.swift: list or wait for on-screen windows owned by processes whose
// executable lives inside a given .app bundle. Read-only (CGWindowList).
//
//   windows list <bundle-prefix>
//   windows all <bundle-prefix>      -> also windows that are hidden or off screen
//   windows wait <bundle-prefix> <timeout-seconds>   -> prints ms until the first
//        normal (layer 0, >= 300x200) on-screen window of that app appears.
import Foundation
import CoreGraphics
import Darwin

func exePath(_ pid: pid_t) -> String {
    var buf = [CChar](repeating: 0, count: 4096)
    let n = proc_pidpath(pid, &buf, UInt32(buf.count))
    return n > 0 ? String(cString: buf) : ""
}

func windows(_ prefix: String, all: Bool = false) -> [[String: Any]] {
    guard let list = CGWindowListCopyWindowInfo(all ? [.optionAll] : [.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] else { return [] }
    var cache: [pid_t: String] = [:]
    return list.filter { w in
        guard let pid = w[kCGWindowOwnerPID as String] as? pid_t else { return false }
        let path = cache[pid] ?? exePath(pid)
        cache[pid] = path
        return path.hasPrefix(prefix)
    }
}

func isNormal(_ w: [String: Any]) -> Bool {
    let layer = w[kCGWindowLayer as String] as? Int ?? -1
    let b = w[kCGWindowBounds as String] as? [String: Any] ?? [:]
    let width = b["Width"] as? Double ?? 0, height = b["Height"] as? Double ?? 0
    return layer == 0 && width >= 300 && height >= 200
}

let args = CommandLine.arguments
guard args.count >= 3 else { print("usage: windows list|wait <bundle-prefix> [timeout]"); exit(2) }
let prefix = args[2]
if args[1] == "list" || args[1] == "all" {
    for w in windows(prefix, all: args[1] == "all") where args[1] == "list" || isNormal(w) {
        let b = w[kCGWindowBounds as String] as? [String: Any] ?? [:]
        print("id=\(w[kCGWindowNumber as String] ?? "") pid=\(w[kCGWindowOwnerPID as String] ?? "") layer=\(w[kCGWindowLayer as String] ?? "") size=\(Int(b["Width"] as? Double ?? 0))x\(Int(b["Height"] as? Double ?? 0)) onscreen=\(w[kCGWindowIsOnscreen as String] ?? false) name=\(w[kCGWindowName as String] ?? "")")
    }
} else {
    let timeout = Double(args.count > 3 ? args[3] : "120") ?? 120
    let start = Date()
    while Date().timeIntervalSince(start) < timeout {
        if let w = windows(prefix).first(where: isNormal) {
            let ms = Int(Date().timeIntervalSince(start) * 1000)
            print("first_window_ms=\(ms) id=\(w[kCGWindowNumber as String] ?? "") pid=\(w[kCGWindowOwnerPID as String] ?? "") name=\(w[kCGWindowName as String] ?? "")")
            exit(0)
        }
        usleep(25_000)
    }
    print("timeout")
    exit(1)
}
