import XCTest
import AgentDeviceSnapshotPresentation

#if os(macOS)
import CoreGraphics
#endif



struct RunnerCoordinateRefusal: Error {
  let message: String
  let hint: String?
}




struct RunnerGestureOutcomeUnknown: Error {
  let message: String
  let hint: String?
}

private struct RunnerUnsupportedOperationError: LocalizedError {
  let message: String

  var errorDescription: String? { message }
}

extension RunnerTests {

  enum PlannedGestureExecution: Equatable {
    case fastSwipe

    case sampled(schedule: String?)
#if os(iOS) && targetEnvironment(simulator)

    case screenEdgeTouch
#endif


    var schedule: String? {
      switch self {
      case .fastSwipe:
        return "endpoint-hold"
      case .sampled(let schedule):
        return schedule
#if os(iOS) && targetEnvironment(simulator)
      case .screenEdgeTouch:
        return "edge-ease-in"
#endif
      }
    }
  }

  enum SynthesizedDragProfile: Equatable {
    case controlledScroll
    case fastSwipe
  }

  func scrollDragProfile(
    releaseBehavior: ScrollReleaseBehavior?
  ) -> SynthesizedDragProfile {
    releaseBehavior == .inertial ? .fastSwipe : .controlledScroll
  }

  struct TouchVisualizationFrame {
    let x: Double
    let y: Double
    let referenceWidth: Double
    let referenceHeight: Double
  }

  struct DragVisualizationFrame {
    let x: Double
    let y: Double
    let x2: Double
    let y2: Double
    let referenceWidth: Double
    let referenceHeight: Double
  }

  struct DragPoints {
    let x: Double
    let y: Double
    let x2: Double
    let y2: Double
  }

  struct SynthesizedDragPlan {
    let points: DragPoints
    let context: SynthesizedCoordinateContext

  }

  struct SelectorElementMatch {
    let element: XCUIElement?
    let isAmbiguous: Bool
    let usedNonHittableFallback: Bool
  }

#if os(iOS)


  enum TouchDispatch {
    case sent
    case notSent(message: String, hint: String?)
    case interrupted(message: String, hint: String?)



    init(synthesisFailure failure: String?, dispatched: Bool) {
      guard let failure else {
        self = .sent
        return
      }
      self = dispatched ? .interrupted(message: failure, hint: nil) : .notSent(message: failure, hint: nil)
    }

  }



  enum PreparedTouch {
    case ready(@MainActor () throws -> TouchDispatch)
    case notSent(message: String, hint: String?)




    init(notSent refusal: RunnerInteractionOutcome) {
      switch refusal {
      case .performed:
        preconditionFailure("a performed gesture is not a refusal before dispatch")
      case .unsupported(let message, let hint), .notDispatched(let message, let hint):
        self = .notSent(message: message, hint: hint)
      }
    }
  }




  @MainActor
  func prepareBackGesture(app: XCUIApplication, context: SynthesizedCoordinateContext) throws -> PreparedTouch {
#if targetEnvironment(simulator)
    return try prepareScreenEdgeBackSwipe(app: app, surface: context.geometry.windowOnScreen.rect)
#else
    return try prepareDeviceBackFling(app: app, context: context)
#endif
  }



  static func backFlingPlan(
    from start: CGPoint,
    to end: CGPoint,
    durationMs: Double,
    across surface: CGRect,
    contactOrigin: String?
  ) -> RunnerGesturePlan {
    RunnerGesturePlan(
      topology: "single",
      intent: "fling",
      executionProfile: "endpoint-hold",
      contactOrigin: contactOrigin,
      durationMs: durationMs,
      viewport: RunnerGestureViewport(
        x: Double(surface.minX), y: Double(surface.minY),
        width: Double(surface.width), height: Double(surface.height)
      ),
      pointers: [
        RunnerGesturePointer(pointerId: 0, samples: [
          RunnerGestureSample(offsetMs: 0, point: RunnerGesturePoint(x: Double(start.x), y: Double(start.y))),
          RunnerGestureSample(offsetMs: durationMs, point: RunnerGesturePoint(x: Double(end.x), y: Double(end.y))),
        ]),
      ]
    )
  }







  static let deviceBackFlingDurationMs = 200.0

