import AgentDeviceMacOSInput
import AppKit
import ApplicationServices
import CoreGraphics
import Foundation

/// How an app-surface action reached the app. Every pointer action is an accessibility action on
/// the element under the point: an inactive app drops pointer events posted to its process, so a
/// pointer action with no accessibility equivalent is refused rather than reported as delivered.
enum BackgroundDeliveryMechanism: String, Encodable, CaseIterable {
  case axPress = "ax-press"
  case axFocus = "ax-focus"
  case axValue = "ax-value"
  case axSelectedText = "ax-selected-text"
  case axConfirm = "ax-confirm"
  case axScrollBar = "ax-scroll-bar"
  /// `AXShowMenu`, confirmed by the app's new menu window.
  case axShowMenu = "ax-show-menu"
  /// Keyboard events posted to the app's process, which inactive apps do accept.
  case keyEvents = "key-events"
}

/// Typed refusals the host maps to `UNSUPPORTED_OPERATION`. Both vocabularies are pinned by
/// `contracts/fixtures/macos-native-helper-outcomes.json`.
enum BackgroundRefusal: String, CaseIterable {
  case pointerGesture = "background-pointer-gesture"
  case noAccessibleTarget = "no-accessible-target"
  case noTextInput = "no-settable-text-input"
  case noScrollBar = "no-scroll-bar"
  case noContextMenu = "no-context-menu"
}

struct BackgroundPressResponse: Encodable {
  let x: Double
  let y: Double
  let clicks: Int
  let bundleId: String?
  let surface: String
  let mechanism: BackgroundDeliveryMechanism
  let role: String?
  let windowTitle: String?
}

struct BackgroundTextResponse: Encodable {
  let bundleId: String?
  let mechanism: BackgroundDeliveryMechanism
  let role: String?
  let windowTitle: String?
}

struct BackgroundMenuResponse: Encodable {
  let x: Double
  let y: Double
  let bundleId: String?
  let mechanism: BackgroundDeliveryMechanism
  let role: String?
  let windowTitle: String?
}

struct BackgroundScrollResponse: Encodable {
  let x: Double
  let y: Double
  let x2: Double
  let y2: Double
  let referenceWidth: Double
  let referenceHeight: Double
  let travelPixels: Double
  let mechanism: BackgroundDeliveryMechanism
}

/// Roles whose ancestors are containers, never the control a click meant.
private let pressSearchBoundaryRoles: Set<String> = [
  "AXWindow", "AXApplication", "AXScrollArea", "AXTable", "AXOutline", "AXList", "AXWebArea",
  "AXSheet", "AXDialog",
]
private let textInputRoles: Set<String> = ["AXTextField", "AXTextArea", "AXComboBox", "AXSearchField"]
/// Roles a click means to activate. Chromium marks most wrapper groups pressable too, so a group
/// is only the target when nothing more specific contains the point.
private let pressableControlRoles: Set<String> = [
  "AXButton", "AXLink", "AXCheckBox", "AXRadioButton", "AXPopUpButton", "AXMenuButton",
  "AXMenuItem", "AXMenuBarItem", "AXCell", "AXRow", "AXTab", "AXDisclosureTriangle",
  "AXIncrementor", "AXSlider", "AXColorWell", "AXDockItem",
]
private let pressSearchMaxAncestors = 4

func refusal(
  _ reason: BackgroundRefusal,
  _ message: String,
  app: NSRunningApplication,
  details: [String: String] = [:]
) -> HelperError {
  .commandFailed(
    message,
    details: details.merging(["reason": reason.rawValue, "bundleId": app.bundleIdentifier ?? ""]) {
      $1
    })
}

func requireSessionApplication(bundleId: String?) throws -> NSRunningApplication {
  guard let bundleId, !bundleId.isEmpty else {
    throw HelperError.invalidArgs("the app surface requires --bundle-id <id>")
  }
  return try resolveTargetApplication(bundleId: bundleId, surface: "app")
}

