import XCTest

extension RunnerTests {
  private static let collapsedTabCandidateTypes: Set<XCUIElement.ElementType> = [
    .button,
    .link,
    .menuItem,
    .other,
    .staticText
  ]
  private static let scrollContainerTypes: Set<XCUIElement.ElementType> = [
    .collectionView,
    .scrollView,
    .table
  ]
  // Per-request XPC timeout for a snapshot command's queries, in seconds.
  // A responsive app answers in well under a second, even on a deep React
  // Native screen. A suspended app never answers. 3s leaves wide margin for
  // a busy app and still bounds the stall when the app leaves the screen.
  // captureRootSnapshot retries a slow root snapshot at XCTest's full
  // timeout, so this bound cannot cut a large tree short.
  private static let snapshotRequestTimeout: TimeInterval = 3.0
  // How long one fast snapshot may run before the collapsed tab fallback's
  // query no longer starts (agent-device's tree slice, #3776). XCTest cannot
  // cancel a query once it runs on the main thread, so the check is made
  // before it starts.
  private static let collapsedTabProcessingBudget: TimeInterval = 8.0
  // The least time a query is admitted with (agent-device's sweep budget).
  private static let minimumQueryBudget: TimeInterval = 0.1

  private struct SnapshotTraversalContext {
    // The app actually read. A no-bundle snapshot can move to the app in
    // front when the one it started on leaves the screen.
    let app: XCUIApplication
    let queryRoot: XCUIElement
    let rootSnapshot: XCUIElementSnapshot
    // How long reading rootSnapshot took: what one more query over the
    // whole tree is expected to cost.
    let rootReadDuration: TimeInterval
    let viewport: CGRect
    let occlusion: OcclusionIndex
    let maxDepth: Int
  }

  /// Everything the hittable check needs, read once per snapshot. The check
  /// asks whether any element drawn later (after the node's own subtree, in
  /// depth-first order) covers the node's centre. It used to re-read every
  /// later snapshot's frame and type for every node — O(n²) Objective-C
  /// property reads, seconds on a web page with thousands of nodes. Frames
  /// are now read once, and only on-screen occluders are kept, so each node
  /// scans a short precomputed list.
  struct OcclusionIndex {
    /// Depth-first position of each snapshot, and the last position inside
    /// its subtree.
    let position: [ObjectIdentifier: (start: Int, end: Int)]
    /// Positions of elements that can cover others (anything but the
    /// application and its windows) with a frame on screen, ascending.
    let occluderPositions: [Int]
    /// Frames, parallel to occluderPositions.
    let occluderFrames: [CGRect]

    init(root: XCUIElementSnapshot, viewport: CGRect, isOccluding: (XCUIElement.ElementType) -> Bool) {
      var position: [ObjectIdentifier: (start: Int, end: Int)] = [:]
      var occluderPositions: [Int] = []
      var occluderFrames: [CGRect] = []
      var next = 0
      @discardableResult
      func visit(_ snapshot: XCUIElementSnapshot) -> Int {
        let start = next
        next += 1
        let frame = snapshot.frame
        if isOccluding(snapshot.elementType), !frame.isNull, !frame.isEmpty, frame.intersects(viewport) {
          occluderPositions.append(start)
          occluderFrames.append(frame)
        }
        var end = start
        for child in snapshot.children {
          end = max(end, visit(child))
        }
        position[ObjectIdentifier(snapshot)] = (start, end)
        return end
      }
      visit(root)
      self.position = position
      self.occluderPositions = occluderPositions
      self.occluderFrames = occluderFrames
    }

    /// Whether an element drawn after `snapshot`'s subtree covers `point`.
    func isCovered(_ snapshot: XCUIElementSnapshot, at point: CGPoint) -> Bool {
      guard let range = position[ObjectIdentifier(snapshot)] else { return false }
      // First occluder past the subtree, by binary search.
      var lo = 0
      var hi = occluderPositions.count
      while lo < hi {
        let mid = (lo + hi) / 2
        if occluderPositions[mid] <= range.end { lo = mid + 1 } else { hi = mid }
      }
      for i in lo..<occluderFrames.count where occluderFrames[i].contains(point) {
        return true
      }
      return false
    }
  }

  /// The fraction of `rect` that lies on screen, 0 for an empty rect.
  static func visibleFraction(_ rect: CGRect, in viewport: CGRect) -> CGFloat {
    if rect.isNull || rect.isEmpty { return 0 }
    let area = rect.width * rect.height
    if area <= 0 { return 0 }
    let overlap = rect.intersection(viewport)
    if overlap.isNull || overlap.isEmpty { return 0 }
    return (overlap.width * overlap.height) / area
  }