  @MainActor
  func prepareDeviceBackFling(app: XCUIApplication, context: SynthesizedCoordinateContext) throws -> PreparedTouch {
    let surface = context.geometry.windowOnScreen.rect
    let plan = Self.backFlingPlan(
      from: CGPoint(x: surface.minX + 2, y: surface.midY),
      to: CGPoint(x: surface.minX + surface.width * 0.9, y: surface.midY),
      durationMs: Self.deviceBackFlingDurationMs,
      across: surface,
      contactOrigin: nil
    )
    let planned: NativePlannedGesture
    switch try nativePlannedGesture(app: app, plan: plan, gesture: "back drag") {
    case .resolved(let resolved): planned = resolved
    case .refused(let outcome): return PreparedTouch(notSent: outcome)
    }
    return .ready {
      var dispatched: ObjCBool = false
      let failure = RunnerSynthesizedGesture.synthesizeGesture(
        withApplication: app,
        resolvedWindow: planned.context.resolvedWindow,
        interfaceOrientation: planned.orientation,
        pointerSamples: planned.pointerSamples,
        dispatched: &dispatched
      )
      return TouchDispatch(synthesisFailure: failure, dispatched: dispatched.boolValue)
    }
  }
#endif

  func performAppSwitcherGesture(app: XCUIApplication) throws {
    if pressTvRemote(.home) {
      sleepFor(resolveTvRemoteDoublePressDelay())
      _ = pressTvRemote(.home)
      return
    }
    try performCoordinateAppSwitcherGesture(app: app)
  }

  private func performCoordinateAppSwitcherGesture(app: XCUIApplication) throws {
#if !os(tvOS)
    let target = try normalizedOffsetAnchor(app: app)
    let start = target.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.99))
    let end = target.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.7))
    start.press(forDuration: 0.6, thenDragTo: end)
#endif
  }

  func pressHomeButton() {
#if os(macOS)
    return
#else
    if pressTvRemote(.home) {
      return
    }
    XCUIDevice.shared.press(.home)
#endif
  }

#if os(watchOS)
  static let actionButtonUnavailableHint = "The Action Button is on Apple Watch Ultra. Open an Apple Watch Ultra simulator."
#else
  static let actionButtonUnavailableHint = "The Action Button is on iPhone 15 Pro and later and iPad Pro (M4) and later. Assign a Shortcut or App Intent to it in Settings > Action Button."