func pressInBackground(
  _ request: MouseClickRequest,
  app: NSRunningApplication,
  cursor: GhostCursor?
) throws -> BackgroundPressResponse {
  guard !request.doubleClick, request.holdMs <= 0 else {
    throw refusal(
      .pointerGesture,
      "double-click and press-and-hold have no accessibility equivalent in a background app",
      app: app
    )
  }
  let point = CGPoint(x: request.x, y: request.y)
  try requireAppWindowPoint(point, app: app)
  cursor?.move(to: point)
  let target = resolvePressTarget(app: app, point: point)
  if let target, isInMenuBar(target.element) {
    throw refusal(.noAccessibleTarget, "the point is on the app's menu bar", app: app)
  }
  guard let target, let mechanism = perform(target) else {
    throw refusal(.noAccessibleTarget, "no pressable accessibility element at the point", app: app)
  }
  var clicks = 1
  while clicks < request.clicks {
    Thread.sleep(forTimeInterval: Double(max(request.intervalMs, 0)) / 1000)
    guard perform(target) != nil else { break }
    clicks += 1
  }
  cursor?.pulse()
  return BackgroundPressResponse(
    x: request.x,
    y: request.y,
    clicks: clicks,
    bundleId: app.bundleIdentifier,
    surface: "app",
    mechanism: mechanism,
    role: role(of: target.element),
    windowTitle: windowTitle(of: target.element)
  )
}

/// Inserts text at the focused element's caret, the way typing does.
func typeInBackground(
  text: String,
  delayMs: Int,
  app: NSRunningApplication,
  cursor: GhostCursor?
) throws -> BackgroundTextResponse {
  let appElement = AXUIElementCreateApplication(app.processIdentifier)
  let focused = elementAttribute(appElement, attribute: kAXFocusedUIElementAttribute as String)
  if let focused, let rect = rectAttribute(focused) {
    cursor?.move(to: CGPoint(x: rect.x + rect.width / 2, y: rect.y + rect.height / 2))
  }
  let focusedRole = focused.map(role(of:))
  if text == "\n", let focused, actionNames(of: focused).contains(kAXConfirmAction as String),
    AXUIElementPerformAction(focused, kAXConfirmAction as CFString) == .success
  {
    cursor?.pulse()
    return BackgroundTextResponse(
      bundleId: app.bundleIdentifier, mechanism: .axConfirm, role: focusedRole,
      windowTitle: windowTitle(of: focused))
  }
  if !text.contains("\n"), let focused,
    isAttributeSettable(focused, attribute: kAXSelectedTextAttribute as String),
    AXUIElementSetAttributeValue(focused, kAXSelectedTextAttribute as CFString, text as CFString)
      == .success
  {
    cursor?.pulse()
    return BackgroundTextResponse(
      bundleId: app.bundleIdentifier, mechanism: .axSelectedText, role: focusedRole,
      windowTitle: windowTitle(of: focused))
  }
  try postText(text, delayMs: delayMs, pid: app.processIdentifier)
  cursor?.pulse()
  return BackgroundTextResponse(
    bundleId: app.bundleIdentifier, mechanism: .keyEvents, role: focusedRole,
    windowTitle: focused.flatMap(windowTitle(of:)))
}

/// Replaces the value of the text input at a point.
func fillInBackground(
  point: CGPoint,
  text: String,
  app: NSRunningApplication,
  cursor: GhostCursor?
) throws -> BackgroundTextResponse {
  try requireAppWindowPoint(point, app: app)
  cursor?.move(to: point)
  let hit = elementAtPoint(in: app, point: point)
  let chain = hit.map(pressSearchChain) ?? []
  let fallback = actionWindow(app: app, hit: hit).flatMap { window in
    smallestElement(in: window, containing: point, where: isTextInput)
  }
  if let input = chain.first(where: isTextInput) ?? fallback, isInMenuBar(input) {
    throw refusal(.noAccessibleTarget, "the point is on the app's menu bar", app: app)
  }
  guard let input = chain.first(where: isTextInput) ?? fallback,
    isAttributeSettable(input, attribute: kAXValueAttribute as String)
  else {
    throw refusal(.noTextInput, "no settable text input at the point", app: app)
  }
  AXUIElementSetAttributeValue(input, kAXFocusedAttribute as CFString, kCFBooleanTrue)
  guard AXUIElementSetAttributeValue(input, kAXValueAttribute as CFString, text as CFString) == .success
  else {
    throw refusal(.noTextInput, "the text input refused the new value", app: app)
  }
  cursor?.pulse()
  return BackgroundTextResponse(
    bundleId: app.bundleIdentifier, mechanism: .axValue, role: role(of: input),
    windowTitle: windowTitle(of: input))
}