  /// Maestro keeps an element when at least 10% of it is on screen.
  static let minVisibleFraction: CGFloat = 0.1

  private struct SnapshotEvaluation {
    let label: String
    let identifier: String
    let valueText: String?
    let hittable: Bool
    let focused: Bool
    let selected: Bool
    let visible: Bool
  }

  // MARK: - Snapshot Entry

  func elementTypeName(_ type: XCUIElement.ElementType) -> String {
    switch type {
    case .application: return "Application"
    case .window: return "Window"
    case .button: return "Button"
    case .cell: return "Cell"
    case .staticText: return "StaticText"
    case .textField: return "TextField"
    case .textView: return "TextView"
    case .secureTextField: return "SecureTextField"
    case .switch: return "Switch"
    case .slider: return "Slider"
    case .link: return "Link"
    case .image: return "Image"
    case .navigationBar: return "NavigationBar"
    case .tabBar: return "TabBar"
    case .collectionView: return "CollectionView"
    case .table: return "Table"
    case .scrollView: return "ScrollView"
    case .searchField: return "SearchField"
    case .segmentedControl: return "SegmentedControl"
    case .stepper: return "Stepper"
    case .picker: return "Picker"
    case .checkBox: return "CheckBox"
    case .menuItem: return "MenuItem"
    case .other: return "Other"
    default:
      switch type.rawValue {
      case 19:
        return "Keyboard"
      case 20:
        return "Key"
      case 24:
        return "SearchField"
      default:
        return "Element(\(type.rawValue))"
      }
    }
  }

  // appStateString names the target's lifecycle state for the snapshot
  // response. XCUIApplication.state is the OS's own answer, unlike the
  // per-node hittable flags, which flip while a screen animates into the
  // background and settle back to their foreground values.
  func appStateString(_ app: XCUIApplication) -> String {
    switch app.state {
    case .runningForeground: return "runningForeground"
    case .runningBackground: return "runningBackground"
    case .runningBackgroundSuspended: return "runningBackgroundSuspended"
    case .notRunning: return "notRunning"
    default: return "unknown"
    }
  }