#endif







  @discardableResult
  func pressActionButton() -> Bool {
#if os(iOS) || os(watchOS)
    guard #available(iOS 16.0, watchOS 9.0, *) else { return false }
    guard XCUIDevice.shared.hasHardwareButton(.action) else { return false }
    XCUIDevice.shared.press(.action)
    return true
#else
    return false
#endif
  }








  @discardableResult
  func pressVolumeButton(_ button: CommandType) -> Bool {
#if os(iOS) && !targetEnvironment(simulator)
    switch button {
    case .volumeUp:
      XCUIDevice.shared.press(.volumeUp)
      return true
    case .volumeDown:
      XCUIDevice.shared.press(.volumeDown)
      return true
    default:
      return false
    }
#else
    return false
#endif
  }





  static func findTextPredicate(_ text: String) -> NSPredicate {
    let editableTypes = [
      XCUIElement.ElementType.textField,
      .secureTextField,
      .searchField,
      .textView,
    ].map(\.rawValue)
    let typed = NSPredicate(
      format: "elementType IN %@ AND enabled == YES AND value != placeholderValue",
      editableTypes
    )
    return NSCompoundPredicate(orPredicateWithSubpredicates: [
      NSPredicate(format: "identifier CONTAINS[c] %@", text),
      NSCompoundPredicate(andPredicateWithSubpredicates: [
        NSCompoundPredicate(notPredicateWithSubpredicate: typed),
        NSPredicate(format: "label CONTAINS[c] %@ OR value CONTAINS[c] %@", text, text),
      ]),
      NSCompoundPredicate(andPredicateWithSubpredicates: [
        typed,
        NSPredicate(format: "label CONTAINS[c] %@ AND label != value", text),
      ]),
    ])
  }

  func findElement(app: XCUIApplication, text: String) throws -> XCUIElement? {
    let predicate = Self.findTextPredicate(text)
    return try elementQueries(app: app, matching: .any)
      .lazy
      .map { $0.matching(predicate).firstMatch }
      .first { $0.exists }
  }

  func findElement(
    app: XCUIApplication,
    selectorKey: String,
    selectorValue: String,
    allowNonHittableFallback: Bool = false,
    expectedPoint: CGPoint? = nil,
    rawMatchPolicy: DirectSelectorRawMatchPolicy = .rejectDistinctMatches
  ) throws -> SelectorElementMatch {
    let value = selectorValue.trimmingCharacters(in: .whitespacesAndNewlines)
    guard !value.isEmpty else {
      return SelectorElementMatch(element: nil, isAmbiguous: false, usedNonHittableFallback: false)
    }
    guard let predicate = Self.selectorPredicate(key: selectorKey, value: value) else {
      return SelectorElementMatch(element: nil, isAmbiguous: false, usedNonHittableFallback: false)
    }

    let matches = try elementQueries(app: app, matching: .any)
      .flatMap { $0.matching(predicate).allElementsBoundByIndex }
      .filter(\.exists)
    let facts = try matches.map { element in
      let isHittable = element.isHittable
      let containsExpectedPoint = expectedPoint.map(element.frame.contains) ?? true
      return SelectorCandidateFacts(
        isHittable: isHittable,
        hasTappableFrame: allowNonHittableFallback && !isHittable && containsExpectedPoint
          ? try hasTappableFrame(app: app, element: element) : false,
        containsExpectedPoint: containsExpectedPoint
      )
    }
    switch classifyDirectSelectorCandidates(
      facts,
      allowNonHittableFallback: allowNonHittableFallback,
      filtersByExpectedPoint: expectedPoint != nil,
      rawMatchPolicy: rawMatchPolicy
    ) {
    case .noMatch:
      return SelectorElementMatch(element: nil, isAmbiguous: false, usedNonHittableFallback: false)
    case .ambiguous:
      return SelectorElementMatch(element: nil, isAmbiguous: true, usedNonHittableFallback: false)
    case let .selected(index, usedNonHittableFallback):
      return SelectorElementMatch(
        element: matches[index],
        isAmbiguous: false,
        usedNonHittableFallback: usedNonHittableFallback
      )
    }
  }








  private func hasTappableFrame(app: XCUIApplication, element: XCUIElement) throws -> Bool {
    let windowFrame = try requestLitPanel == nil
      ? readableAppFrame(app: app)
      : requireRequestLitPanelSurface(app: app).geometry.windowOnScreen.rect
    let frame = element.frame
    if frame.isEmpty {
      return false
    }
    return TapPointPolicy.isAllowed(elementFrame: frame, windowFrame: windowFrame)
  }
























  func resolveRunnerWindow(app: XCUIApplication) throws -> (window: XCUIElement?, frame: CGRect) {
    try resolveRunnerWindow(app: app) { heldAppFrame(app: $0) ?? .zero }
  }



  func resolveCoordinateWindow(app: XCUIApplication) throws -> (window: XCUIElement?, frame: CGRect) {
    try resolveRunnerWindow(app: app, appFrame: readableAppFrame)
  }

  private func resolveRunnerWindow(
    app: XCUIApplication,
    appFrame: (XCUIApplication) throws -> CGRect
  ) throws -> (window: XCUIElement?, frame: CGRect) {
    if requestLitPanel != nil {
      let booked = try requireRequestLitPanelSurface(app: app)
      return (booked.window, booked.geometry.windowOnScreen.rect)
    }
    guard let resolved = resolveRunnerWindowElement(app: app) else { return (nil, try appFrame(app)) }
    return (resolved.window, resolved.frame)
  }






  func heldAppFrame(app: XCUIApplication) -> CGRect? {
#if os(iOS)
    var frame = CGRect.null
    let held = holdingRecordedIssues { frame = app.frame }
    let finite = !frame.isNull && !frame.isInfinite
      && frame.minX.isFinite && frame.minY.isFinite && frame.maxX.isFinite && frame.maxY.isFinite
    guard held.issues.isEmpty, held.exceptionMessage == nil, finite else { return nil }
    return frame
#else
    return app.frame
#endif
  }



  func readableAppFrame(app: XCUIApplication) throws -> CGRect {
#if os(iOS)
    guard let frame = heldAppFrame(app: app) else { throw unreadableTreeRefusal }
    return frame
#else
    return app.frame
#endif
  }




  func resolveRunnerWindowElement(app: XCUIApplication) -> (window: XCUIElement, frame: CGRect)? {
    if requestLitPanel != nil {
      guard bookRequestLitPanelSurface(app: app) == nil, let booked = litPanelState.surface else { return nil }
      return (booked.window, booked.geometry.windowOnScreen.rect)
    }
    for window in app.windows.allElementsBoundByIndex where window.exists {
      let frame = window.frame
      if !frame.isEmpty {
        return (window, frame)
      }
    }
    return nil
  }

  func onScreenWindowFrame(app: XCUIApplication) throws -> CGRect {
    try resolveRunnerWindow(app: app).frame
  }

  static func selectorPredicate(key: String, value: String) -> NSPredicate? {
    switch key {
    case "id":
      return NSPredicate(format: "identifier ==[c] %@", value)
    case "label":
      return NSPredicate(format: "label ==[c] %@", value)
    case "value":
      return NSPredicate(format: "value ==[c] %@", value)
    case "text":
      return NSPredicate(format: "label ==[c] %@ OR identifier ==[c] %@ OR value ==[c] %@", value, value, value)
    default:
      return nil
    }
  }





  func probeElementHittability(app: XCUIApplication, selectorKey: String, selectorValue: String) throws -> Response {
    let value = selectorValue.trimmingCharacters(in: .whitespacesAndNewlines)
    guard !value.isEmpty, let predicate = Self.selectorPredicate(key: selectorKey, value: value) else {
      return Response(ok: true, data: DataPayload(found: false, matchCount: 0))
    }
    let matches = try elementQueries(app: app, matching: .any)
      .flatMap { $0.matching(predicate).allElementsBoundByIndex }
      .filter(\.exists)
    guard matches.count == 1, let element = matches.first else {
      return Response(ok: true, data: DataPayload(found: !matches.isEmpty, matchCount: matches.count))
    }
    return Response(
      ok: true,
      data: DataPayload(
        found: true,
        matchCount: 1,
        hittable: element.isHittable,
        rect: SnapshotRect(element.frame)
      )
    )
  }

  func queryElement(app: XCUIApplication, selectorKey: String, selectorValue: String) throws -> Response {





    let match = try findElement(
      app: app,
      selectorKey: selectorKey,
      selectorValue: selectorValue,
      rawMatchPolicy: .preferHittableMatch
    )
    if match.isAmbiguous {
      return Response(ok: false, error: ErrorPayload(code: "AMBIGUOUS_MATCH", message: "selector matched multiple elements"))
    }
    guard let element = match.element else {
      return Response(ok: true, data: DataPayload(found: false, nodes: []))
    }

    let label = element.label.trimmingCharacters(in: .whitespacesAndNewlines)
    let identifier = element.identifier.trimmingCharacters(in: .whitespacesAndNewlines)
    let valueText = String(describing: element.value ?? "")
      .trimmingCharacters(in: .whitespacesAndNewlines)
    let node = SnapshotPresentation.singleElementRead(
      RawAXNode(
        index: 0,
        type: elementTypeName(element.elementType),
        label: label.isEmpty ? nil : label,
        identifier: identifier.isEmpty ? nil : identifier,
        value: valueText.isEmpty ? nil : valueText,
        rect: SnapshotRect(element.frame),
        enabled: element.isEnabled,
        focused: nil,
        selected: element.isSelected ? true : nil,
        hittable: element.isHittable,
        depth: 0,
        parentIndex: nil,
        hiddenContentAbove: nil,
        hiddenContentBelow: nil
      )
    )
    return Response(
      ok: true,
      data: DataPayload(
        text: readableText(for: element),
        found: true,
        nodes: [node]
      )
    )
  }



  func smallestElementFirst(_ left: any XCUIElementAttributes, _ right: any XCUIElementAttributes) -> Bool {
    let leftArea = max(1, left.frame.width * left.frame.height)
    let rightArea = max(1, right.frame.width * right.frame.height)
    if leftArea != rightArea {
      return leftArea < rightArea
    }
    if left.frame.minY != right.frame.minY {
      return left.frame.minY < right.frame.minY
    }
    if left.frame.minX != right.frame.minX {
      return left.frame.minX < right.frame.minX
    }
    return left.elementType.rawValue < right.elementType.rawValue
  }

  func readTextAt(app: XCUIApplication, x: Double, y: Double) throws -> String? {
    let point = CGPoint(x: x, y: y)
    let textInputCandidates = try textInputCandidatesAt(app: app, point: point, contentTranslation: liveContentTranslation(app: app))
      .map(\.element)
    for element in textInputCandidates where prefersExpandedTextRead(element) {
      if let text = readableText(for: element) {
        return text
      }
    }

    let candidates = try elementQueries(app: app, matching: .any)
      .flatMap { $0.allElementsBoundByIndex }
      .filter { element in
        element.exists && !element.frame.isEmpty && element.frame.contains(point)
      }
      .sorted { smallestElementFirst($0, $1) }

    for element in candidates where prefersExpandedTextRead(element) {
      if let text = readableText(for: element) {
        return text
      }
    }
    for element in candidates {
      if let text = readableText(for: element) {
        return text
      }
    }
    return nil
  }

  private func readableText(for element: XCUIElement) -> String? {
    let label = element.label.trimmingCharacters(in: .whitespacesAndNewlines)
    let identifier = element.identifier.trimmingCharacters(in: .whitespacesAndNewlines)
    let valueText = String(describing: element.value ?? "")
      .trimmingCharacters(in: .whitespacesAndNewlines)
    switch element.elementType {
    case .textField, .secureTextField, .searchField, .textView:
      if !valueText.isEmpty { return valueText }
      if !label.isEmpty { return label }
      return identifier.isEmpty ? nil : identifier
    default:
      if !label.isEmpty { return label }
      if !valueText.isEmpty { return valueText }
      return identifier.isEmpty ? nil : identifier
    }
  }

  private func prefersExpandedTextRead(_ element: XCUIElement) -> Bool {
    switch element.elementType {
    case .textField, .secureTextField, .searchField, .textView:
      return true
    default:
      return false
    }
  }



  func tapAt(
    app: XCUIApplication,
    x: Double,
    y: Double,
    context: SynthesizedCoordinateContext? = nil
  ) throws -> RunnerInteractionOutcome {
    if let outcome = selectFocusedTvElement(app: app, point: CGPoint(x: x, y: y), action: "tap") {
      return outcome
    }
#if os(iOS)
    return try runOnMainActor({ try tapAtScreenPoint(app: app, x: x, y: y, context: context) }).get()
#else
    return try performCoordinateTap(app: app, x: x, y: y)
#endif
  }