private let popUpMenuWindowLayer = Int(CGWindowLevelForKey(.popUpMenuWindow))
/// An app that opens a menu tracks it until the menu closes and answers `AXShowMenu` only then,
/// so the action's reply is abandoned after this long and the menu window decides the outcome.
private let showMenuReplyTimeoutSeconds: Float = 0.5
private let menuWindowWaitMs = 1_000
private let menuWindowPollMs = 50

/// Opens the context menu of the element at a point, the way a secondary click does: the nearest
/// element up the hit chain that offers `AXShowMenu` opens it. Success is the app's new menu
/// window, never the action's own reply.
func showMenuInBackground(
  point: CGPoint,
  app: NSRunningApplication,
  cursor: GhostCursor?
) throws -> BackgroundMenuResponse {
  try requireAppWindowPoint(point, app: app)
  cursor?.move(to: point)
  let hit = hitTest(in: app, point: point)
  let owner: AXUIElement
  switch contextMenuOwner(
    from: hit.element,
    role: role(of:),
    offersMenu: { actionNames(of: $0).contains(showMenuAction as String) },
    parent: { elementAttribute($0, attribute: kAXParentAttribute as String) }
  ) {
  case .owner(let element): owner = element
  case .noTarget:
    throw refusal(
      .noAccessibleTarget, "the app's hit test found no accessibility element at the point",
      app: app, details: ["axError": String(hit.axError.rawValue)])
  case .noMenu:
    throw refusal(
      .noContextMenu, "no accessibility element at the point offers a context menu", app: app)
  }
  if isInMenuBar(owner) {
    throw refusal(.noAccessibleTarget, "the point is on the app's menu bar", app: app)
  }
  let pid = app.processIdentifier
  let menusBefore = popUpMenuWindowNumbers(pid: pid, windowInfo: try requireWindowInfo())
  AXUIElementSetMessagingTimeout(owner, showMenuReplyTimeoutSeconds)
  let reply = AXUIElementPerformAction(owner, showMenuAction)
  guard try waitForNewMenuWindow(pid: pid, excluding: menusBefore) else {
    throw HelperError.commandFailed(
      "the element offered a context menu, but no menu opened",
      details: [
        "reason": "context-menu-not-observed",
        "axError": String(reply.rawValue),
        "bundleId": app.bundleIdentifier ?? "",
        "hint": "No menu window appeared. Take a snapshot to check the app before you retry.",
      ]
    )
  }
  cursor?.pulse()
  return BackgroundMenuResponse(
    x: point.x,
    y: point.y,
    bundleId: app.bundleIdentifier,
    mechanism: .axShowMenu,
    role: role(of: owner),
    windowTitle: windowTitle(of: owner)
  )
}

func popUpMenuWindowNumbers(pid: pid_t, windowInfo: [[String: Any]]) -> Set<Int> {
  Set(
    windowInfo.compactMap { entry in
      guard (entry[kCGWindowOwnerPID as String] as? Int32) == pid,
        (entry[kCGWindowLayer as String] as? Int) == popUpMenuWindowLayer
      else {
        return nil
      }
      return entry[kCGWindowNumber as String] as? Int
    })
}

private let showMenuAction = "AXShowMenu" as CFString

/// Where a secondary click's context menu comes from: no hit-test element, no element with a
/// menu, or the element that owns it.
enum ContextMenuOwner<Element> {
  case noTarget
  case noMenu
  case owner(Element)
}

extension ContextMenuOwner: Equatable where Element: Equatable {}

/// An open menu's items sit under the element that opened it, so the walk stops at a menu too.
private let contextMenuOwnerBoundaryRoles: Set<String> = ["AXWindow", "AXApplication", "AXMenu"]