  func snapshotFast(app requested: XCUIApplication, options: SnapshotOptions) -> Response {
    let processingDeadline = Date().addingTimeInterval(Self.collapsedTabProcessingBudget)
    if let blocking = blockingSystemAlertSnapshot() {
      return Response(ok: true, data: blocking)
    }

    let target = snapshotTarget(requested, options: options)
    guard let context = makeSnapshotTraversalContext(app: target, options: options) else {
      // The public snapshot threw (a deep React Native tree makes the AX server
      // answer kAXErrorIllegalArgument), which would otherwise hand back an
      // empty tree — the devicelab-vs-WDA RN gap. Recover the tree through the
      // private AX client instead of returning nothing. Only for an app in
      // front: one that has left the screen is suspended and cannot answer.
      if target.state == .runningForeground,
         let fallback = privateAXFallbackPayload(app: target, options: options) {
        return Response(ok: true, data: fallback)
      }
      return snapshotFailure(target)
    }
    let app = context.app

    var nodes: [SnapshotNode] = []
    var truncated = false

    // Read at most once per snapshot, and only when a collapsed container
    // asks. A query that could not start leaves the tree marked truncated.
    var cachedCollapsedTabCandidates: [CollapsedTabCandidate]?
    func collapsedTabCandidatesOnce() -> [CollapsedTabCandidate] {
      if let cachedCollapsedTabCandidates {
        return cachedCollapsedTabCandidates
      }
      let candidates = collapsedTabCandidates(context: context, processingDeadline: processingDeadline)
      if candidates == nil { truncated = true }
      cachedCollapsedTabCandidates = candidates ?? []
      return candidates ?? []
    }

    let rootEvaluation = evaluateSnapshot(context.rootSnapshot, in: context)
    nodes.append(
      makeSnapshotNode(
        snapshot: context.rootSnapshot,
        evaluation: rootEvaluation,
        depth: 0,
        index: 0,
        parentIndex: nil
      )
    )
    if context.maxDepth > 0 {
      let didTruncateFallback = appendCollapsedTabFallbackNodes(
        to: &nodes,
        containerSnapshot: context.rootSnapshot,
        resolveCandidates: collapsedTabCandidatesOnce,
        viewport: context.viewport,
        depth: 1,
        parentIndex: 0,
        nodeLimit: fastSnapshotLimit
      )
      truncated = truncated || didTruncateFallback
    }

    var seen = Set<String>()
    // The last field is true when an ancestor lies wholly off screen: its
    // descendants' frames are then clipped to the viewport by the app
    // (Flutter semantics especially) and cannot be trusted as "on screen".
    var stack: [(XCUIElementSnapshot, Int, Int, Int?, Bool)] = context.rootSnapshot.children.map {
      ($0, 1, 1, 0, false)
    }
    let nodeLimit = options.visibleOnly ? visibleSnapshotLimit : fastSnapshotLimit

    while let (snapshot, depth, visibleDepth, parentIndex, underOffscreen) = stack.popLast() {
      if nodes.count >= nodeLimit {
        truncated = true
        break
      }
      if let limit = options.depth, depth > limit { continue }

      let frame = snapshot.frame
      let hasFrame = !frame.isNull && !frame.isEmpty
      let offscreen = hasFrame && !frame.intersects(context.viewport)
      if options.visibleOnly
        && (underOffscreen || Self.visibleFraction(frame, in: context.viewport) < Self.minVisibleFraction) {
        // Not on screen: leave it out, but keep walking — a frameless
        // wrapper can hold visible children, and those attach to the
        // nearest included ancestor.
        if depth < context.maxDepth {
          for child in snapshot.children.reversed() {
            stack.append((child, depth + 1, visibleDepth, parentIndex, underOffscreen || offscreen))
          }
        }
        continue
      }

      let evaluation = evaluateSnapshot(snapshot, in: context)
      let include = shouldInclude(
        snapshot: snapshot,
        label: evaluation.label,
        identifier: evaluation.identifier,
        valueText: evaluation.valueText,
        options: options,
        hittable: evaluation.hittable,
        visible: evaluation.visible
      )

      let key = "\(snapshot.elementType)-\(evaluation.label)-\(evaluation.identifier)-\(snapshot.frame.origin.x)-\(snapshot.frame.origin.y)"
      let isDuplicate = seen.contains(key)
      if !isDuplicate {
        seen.insert(key)
      }

      let currentIndex = include && !isDuplicate ? nodes.count : parentIndex
      if depth < context.maxDepth {
        let nextVisibleDepth = include && !isDuplicate ? visibleDepth + 1 : visibleDepth
        for child in snapshot.children.reversed() {
          stack.append((child, depth + 1, nextVisibleDepth, currentIndex, underOffscreen || offscreen))
        }
      }

      if !include || isDuplicate { continue }

      let index = nodes.count
      nodes.append(
        makeSnapshotNode(
          snapshot: snapshot,
          evaluation: evaluation,
          depth: min(context.maxDepth, visibleDepth),
          index: index,
          parentIndex: parentIndex
        )
      )
      if visibleDepth < context.maxDepth {
        let didTruncateFallback = appendCollapsedTabFallbackNodes(
          to: &nodes,
          containerSnapshot: snapshot,
          resolveCandidates: collapsedTabCandidatesOnce,
          viewport: context.viewport,
          depth: visibleDepth + 1,
          parentIndex: index,
          nodeLimit: nodeLimit
        )
        truncated = truncated || didTruncateFallback
      }

    }

    // A foreground app whose public snapshot yielded only the root node is the
    // other half of the RN gap: the serializer returned a childless tree on a
    // screen that plainly has content. Try the private AX path and prefer it
    // when it recovers more than the root.
    if nodes.count <= 1, app.state == .runningForeground,
       let fallback = privateAXFallbackPayload(app: app, options: options),
       (fallback.nodes?.count ?? 0) > nodes.count {
      return Response(ok: true, data: fallback)
    }

    return snapshotSuccess(nodes: nodes, truncated: truncated, app: app)
  }

  func snapshotRaw(app requested: XCUIApplication, options: SnapshotOptions) -> Response {
    if let blocking = blockingSystemAlertSnapshot() {
      return Response(ok: true, data: blocking)
    }

    let target = snapshotTarget(requested, options: options)
    guard let context = makeSnapshotTraversalContext(app: target, options: options) else {
      return snapshotFailure(target)
    }
    let app = context.app

    var nodes: [SnapshotNode] = []
    var truncated = false

    func walk(_ snapshot: XCUIElementSnapshot, depth: Int, parentIndex: Int?) {
      if nodes.count >= maxSnapshotElements {
        truncated = true
        return
      }
      if let limit = options.depth, depth > limit { return }

      let evaluation = evaluateSnapshot(snapshot, in: context)
      let include = shouldInclude(
        snapshot: snapshot,
        label: evaluation.label,
        identifier: evaluation.identifier,
        valueText: evaluation.valueText,
        options: options,
        hittable: evaluation.hittable,
        visible: evaluation.visible
      )
      let currentIndex = include ? nodes.count : parentIndex
      if include {
        nodes.append(
          makeSnapshotNode(
            snapshot: snapshot,
            evaluation: evaluation,
            depth: depth,
            index: nodes.count,
            parentIndex: parentIndex
          )
        )
      }

      let children = snapshot.children
      for child in children {
        walk(child, depth: depth + 1, parentIndex: currentIndex)
        if truncated { return }
      }
    }

    walk(context.rootSnapshot, depth: 0, parentIndex: nil)
    return snapshotSuccess(nodes: nodes, truncated: truncated, app: app)
  }