#if os(iOS)






  @MainActor
  private func tapAtScreenPoint(
    app: XCUIApplication,
    x: Double,
    y: Double,
    context: SynthesizedCoordinateContext?
  ) throws -> RunnerInteractionOutcome {
    guard let context = try context ?? synthesizedCoordinateContext(app: app) else {

      _ = try readableAppFrame(app: app)
      return try performCoordinateTap(app: app, x: x, y: y, treeProven: true)
    }
    guard context.treeUnreadable else {
      return try performCoordinateTap(app: app, x: x, y: y, treeProven: true)
    }
    switch try performSynthesizedTapGesture(app: app, x: x, y: y, context: context) {
    case .performed:
      return .performed
    case .xctestFallback(let message, let hint):
      throw RunnerCoordinateRefusal(message: message, hint: hint)
    case .refused(_, let refusal):
      let text = refusal.refusalText
      throw RunnerCoordinateRefusal(message: text?.message ?? "synthesized tap refused", hint: text?.hint)
    }
  }

  var unreadableTreeRefusal: RunnerCoordinateRefusal {
    RunnerCoordinateRefusal(
      message: "XCTest cannot anchor a coordinate gesture: the app's accessibility tree answered no window and no frame",
      hint: "XCTest cannot snapshot this app's accessibility tree, so the runner dispatched nothing. Retry on a shallower screen, or run snapshot -i and act on a ref once its capture reads back."
    )
  }





  private func requireReadableTreeAnchor(app: XCUIApplication) throws -> XCUIElement {
    if requestLitPanel != nil {
      return try requireRequestLitPanelSurface(app: app).window
    }
    if let resolved = resolveRunnerWindowElement(app: app) {
      return resolved.window
    }
    _ = try readableAppFrame(app: app)
    return app
  }