/// AppKit offers a secondary click to the hit view and then to each superview in turn, so the
/// nearest ancestor with a menu owns it.
func contextMenuOwner<Element>(
  from hit: Element?,
  role: (Element) -> String,
  offersMenu: (Element) -> Bool,
  parent: (Element) -> Element?
) -> ContextMenuOwner<Element> {
  guard var element = hit else { return .noTarget }
  for _ in 0..<32 {
    if contextMenuOwnerBoundaryRoles.contains(role(element)) { return .noMenu }
    if offersMenu(element) { return .owner(element) }
    guard let next = parent(element) else { return .noMenu }
    element = next
  }
  return .noMenu
}

/// A window list that never became readable is a refusal, not an unobserved menu.
private func waitForNewMenuWindow(pid: pid_t, excluding before: Set<Int>) throws -> Bool {
  let deadline = Date().addingTimeInterval(Double(menuWindowWaitMs) / 1000)
  var readAny = false
  repeat {
    if let info = appWindowInfo() {
      readAny = true
      if !popUpMenuWindowNumbers(pid: pid, windowInfo: info).subtracting(before).isEmpty {
        return true
      }
    }
    Thread.sleep(forTimeInterval: Double(menuWindowPollMs) / 1000)
  } while Date() < deadline
  if !readAny { _ = try requireWindowInfo(nil) }
  return false
}

/// Scrolls the scroll area at the center of the app's front window.
func scrollInBackground(
  direction: String,
  amount: Double?,
  pixels: Double?,
  app: NSRunningApplication,
  cursor: GhostCursor?
) throws -> BackgroundScrollResponse {
  let isVertical = direction == "up" || direction == "down"
  guard isVertical || direction == "left" || direction == "right" else {
    throw HelperError.invalidArgs("scroll requires --direction <up|down|left|right>")
  }
  guard let frame = try frontWindowFrame(pid: app.processIdentifier) else {
    throw HelperError.commandFailed(
      "scroll could not resolve an on-screen window",
      details: ["reason": "window-not-found", "bundleId": app.bundleIdentifier ?? ""]
    )
  }
  let travel = scrollTravelPixels(
    axisLength: Double(isVertical ? frame.height : frame.width),
    amount: amount,
    pixels: pixels
  )
  let center = CGPoint(x: frame.midX, y: frame.midY)
  cursor?.move(to: center)
  let revealsLaterContent = direction == "down" || direction == "right"
  guard
    performScrollBarScroll(
      app: app,
      at: center,
      isVertical: isVertical,
      signedTravel: revealsLaterContent ? travel : -travel
    )
  else {
    throw refusal(.noScrollBar, "no scroll area with a settable scroll bar under the window center", app: app)
  }
  cursor?.pulse()
  // Reported as the equivalent drag, start to end, the way the runner reports a desktop scroll.
  let half = travel / 2
  let sign: Double = revealsLaterContent ? 1 : -1
  return BackgroundScrollResponse(
    x: isVertical ? center.x : center.x + sign * half,
    y: isVertical ? center.y + sign * half : center.y,
    x2: isVertical ? center.x : center.x - sign * half,
    y2: isVertical ? center.y - sign * half : center.y,
    referenceWidth: Double(frame.width),
    referenceHeight: Double(frame.height),
    travelPixels: travel,
    mechanism: .axScrollBar
  )
}

/// Mirrors `runnerScrollGesturePlan`'s travel so both macOS backends scroll the same distance:
/// the requested travel, kept clear of the outer tenth of the axis on both sides.
func scrollTravelPixels(axisLength: Double, amount: Double?, pixels: Double?) -> Double {
  let requested = pixels.map { max(1, $0.rounded()) } ?? (axisLength * (amount ?? 0.6)).rounded()
  let edgePadding = max(1, (axisLength * 0.1).rounded())
  return max(1, min(requested, axisLength - edgePadding * 2))
}

/// The scroll bar value that moves the content by `signedTravel` points, clamped to its ends.
func scrollBarValue(current: Double, signedTravel: Double, overflow: Double) -> Double {
  min(1, max(0, current + signedTravel / overflow))
}