  /// A tree read through XCTest's public snapshot API.
  private func snapshotSuccess(nodes: [SnapshotNode], truncated: Bool, app: XCUIApplication) -> Response {
    Response(
      ok: true,
      data: DataPayload(
        nodes: nodes,
        truncated: truncated,
        appState: appStateString(app),
        source: SnapshotSource.xctest
      )
    )
  }

  /// A SNAPSHOT_FAILED reply for an app whose tree cannot be read in its
  /// current state, or nil when a read is worth trying. A suspended app never
  /// answers — querying it only burns the request timeout — and an app that
  /// is not running has no tree. A snapshot does not launch or activate the
  /// app, so this is the honest answer rather than something to fix first.
  func unreadableSnapshotTarget(_ app: XCUIApplication) -> Response? {
    switch app.state {
    case .notRunning, .unknown, .runningBackgroundSuspended:
      return snapshotFailure(app, reason: "not attempted: the app cannot answer in this state")
    default:
      return nil
    }
  }

  /// The reply when no tree could be read at all. It used to be ok with an
  /// empty node list, which a caller cannot tell apart from a screen that is
  /// really empty, so a timed-out read looked like "nothing on screen". The
  /// app's state stays in the payload: a suspended app is the usual cause.
  func snapshotFailure(_ app: XCUIApplication, reason: String = "failed or timed out") -> Response {
    let state = appStateString(app)
    return Response(
      ok: false,
      data: DataPayload(appState: state),
      error: ErrorPayload(
        code: "SNAPSHOT_FAILED",
        message: "accessibility snapshot \(reason) (appState=\(state))"
      )
    )
  }

  func snapshotRect(from frame: CGRect) -> SnapshotRect {
    return SnapshotRect(
      x: Double(frame.origin.x),
      y: Double(frame.origin.y),
      width: Double(frame.size.width),
      height: Double(frame.size.height)
    )
  }

  // MARK: - Snapshot Filtering

  private func shouldInclude(
    snapshot: XCUIElementSnapshot,
    label: String,
    identifier: String,
    valueText: String?,
    options: SnapshotOptions,
    hittable: Bool,
    visible: Bool
  ) -> Bool {
    let type = snapshot.elementType
    let hasContent = !label.isEmpty || !identifier.isEmpty || (valueText != nil)
    if options.compact && type == .other && !hasContent && !hittable {
      if snapshot.children.count <= 1 { return false }
    }
    if options.interactiveOnly {
      if isScrollableContainer(snapshot, visible: visible) { return true }
      #if os(macOS)
        if !visible && type != .application {
          return false
        }
      #endif
      if interactiveTypes.contains(type) { return true }
      if hittable && type != .other { return true }
      if hasContent { return true }
      return false
    }
    if options.compact {
      return hasContent || hittable
    }
    return true
  }

  private func computedSnapshotHittable(
    _ snapshot: XCUIElementSnapshot,
    in context: SnapshotTraversalContext
  ) -> Bool {
    guard snapshot.isEnabled else { return false }
    let frame = snapshot.frame
    if frame.isNull || frame.isEmpty { return false }
    let center = CGPoint(x: frame.midX, y: frame.midY)
    if !context.viewport.contains(center) { return false }
    return !context.occlusion.isCovered(snapshot, at: center)
  }

  /// Runs a snapshot command's queries with a short XPC request timeout, so a
  /// query against an app that leaves the screen mid-command gives up after
  /// `snapshotRequestTimeout` instead of XCTest's 30s. That 30s wait would
  /// also hold every command queued behind this one on the main thread.
  /// `captureRootSnapshot` retries a slow snapshot of an app that is still
  /// in front with XCTest's full timeout, so a large tree still completes.
  func withSnapshotRequestTimeout(_ body: () -> Response) -> Response {
    var payload: Response?
    RunnerXCTestTimeouts.withXPCRequestTimeout(Self.snapshotRequestTimeout) {
      payload = body()
    }
    // The helper runs the block exactly once on every path that returns.
    return payload!
  }

  /// The app a snapshot should read. A no-bundle snapshot follows the
  /// screen. This is checked again here, just before the queries, because
  /// the alert check that comes first takes long enough for Home to land.
  private func snapshotTarget(_ requested: XCUIApplication, options: SnapshotOptions) -> XCUIApplication {
    options.followsScreen ? foregroundTarget(requested) : requested
  }