#endif

  func mouseClickAt(app: XCUIApplication, x: Double, y: Double, button: String) throws {
#if os(macOS)
    let coordinate = try interactionCoordinate(app: app, x: x, y: y)
    switch button {
    case "primary":
      coordinate.tap()
    case "secondary":
      coordinate.rightClick()
    case "middle":
      throw RunnerUnsupportedOperationError(message: "middle mouse button is not supported")
    default:
      throw RunnerUnsupportedOperationError(message: "unsupported mouse button: \(button)")
    }
#elseif os(tvOS)
    throw RunnerUnsupportedOperationError(message: "mouseClick is not supported on tvOS")
#else
    throw RunnerUnsupportedOperationError(message: "mouseClick is only supported on macOS")
#endif
  }

  func desktopScrollAt(
    app: XCUIApplication,
    x: Double,
    y: Double,
    direction: RunnerScrollDirection,
    pixels: Double,
    durationMs: Double?
  ) throws {
#if os(macOS)
    let events = desktopScrollWheelDeltaEvents(
      direction: direction,
      pixels: pixels,
      durationMs: durationMs
    )

    let coordinate = try interactionCoordinate(app: app, x: x, y: y)
    let interval = desktopScrollEventIntervalSeconds(durationMs: durationMs, eventCount: events.count)
    for (index, deltas) in events.enumerated() {


      coordinate.scroll(
        byDeltaX: CGFloat(deltas.horizontal),
        deltaY: CGFloat(deltas.vertical)
      )
      if interval > 0 && index < events.count - 1 {
        Thread.sleep(forTimeInterval: interval)
      }
    }
#elseif os(tvOS)
    throw RunnerUnsupportedOperationError(message: "desktopScroll is not supported on tvOS")
#else
    throw RunnerUnsupportedOperationError(message: "desktopScroll is only supported on macOS")
#endif
  }

  func desktopScrollWheelDeltas(
    direction: RunnerScrollDirection,
    pixels: Double
  ) -> (vertical: Int32, horizontal: Int32) {
    let magnitude = Int32(max(1, min(Double(Int32.max), pixels.rounded())))
    switch direction {
    case .up:
      return (vertical: magnitude, horizontal: 0)
    case .down:
      return (vertical: -magnitude, horizontal: 0)
    case .left:
      return (vertical: 0, horizontal: magnitude)
    case .right:
      return (vertical: 0, horizontal: -magnitude)
    }
  }

  func desktopScrollWheelDeltaEvents(
    direction: RunnerScrollDirection,
    pixels: Double,
    durationMs: Double?
  ) -> [(vertical: Int32, horizontal: Int32)] {
    let totalDeltas = desktopScrollWheelDeltas(direction: direction, pixels: pixels)
    let magnitude = max(abs(Int(totalDeltas.vertical)), abs(Int(totalDeltas.horizontal)))
    let duration = max(0, durationMs ?? 0)
    let requestedEventCount = duration > 0 ? Int(ceil(duration / 16.0)) : 1
    let eventCount = max(1, min(magnitude, requestedEventCount))
    guard eventCount > 1 else {
      return [totalDeltas]
    }

    if totalDeltas.vertical != 0 {
      return distributeDesktopScrollDelta(totalDeltas.vertical, eventCount: eventCount)
        .map { (vertical: $0, horizontal: 0) }
    }
    return distributeDesktopScrollDelta(totalDeltas.horizontal, eventCount: eventCount)
      .map { (vertical: 0, horizontal: $0) }
  }

  func desktopScrollEventIntervalSeconds(durationMs: Double?, eventCount: Int) -> TimeInterval {
    guard let durationMs, durationMs > 0, eventCount > 1 else { return 0 }
    return (durationMs / 1000.0) / Double(eventCount - 1)
  }

  private func distributeDesktopScrollDelta(_ delta: Int32, eventCount: Int) -> [Int32] {
    let sign: Int32 = delta < 0 ? -1 : 1
    let magnitude = abs(Int(delta))
    let base = magnitude / eventCount
    let remainder = magnitude % eventCount
    return (0..<eventCount).map { index in
      sign * Int32(base + (index < remainder ? 1 : 0))
    }
  }

  func doubleTapAt(app: XCUIApplication, x: Double, y: Double) throws -> RunnerInteractionOutcome {
    if let outcome = selectFocusedTvElement(app: app, point: CGPoint(x: x, y: y), action: "double tap") {
      guard case .performed = outcome else { return outcome }
      sleepFor(0.1)
      _ = pressTvRemote(.select)
      return .performed
    }
    return try performCoordinateDoubleTap(app: app, x: x, y: y)
  }

  func longPressAt(app: XCUIApplication, x: Double, y: Double, duration: TimeInterval) throws -> RunnerInteractionOutcome {
    if let outcome = longSelectFocusedTvElement(app: app, point: CGPoint(x: x, y: y), duration: duration) {
      return outcome
    }
    return try performCoordinateLongPress(app: app, x: x, y: y, duration: duration)
  }

  func dragAt(
    app: XCUIApplication,
    x: Double,
    y: Double,
    x2: Double,
    y2: Double,
    holdDuration: TimeInterval
  ) throws -> RunnerInteractionOutcome {

    let dx = x2 - x
    let dy = y2 - y
    let button: TvRemoteButton = abs(dx) > abs(dy)
      ? (dx > 0 ? .right : .left)
      : (dy > 0 ? .down : .up)
    if pressTvRemote(button) {
      return .performed
    }
    return try performCoordinateDrag(app: app, x: x, y: y, x2: x2, y2: y2, holdDuration: holdDuration)
  }

  private func performCoordinateTap(
    app: XCUIApplication,
    x: Double,
    y: Double,
    treeProven: Bool = false
  ) throws -> RunnerInteractionOutcome {
#if os(tvOS)
    return .unsupported(
      message: "coordinate tap is not supported on tvOS; move focus with swipe or scroll, then select the focused element",
      hint: "tvOS has no coordinate input; move focus with swipe/scroll to the target, then select it."
    )
#else
    try interactionCoordinate(app: app, x: x, y: y, treeProven: treeProven).tap()
    return .performed
#endif
  }

  private func performCoordinateDoubleTap(app: XCUIApplication, x: Double, y: Double) throws -> RunnerInteractionOutcome {
#if os(tvOS)
    return .unsupported(
      message: "coordinate double tap is not supported on tvOS; move focus with swipe or scroll, then select the focused element",
      hint: "tvOS has no coordinate input; move focus with swipe/scroll to the target, then select it."
    )
#else
    try interactionCoordinate(app: app, x: x, y: y).doubleTap()
    return .performed
#endif
  }

  private func performCoordinateLongPress(app: XCUIApplication, x: Double, y: Double, duration: TimeInterval) throws -> RunnerInteractionOutcome {
#if os(tvOS)
    return .unsupported(
      message: "coordinate long press is not supported on tvOS; move focus with swipe or scroll, then long-select the focused element",
      hint: "tvOS has no coordinate input; move focus with swipe/scroll to the target, then long-select it."
    )
#else
    try interactionCoordinate(app: app, x: x, y: y).press(forDuration: duration)
    return .performed
#endif
  }

  private func performCoordinateDrag(
    app: XCUIApplication,
    x: Double,
    y: Double,
    x2: Double,
    y2: Double,
    holdDuration: TimeInterval
  ) throws -> RunnerInteractionOutcome {
#if os(tvOS)
    return .unsupported(
      message: "coordinate drag is not supported on tvOS",
      hint: "tvOS has no coordinate input; use remote-driven swipe/scroll to move focus instead."
    )
#else
    let start = try interactionCoordinate(app: app, x: x, y: y)
    let end = try interactionCoordinate(app: app, x: x2, y: y2, treeProven: true)
    start.press(forDuration: holdDuration, thenDragTo: end)
    return .performed
#endif
  }