/// A SwiftUI `Form` lists each row as a child of the scroll area, with no single document view as
/// tall as the content, so the content is the span all of the area's children cover.
func scrollContentOverflow(area: RectResponse, contentFrames: [RectResponse], isVertical: Bool)
  -> Double
{
  let spans = contentFrames
    .filter { $0.width > 0 && $0.height > 0 }
    .map { isVertical ? ($0.y, $0.y + $0.height) : ($0.x, $0.x + $0.width) }
  guard let start = spans.map(\.0).min(), let end = spans.map(\.1).max() else { return 0 }
  return end - start - (isVertical ? area.height : area.width)
}

func isPressableControlRole(_ role: String) -> Bool {
  pressableControlRoles.contains(role)
}

private enum PressTarget {
  case focus(AXUIElement)
  case press(AXUIElement)

  var element: AXUIElement {
    switch self {
    case .focus(let element), .press(let element): element
    }
  }
}

/// What a click at a point means. The app's own hit test answers first; web content often answers
/// with a wrapper group, so the snapshot geometry decides when the hit names no control.
private func resolvePressTarget(app: NSRunningApplication, point: CGPoint) -> PressTarget? {
  let hit = elementAtPoint(in: app, point: point)
  let chain = hit.map(pressSearchChain) ?? []
  if let input = chain.first(where: isTextInput) { return .focus(input) }
  if let control = chain.first(where: isPressableControl) { return .press(control) }
  if let found = actionWindow(app: app, hit: hit).flatMap({
    smallestElement(in: $0, containing: point, where: { isTextInput($0) || isPressableControl($0) })
  }) {
    return isTextInput(found) ? .focus(found) : .press(found)
  }
  return chain.first(where: { actionNames(of: $0).contains(kAXPressAction as String) }).map {
    .press($0)
  }
}

private func perform(_ target: PressTarget) -> BackgroundDeliveryMechanism? {
  switch target {
  case .focus(let element):
    return AXUIElementSetAttributeValue(element, kAXFocusedAttribute as CFString, kCFBooleanTrue)
      == .success ? .axFocus : nil
  case .press(let element):
    return AXUIElementPerformAction(element, kAXPressAction as CFString) == .success ? .axPress : nil
  }
}

/// The app's accessibility tree also holds its menu bar, whose Apple menu acts for the whole Mac
/// (Sleep, Lock Screen, Recent Items). A point action therefore lands only inside one of the app's
/// own on-screen windows, its menus and sheets included, and never on a menu bar element: the app
/// owns its menu bar's window too, so the window check alone does not exclude it.
private func requireAppWindowPoint(_ point: CGPoint, app: NSRunningApplication) throws {
  guard let info = appWindowInfo() else {
    throw refusal(.noAccessibleTarget, "the app's on-screen windows could not be read", app: app)
  }
  let inAppWindow = info.contains { entry in
    guard (entry[kCGWindowOwnerPID as String] as? Int32) == app.processIdentifier,
      let boundsDict = entry[kCGWindowBounds as String] as? NSDictionary,
      let bounds = CGRect(dictionaryRepresentation: boundsDict as CFDictionary)
    else {
      return false
    }
    return bounds.contains(point)
  }
  guard inAppWindow else {
    throw refusal(.noAccessibleTarget, "the point is outside the app's on-screen windows", app: app)
  }
}

private func isInMenuBar(_ element: AXUIElement) -> Bool {
  var current: AXUIElement? = element
  var depth = 0
  while let node = current, depth < 32 {
    let nodeRole = role(of: node)
    if nodeRole == "AXMenuBar" || nodeRole == "AXMenuBarItem" { return true }
    if nodeRole == "AXApplication" { return false }
    current = elementAttribute(node, attribute: kAXParentAttribute as String)
    depth += 1
  }
  return false
}

/// The app's own hit test, scoped to the app so windows of other apps above it do not answer.
private func elementAtPoint(in app: NSRunningApplication, point: CGPoint) -> AXUIElement? {
  hitTest(in: app, point: point).element
}