  private func makeSnapshotTraversalContext(
    app requested: XCUIApplication,
    options: SnapshotOptions
  ) -> SnapshotTraversalContext? {
    var app = requested
    var readStarted = Date()
    var captured = captureRootSnapshot(app: app, options: options)
    if captured == nil, options.followsScreen, app.state != .runningForeground {
      // The app left the screen while its snapshot was in flight. A
      // no-bundle snapshot reads whatever is in front, so read the app that
      // is in front now. The next command would do the same.
      let front = foregroundTarget(app)
      if front !== app {
        app = front
        readStarted = Date()
        captured = captureRootSnapshot(app: app, options: options)
      }
    }
    guard let (queryRoot, rootSnapshot) = captured else {
      return nil
    }
    let rootReadDuration = Date().timeIntervalSince(readStarted)

    let viewport = snapshotViewport(app: app, rootSnapshot: queryRoot === app ? rootSnapshot : nil)
    return SnapshotTraversalContext(
      app: app,
      queryRoot: queryRoot,
      rootSnapshot: rootSnapshot,
      rootReadDuration: rootReadDuration,
      viewport: viewport,
      occlusion: OcclusionIndex(root: rootSnapshot, viewport: viewport, isOccluding: isOccludingType),
      maxDepth: options.depth ?? Int.max
    )
  }

  /// Snapshots `app`, or the element `options.scope` names in it. Returns nil
  /// when the snapshot fails.
  ///
  /// A failure that took the whole request timeout means XCTest stopped
  /// waiting for the app to answer. If the app is still in front, the tree
  /// may simply be slow to serialize, so the snapshot is tried once more with
  /// XCTest's own timeout, the behavior before the short timeout existed.
  /// If the app has left the screen, it gets no second wait: a suspended app
  /// does not answer.
  private func captureRootSnapshot(
    app: XCUIApplication,
    options: SnapshotOptions
  ) -> (XCUIElement, XCUIElementSnapshot)? {
    let queryRoot = options.scope.flatMap { findScopeElement(app: app, scope: $0) } ?? app
    let started = ProcessInfo.processInfo.systemUptime
    if let root = try? queryRoot.snapshot() {
      return (queryRoot, root)
    }
    let elapsed = ProcessInfo.processInfo.systemUptime - started
    guard elapsed >= Self.snapshotRequestTimeout * 0.9 else {
      return nil
    }
    let state = app.state
    NSLog("DL_SNAPSHOT_REQUEST_TIMEOUT elapsed=%.1f state=%d", elapsed, state.rawValue)
    guard state == .runningForeground else {
      return nil
    }
    var root: XCUIElementSnapshot?
    RunnerXCTestTimeouts.withXPCRequestTimeout(RunnerXCTestTimeouts.defaultXPCRequestTimeout()) {
      root = try? queryRoot.snapshot()
    }
    return root.map { (queryRoot, $0) }
  }

  private func evaluateSnapshot(
    _ snapshot: XCUIElementSnapshot,
    in context: SnapshotTraversalContext
  ) -> SnapshotEvaluation {
    let label = aggregatedLabel(for: snapshot) ?? snapshot.label.trimmingCharacters(in: .whitespacesAndNewlines)
    let identifier = snapshot.identifier.trimmingCharacters(in: .whitespacesAndNewlines)
    let valueText = snapshotValueText(snapshot)
    return SnapshotEvaluation(
      label: label,
      identifier: identifier,
      valueText: valueText,
      hittable: computedSnapshotHittable(snapshot, in: context),
      focused: snapshotHasFocus(snapshot),
      selected: snapshotIsSelected(snapshot),
      visible: isVisibleInViewport(snapshot.frame, context.viewport)
    )
  }

  private func makeSnapshotNode(
    snapshot: XCUIElementSnapshot,
    evaluation: SnapshotEvaluation,
    depth: Int,
    index: Int,
    parentIndex: Int?
  ) -> SnapshotNode {
    return SnapshotNode(
      index: index,
      type: elementTypeName(snapshot.elementType),
      label: evaluation.label.isEmpty ? nil : evaluation.label,
      identifier: evaluation.identifier.isEmpty ? nil : evaluation.identifier,
      value: evaluation.valueText,
      placeholderValue: snapshotPlaceholderText(snapshot),
      rect: snapshotRect(from: snapshot.frame),
      enabled: snapshot.isEnabled,
      focused: evaluation.focused ? true : nil,
      selected: evaluation.selected ? true : nil,
      hittable: evaluation.hittable,
      depth: depth,
      parentIndex: parentIndex,
      hiddenContentAbove: nil,
      hiddenContentBelow: nil
    )
  }