#if !os(tvOS)


  private func normalizedOffsetAnchor(app: XCUIApplication) throws -> XCUIElement {
#if os(iOS)
    return try requireReadableTreeAnchor(app: app)
#else
    return try resolveCoordinateWindow(app: app).window ?? app
#endif
  }


  private func interactionCoordinate(
    app: XCUIApplication,
    x: Double,
    y: Double,
    treeProven: Bool = false
  ) throws -> XCUICoordinate {
#if os(iOS)
    if !treeProven {
      _ = try requireReadableTreeAnchor(app: app)
    }








    if requestLitPanel == nil {
      let origin = app.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0))
      return origin.withOffset(CGVector(dx: x, dy: y))
    }
    let booked = try requireRequestLitPanelSurface(app: app)
    let origin = booked.window.coordinate(withNormalizedOffset: .zero)
    let point = booked.geometry.contentPoint(from: SurfacePoint(CGPoint(x: x, y: y))).point
    return origin.withOffset(CGVector(dx: point.x, dy: point.y))
#else
    let resolved = try resolveCoordinateWindow(app: app)
    let root = resolved.window ?? app
    let origin = root.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0))
    let offsetX = x - Double(resolved.frame.origin.x)
    let offsetY = y - Double(resolved.frame.origin.y)
    return origin.withOffset(CGVector(dx: offsetX, dy: offsetY))
#endif
  }
#endif
}