/// The app's hit test with its accessibility result, so a failed hit test stays distinct from
/// an element that cannot take the action.
private func hitTest(
  in app: NSRunningApplication,
  point: CGPoint
) -> (element: AXUIElement?, axError: AXError) {
  let appElement = AXUIElementCreateApplication(app.processIdentifier)
  var hit: AXUIElement?
  let axError = AXUIElementCopyElementAtPosition(appElement, Float(point.x), Float(point.y), &hit)
  return (axError == .success ? hit : nil, axError)
}

private func pressSearchChain(from hit: AXUIElement) -> [AXUIElement] {
  var chain: [AXUIElement] = []
  var current: AXUIElement? = hit
  while let element = current, chain.count <= pressSearchMaxAncestors {
    if pressSearchBoundaryRoles.contains(role(of: element)) { break }
    chain.append(element)
    current = elementAttribute(element, attribute: kAXParentAttribute as String)
  }
  return chain
}

/// The one window a point action may act in: the window the app's hit test landed in, else the
/// app's front on-screen window. A fallback target never comes from a window behind it, and the
/// response names the window so the host can check it. The caller's `requireAppWindowPoint` has
/// already read the window list, so a list that turned unreadable here is treated as no window.
private func actionWindow(app: NSRunningApplication, hit: AXUIElement?) -> AXUIElement? {
  if let hit {
    if role(of: hit) == "AXWindow" { return hit }
    if let window = elementAttribute(hit, attribute: kAXWindowAttribute as String) { return window }
  }
  guard let front = try? frontWindowFrame(pid: app.processIdentifier) else { return nil }
  return windows(of: AXUIElementCreateApplication(app.processIdentifier)).first { window in
    rectAttribute(window).map { isSameFrame($0, front) } ?? false
  }
}

/// Whether an accessibility window frame is the frame of a WindowServer window.
private func isSameFrame(_ rect: RectResponse, _ frame: CGRect) -> Bool {
  abs(rect.x - frame.minX) < 1 && abs(rect.y - frame.minY) < 1
    && abs(rect.width - frame.width) < 1 && abs(rect.height - frame.height) < 1
}

private func windowTitle(of element: AXUIElement) -> String? {
  let window = role(of: element) == "AXWindow"
    ? element : elementAttribute(element, attribute: kAXWindowAttribute as String)
  return window.flatMap { stringAttribute($0, attribute: kAXTitleAttribute as String) }
}

/// The smallest matching element in a window whose frame contains the point, skipping subtrees
/// whose frame excludes the point.
private func smallestElement(
  in window: AXUIElement,
  containing point: CGPoint,
  where matches: (AXUIElement) -> Bool
) -> AXUIElement? {
  var best: (element: AXUIElement, area: Double)?
  var budget = 6000
  func visit(_ element: AXUIElement, depth: Int) {
    guard budget > 0, depth < 64 else { return }
    budget -= 1
    if let rect = rectAttribute(element), rect.width > 0, rect.height > 0 {
      guard CGRect(x: rect.x, y: rect.y, width: rect.width, height: rect.height).contains(point)
      else { return }
      let area = rect.width * rect.height
      if area < (best?.area ?? .infinity), matches(element) {
        best = (element, area)
      }
    }
    for child in children(of: element) {
      visit(child, depth: depth + 1)
    }
  }
  visit(window, depth: 0)
  return best?.element
}

/// Moves the scroll bar of the scroll area under a point by the travel's share of the content's
/// overflow. An inactive app honors a scroll bar change where it drops wheel events.
private func performScrollBarScroll(
  app: NSRunningApplication,
  at point: CGPoint,
  isVertical: Bool,
  signedTravel: Double
) -> Bool {
  var current = elementAtPoint(in: app, point: point)
  for _ in 0..<8 {
    guard let element = current, role(of: element) != "AXWindow" else { return false }
    current = elementAttribute(element, attribute: kAXParentAttribute as String)
    guard role(of: element) == "AXScrollArea" else { continue }
    let barAttribute = isVertical ? kAXVerticalScrollBarAttribute : kAXHorizontalScrollBarAttribute
    guard let bar = elementAttribute(element, attribute: barAttribute as String),
      isAttributeSettable(bar, attribute: kAXValueAttribute as String),
      let value = numberAttribute(bar, attribute: kAXValueAttribute as String),
      let area = rectAttribute(element)
    else {
      continue
    }
    let overflow = scrollContentOverflow(
      area: area,
      contentFrames: children(of: element)
        .filter({ role(of: $0) != "AXScrollBar" })
        .compactMap(rectAttribute),
      isVertical: isVertical
    )
    guard overflow > 0 else { continue }
    let next = scrollBarValue(current: value, signedTravel: signedTravel, overflow: overflow)
    return AXUIElementSetAttributeValue(bar, kAXValueAttribute as CFString, NSNumber(value: next))
      == .success
  }
  return false
}