  // Local extension (not in upstream agent-device): read the placeholder
  // string from an XCUIElementSnapshot. Used so maestro-runner YAML flows
  // can match by placeholder text (e.g. an RN TextInput placeholder).
  private func snapshotPlaceholderText(_ snapshot: XCUIElementSnapshot) -> String? {
    var placeholder: String?
    _ = RunnerObjCExceptionCatcher.catchException({
      if let value = (snapshot as! NSObject).value(forKey: "placeholderValue") as? String {
        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
        if !trimmed.isEmpty {
          placeholder = trimmed
        }
      }
    })
    return placeholder
  }

  private func isOccludingType(_ type: XCUIElement.ElementType) -> Bool {
    switch type {
    case .application, .window:
      return false
    default:
      return true
    }
  }

  private func snapshotValueText(_ snapshot: XCUIElementSnapshot) -> String? {
    Self.valueText(snapshot.value)
  }

  /// An element's value as a node publishes it; blank reads as no value.
  private static func valueText(_ value: Any?) -> String? {
    guard let value else { return nil }
    let text = String(describing: value).trimmingCharacters(in: .whitespacesAndNewlines)
    return text.isEmpty ? nil : text
  }

  /// The on-screen rect the hittable and visibility checks measure against.
  /// When the app's own snapshot is at hand, its windows are read from it
  /// rather than queried again: each query is another round trip, and another
  /// full request timeout if the app leaves the screen meanwhile.
  private func snapshotViewport(app: XCUIApplication, rootSnapshot: XCUIElementSnapshot?) -> CGRect {
    if let rootSnapshot {
      let window = rootSnapshot.children.first {
        $0.elementType == .window && !$0.frame.isNull && !$0.frame.isEmpty
      }
      if let window {
        return window.frame
      }
      if !rootSnapshot.frame.isNull && !rootSnapshot.frame.isEmpty {
        return rootSnapshot.frame
      }
    }
    let windows = app.windows.allElementsBoundByIndex
    if let window = windows.first(where: { $0.exists && !$0.frame.isNull && !$0.frame.isEmpty }) {
      return window.frame
    }
    let appFrame = app.frame
    if !appFrame.isNull && !appFrame.isEmpty {
      return appFrame
    }
    return .infinite
  }

  private func aggregatedLabel(for snapshot: XCUIElementSnapshot, depth: Int = 0) -> String? {
    if depth > 4 { return nil }
    let text = snapshot.label.trimmingCharacters(in: .whitespacesAndNewlines)
    if !text.isEmpty { return text }
    if let valueText = snapshotValueText(snapshot) { return valueText }
    for child in snapshot.children {
      if let childLabel = aggregatedLabel(for: child, depth: depth + 1) {
        return childLabel
      }
    }
    return nil
  }

  private func isVisibleInViewport(_ rect: CGRect, _ viewport: CGRect) -> Bool {
    if rect.isNull || rect.isEmpty { return false }
    return rect.intersects(viewport)
  }

  private func appendCollapsedTabFallbackNodes(
    to nodes: inout [SnapshotNode],
    containerSnapshot: XCUIElementSnapshot,
    resolveCandidates: () -> [CollapsedTabCandidate],
    viewport: CGRect,
    depth: Int,
    parentIndex: Int,
    nodeLimit: Int
  ) -> Bool {
    let fallbackNodes = collapsedTabFallbackNodes(
      for: containerSnapshot,
      resolveCandidates: resolveCandidates,
      viewport: viewport,
      startingIndex: nodes.count,
      depth: depth,
      parentIndex: parentIndex
    )
    if fallbackNodes.isEmpty { return false }
    let remaining = max(0, nodeLimit - nodes.count)
    if remaining == 0 { return true }
    nodes.append(contentsOf: fallbackNodes.prefix(remaining))
    return fallbackNodes.count > remaining
  }

  /// One live element a collapsed tab container may adopt, as the matching
  /// query's predicate read it.
  private struct CollapsedTabCandidate {
    let type: XCUIElement.ElementType
    let frame: CGRect
    let label: String
    let identifier: String
    let valueText: String?
    let enabled: Bool
    let focused: Bool
    let selected: Bool
  }

  // Ported from agent-device #3776 (MIT): a wide slider qualified for this
  // fallback, which then read every live descendant of the app one attribute
  // at a time on the XCTest main thread — one round trip each, which nothing
  // can cancel — so a crowded screen kept the runner busy until it was
  // treated as wedged. Candidates now come from one query whose predicate
  // applies the type, geometry and content rules and copies each match's
  // attributes as XCTest evaluates it, and the query starts only while the
  // time left before processingDeadline covers what the root snapshot took.
  // nil means it did not start.
  private func collapsedTabCandidates(
    context: SnapshotTraversalContext,
    processingDeadline: Date
  ) -> [CollapsedTabCandidate]? {
    let containerFrames = Self.snapshotDescendants(of: context.rootSnapshot)
      .filter { isCollapsedTabContainer($0) }
      .map(\.frame)
    if containerFrames.isEmpty { return [] }
    let expectedCost = max(Self.minimumQueryBudget, context.rootReadDuration)
    guard processingDeadline.timeIntervalSinceNow >= expectedCost else {
      NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_TAB_FALLBACK_QUERY_NOT_STARTED")
      return nil
    }
    var candidates: [CollapsedTabCandidate] = []
    let predicate = NSPredicate { object, _ in
      guard let attributes = object as? XCUIElementAttributes,
        Self.hasCollapsedTabContent(attributes),
        containerFrames.contains(where: {
          Self.isCollapsedTabCandidate(type: attributes.elementType, frame: attributes.frame, in: $0)
        })
      else {
        return false
      }
      candidates.append(self.collapsedTabCandidate(attributes))
      return true
    }
    let matches = safeSnapshotElementsQuery {
      context.queryRoot.descendants(matching: .any).matching(predicate).allElementsBoundByIndex
    }
    return matches.isEmpty ? [] : candidates
  }

  private func collapsedTabCandidate(_ attributes: XCUIElementAttributes) -> CollapsedTabCandidate {
    var focused = false
    _ = RunnerObjCExceptionCatcher.catchException({
      if let value = (attributes as? NSObject)?.value(forKey: "hasFocus") as? Bool {
        focused = value
      }
    })
    return CollapsedTabCandidate(
      type: attributes.elementType,
      frame: attributes.frame,
      label: attributes.label.trimmingCharacters(in: .whitespacesAndNewlines),
      identifier: attributes.identifier.trimmingCharacters(in: .whitespacesAndNewlines),
      valueText: Self.valueText(attributes.value),
      enabled: attributes.isEnabled,
      focused: focused,
      selected: attributes.isSelected
    )
  }

  /// Every descendant of `root` in its captured snapshot, without `root`.
  private static func snapshotDescendants(of root: XCUIElementSnapshot) -> [XCUIElementSnapshot] {
    var descendants: [XCUIElementSnapshot] = []
    var stack = Array(root.children.reversed())
    while let snapshot = stack.popLast() {
      descendants.append(snapshot)
      stack.append(contentsOf: snapshot.children.reversed())
    }
    return descendants
  }

  /// A collapsed tab container's item: a candidate type, smaller than the
  /// container, and centred inside it.
  private static func isCollapsedTabCandidate(
    type: XCUIElement.ElementType,
    frame: CGRect,
    in containerFrame: CGRect
  ) -> Bool {
    guard collapsedTabCandidateTypes.contains(type), !frame.isNull, !frame.isEmpty else {
      return false
    }
    if frame.equalTo(containerFrame) { return false }
    let area = max(CGFloat(1), frame.width * frame.height)
    let containerArea = max(CGFloat(1), containerFrame.width * containerFrame.height)
    return area < containerArea * 0.9 && containerFrame.contains(CGPoint(x: frame.midX, y: frame.midY))
  }