private func role(of element: AXUIElement) -> String {
  stringAttribute(element, attribute: kAXRoleAttribute as String) ?? ""
}

private func isTextInput(_ element: AXUIElement) -> Bool {
  textInputRoles.contains(role(of: element))
}

private func isPressableControl(_ element: AXUIElement) -> Bool {
  isPressableControlRole(role(of: element))
    && actionNames(of: element).contains(kAXPressAction as String)
}

private func actionNames(of element: AXUIElement) -> [String] {
  var names: CFArray?
  guard AXUIElementCopyActionNames(element, &names) == .success, let names = names as? [String] else {
    return []
  }
  return names
}

private func isAttributeSettable(_ element: AXUIElement, attribute: String) -> Bool {
  var settable = DarwinBoolean(false)
  return AXUIElementIsAttributeSettable(element, attribute as CFString, &settable) == .success
    && settable.boolValue
}

private func numberAttribute(_ element: AXUIElement, attribute: String) -> Double? {
  var value: CFTypeRef?
  guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success,
    let number = value as? NSNumber
  else {
    return nil
  }
  return number.doubleValue
}

struct OnScreenWindow {
  let number: Int
  let bounds: CGRect
  let sharingState: Int?
}

/// Only normal-layer windows qualify; app-modal alerts at level 8 are excluded.
let frontWindowLayer = 0

/// The pid's visible, nonempty normal-layer windows, front to back.
func onScreenWindows(pid: pid_t, windowInfo: [[String: Any]]) -> [OnScreenWindow] {
  windowInfo.compactMap { entry in
    guard (entry[kCGWindowOwnerPID as String] as? Int32) == pid,
      (entry[kCGWindowLayer as String] as? Int) == frontWindowLayer,
      (entry[kCGWindowIsOnscreen as String] as? Bool) == true,
      let alpha = entry[kCGWindowAlpha as String] as? Double, alpha > 0,
      let number = entry[kCGWindowNumber as String] as? Int,
      let boundsDict = entry[kCGWindowBounds as String] as? NSDictionary,
      let bounds = CGRect(dictionaryRepresentation: boundsDict as CFDictionary),
      bounds.width > 0, bounds.height > 0
    else {
      return nil
    }
    return OnScreenWindow(
      number: number, bounds: bounds, sharingState: entry[kCGWindowSharingState as String] as? Int)
  }
}

func appWindowInfo() -> [[String: Any]]? {
  CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID)
    as? [[String: Any]]
}

/// The app's front on-screen window: frontmost among its eligible windows, or nil when it has
/// none. A window list that cannot be read is a refusal, not an empty list: the caller must not
/// report "no window" for a WindowServer it could not ask.
func frontWindow(pid: pid_t, windowInfo: [[String: Any]]? = appWindowInfo()) throws -> OnScreenWindow? {
  let windowInfo = try requireWindowInfo(windowInfo)
  return frontWindow(
    among: onScreenWindows(pid: pid, windowInfo: windowInfo),
    isSharingIndicator: { isWindowSharingIndicator(pid: pid, frame: $0.bounds) }
  )
}

/// The frontmost candidate that is not a window-sharing indicator. A lone window is never one: an
/// indicator only appears in front of the window it belongs to.
func frontWindow(
  among candidates: [OnScreenWindow],
  isSharingIndicator: (OnScreenWindow) -> Bool
) -> OnScreenWindow? {
  guard candidates.count > 1 else { return candidates.first }
  return candidates.first { !isSharingIndicator($0) }
}