  /// Whether an element names something a flow can address: a label,
  /// identifier or value that is not blank.
  private static func hasCollapsedTabContent(_ attributes: XCUIElementAttributes) -> Bool {
    [attributes.label, attributes.identifier]
      .contains { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
      || valueText(attributes.value) != nil
  }

  private func collapsedTabFallbackNodes(
    for containerSnapshot: XCUIElementSnapshot,
    resolveCandidates: () -> [CollapsedTabCandidate],
    viewport: CGRect,
    startingIndex: Int,
    depth: Int,
    parentIndex: Int
  ) -> [SnapshotNode] {
    guard isCollapsedTabContainer(containerSnapshot) else { return [] }
    let containerFrame = containerSnapshot.frame

    let candidates = resolveCandidates().compactMap { candidate in
      collapsedTabCandidateNode(
        candidate: candidate,
        containerSnapshot: containerSnapshot,
        containerFrame: containerFrame,
        viewport: viewport
      )
    }
    .sorted { left, right in
      if left.rect.x != right.rect.x {
        return left.rect.x < right.rect.x
      }
      return left.rect.y < right.rect.y
    }

    if candidates.count < 2 { return [] }
    let rowMidpoints = candidates.map { $0.rect.y + ($0.rect.height / 2) }
    let rowSpread = (rowMidpoints.max() ?? 0) - (rowMidpoints.min() ?? 0)
    // Allow modest vertical jitter and short two-row wraps while still rejecting unrelated controls.
    if rowSpread > max(24.0, Double(containerFrame.height) * 0.6) { return [] }

    var seen = Set<String>()
    let uniqueCandidates = candidates.filter { node in
      let key = "\(node.type)-\(node.label ?? "")-\(node.identifier ?? "")-\(node.value ?? "")-\(node.rect.x)-\(node.rect.y)-\(node.rect.width)-\(node.rect.height)"
      if seen.contains(key) { return false }
      seen.insert(key)
      return true
    }
    if uniqueCandidates.count < 2 { return [] }

    return uniqueCandidates.enumerated().map { offset, node in
      SnapshotNode(
        index: startingIndex + offset,
        type: node.type,
        label: node.label,
        identifier: node.identifier,
        value: node.value,
        placeholderValue: node.placeholderValue,
        rect: node.rect,
        enabled: node.enabled,
        focused: node.focused,
        selected: node.selected,
        hittable: node.hittable,
        depth: depth,
        parentIndex: parentIndex,
        hiddenContentAbove: nil,
        hiddenContentBelow: nil
      )
    }
  }

  private func collapsedTabCandidateNode(
    candidate: CollapsedTabCandidate,
    containerSnapshot: XCUIElementSnapshot,
    containerFrame: CGRect,
    viewport: CGRect
  ) -> SnapshotNode? {
    if !Self.isCollapsedTabCandidate(type: candidate.type, frame: candidate.frame, in: containerFrame) {
      return nil
    }
    if sameSemanticElement(
      containerSnapshot: containerSnapshot,
      elementType: candidate.type,
      label: candidate.label,
      identifier: candidate.identifier
    ) {
      return nil
    }
    return SnapshotNode(
      index: 0,
      type: elementTypeName(candidate.type),
      label: candidate.label.isEmpty ? nil : candidate.label,
      identifier: candidate.identifier.isEmpty ? nil : candidate.identifier,
      value: candidate.valueText,
      placeholderValue: nil,
      rect: snapshotRect(from: candidate.frame),
      enabled: candidate.enabled,
      focused: candidate.focused ? true : nil,
      selected: candidate.selected ? true : nil,
      // Read from geometry: asking XCTest would be one more round trip per
      // item, the cost this fallback no longer pays.
      hittable: candidate.enabled && isVisibleInViewport(candidate.frame, viewport),
      depth: 0,
      parentIndex: nil,
      hiddenContentAbove: nil,
      hiddenContentBelow: nil
    )
  }

  private func snapshotHasFocus(_ snapshot: XCUIElementSnapshot) -> Bool {
    var focused = false
    _ = RunnerObjCExceptionCatcher.catchException({
      if let value = (snapshot as! NSObject).value(forKey: "hasFocus") as? Bool {
        focused = value
      }
    })
    return focused
  }

  private func snapshotIsSelected(_ snapshot: XCUIElementSnapshot) -> Bool {
    return snapshot.isSelected
  }

  /// A wide tab bar or segmented control that XCTest reports without
  /// children. Sliders no longer qualify (agent-device #3776): a wide slider
  /// has no items to adopt, and qualifying sent every screen with one
  /// through the descendant query.
  private func isCollapsedTabContainer(_ snapshot: XCUIElementSnapshot) -> Bool {
    if !snapshot.children.isEmpty { return false }
    let frame = snapshot.frame
    if frame.isNull || frame.isEmpty { return false }
    if frame.width < max(CGFloat(160), frame.height * 1.75) { return false }
    switch snapshot.elementType {
    case .tabBar, .segmentedControl:
      return true
    default:
      return false
    }
  }

  private func sameSemanticElement(
    containerSnapshot: XCUIElementSnapshot,
    elementType: XCUIElement.ElementType,
    label: String,
    identifier: String
  ) -> Bool {
    if containerSnapshot.elementType != elementType { return false }
    let containerLabel = containerSnapshot.label.trimmingCharacters(in: .whitespacesAndNewlines)
    let containerIdentifier = containerSnapshot.identifier
      .trimmingCharacters(in: .whitespacesAndNewlines)
    return containerLabel == label && containerIdentifier == identifier
  }

  private func safeSnapshotElementsQuery(_ fetch: () -> [XCUIElement]) -> [XCUIElement] {
    var elements: [XCUIElement] = []
    let exceptionMessage = RunnerObjCExceptionCatcher.catchException({
      elements = fetch()
    })
    if let exceptionMessage {
      NSLog(
        "AGENT_DEVICE_RUNNER_SNAPSHOT_QUERY_IGNORED_EXCEPTION=%@",
        exceptionMessage
      )
      return []
    }
    return elements
  }

  private func isScrollableContainer(_ snapshot: XCUIElementSnapshot, visible: Bool) -> Bool {
    if !visible { return false }
    if !Self.scrollContainerTypes.contains(snapshot.elementType) { return false }
    return !snapshot.children.isEmpty
  }
}