func requireWindowInfo(_ windowInfo: [[String: Any]]? = appWindowInfo()) throws -> [[String: Any]] {
  guard let windowInfo else {
    throw HelperError.commandFailed(
      "the app's on-screen windows could not be read",
      details: [
        "reason": "window-list-unreadable",
        "hint": "The app's on-screen window list could not be read. Retry the command.",
      ]
    )
  }
  return windowInfo
}

/// While a ScreenCaptureKit stream shares one of an app's windows, macOS 27 adds a 66 x 20
/// normal-layer window titled "Window" in front of it. Its only child is a button titled
/// `WindowSharingSessionButton`. That window is a system indicator, not the app's front window.
private let windowSharingIndicatorButtonTitle = "WindowSharingSessionButton"

/// Whether a child of a window, by its accessibility role and title, marks the window as the
/// indicator. The title is read only for a button.
func isWindowSharingIndicatorButton(role: String, title: @autoclosure () -> String?) -> Bool {
  role == "AXButton" && title() == windowSharingIndicatorButtonTitle
}

/// `AXUIElementSetMessagingTimeout` applies only to the element it is set on, so every element the
/// probe reads gets it, and the probe stops at its own deadline.
private let sharingIndicatorReplyTimeoutSeconds: Float = 0.1
private let sharingIndicatorProbeSeconds = 0.5

/// An accessibility tree that cannot be read in time, from a hung app or without Accessibility
/// access, reads as no indicator, so the frontmost window stays the choice as before the indicator
/// check. Refusing instead would fail screenshots, which need no accessibility read today.
private func isWindowSharingIndicator(pid: pid_t, frame: CGRect) -> Bool {
  let deadline = Date().addingTimeInterval(sharingIndicatorProbeSeconds)
  func bounded(_ element: AXUIElement) -> AXUIElement? {
    guard Date() < deadline else { return nil }
    AXUIElementSetMessagingTimeout(element, sharingIndicatorReplyTimeoutSeconds)
    return element
  }
  guard let appElement = bounded(AXUIElementCreateApplication(pid)) else { return false }
  let window = windows(of: appElement).first { window in
    guard let window = bounded(window), let rect = rectAttribute(window) else { return false }
    return isSameFrame(rect, frame)
  }
  guard let window else { return false }
  return children(of: window).contains { child in
    guard let child = bounded(child) else { return false }
    return isWindowSharingIndicatorButton(
      role: role(of: child), title: stringAttribute(child, attribute: kAXTitleAttribute as String))
  }
}

func frontWindowFrame(pid: pid_t, windowInfo: [[String: Any]]? = appWindowInfo()) throws -> CGRect? {
  try frontWindow(pid: pid, windowInfo: windowInfo)?.bounds
}

private let returnVirtualKey: CGKeyCode = 36
private let tabVirtualKey: CGKeyCode = 48

private func postKey(virtualKey: CGKeyCode, pid: pid_t) throws {
  guard let down = CGEvent(keyboardEventSource: nil, virtualKey: virtualKey, keyDown: true),
    let up = CGEvent(keyboardEventSource: nil, virtualKey: virtualKey, keyDown: false)
  else {
    throw HelperError.commandFailed("key event creation failed", details: ["reason": "event_creation_failed"])
  }
  down.postToPid(pid)
  up.postToPid(pid)
}

private func postText(_ text: String, delayMs: Int, pid: pid_t) throws {
  for character in text {
    switch character {
    case "\n", "\r":
      try postKey(virtualKey: returnVirtualKey, pid: pid)
    case "\t":
      try postKey(virtualKey: tabVirtualKey, pid: pid)
    default:
      guard let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),
        let up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
      else {
        throw HelperError.commandFailed(
          "key event creation failed", details: ["reason": "event_creation_failed"])
      }
      let units = Array(String(character).utf16)
      down.keyboardSetUnicodeString(stringLength: units.count, unicodeString: units)
      up.keyboardSetUnicodeString(stringLength: units.count, unicodeString: units)
      down.postToPid(pid)
      up.postToPid(pid)
    }
    if delayMs > 0 {
      Thread.sleep(forTimeInterval: Double(delayMs) / 1000)
    }
  }
}
