import XCTest

extension RunnerTests {
  func focusedTextInput(app: XCUIApplication) -> XCUIElement? {
#if os(iOS)



    return nil
#else
    return safely("FOCUSED_INPUT_QUERY") {
      let candidates = app
        .descendants(matching: .any)
        .matching(NSPredicate(format: "hasKeyboardFocus == 1"))
        .allElementsBoundByIndex
      for candidate in candidates where candidate.exists {
        switch candidate.elementType {
        case .textField, .secureTextField, .searchField, .textView:
          return candidate
        default:
          continue
        }
      }
      return nil
    }
#endif
  }

  func waitForTextEntryReadiness(
    app: XCUIApplication,
    target: TextEntryTarget,
    timeout: TimeInterval = TextEntryTiming.readinessTimeout
  ) throws -> XCUIElement? {
#if os(iOS)
    let candidate = try resolveTextEntryInput(app: app, target: target)?.element
    let keyboardVisibleAtEntry = isKeyboardVisible(app: app)
    let deadline = Date().addingTimeInterval(timeout)
    var hardwareKeyboardFallback = Date().addingTimeInterval(
      min(TextEntryTiming.hardwareKeyboardFallbackTimeout, timeout)
    )
    var sawSoftwareKeyboard = false
    while Date() < deadline {





      if keyboardBecameVisible(app: app, wasVisibleAtEntry: keyboardVisibleAtEntry) {
        return candidate
      }
      sawSoftwareKeyboard = sawSoftwareKeyboard || keyboardElementExists(app: app)






      if !sawSoftwareKeyboard, Date() >= hardwareKeyboardFallback, let candidate {
        if keyboardFocusConfirmed(app: app, element: candidate) {
          return candidate
        }
        hardwareKeyboardFallback = Date().addingTimeInterval(
          TextEntryTiming.hardwareKeyboardFallbackTimeout
        )
      }
      sleepFor(TextEntryTiming.pollInterval)
    }
    return candidate
#else
    return try resolveTextEntryInput(app: app, target: target)?.element
#endif
  }















  func waitForTextEntryReadinessAfterTap(app: XCUIApplication, element: XCUIElement) throws {
#if os(iOS)
    if waitForTextEntryFocus(app: app, element: element, timeout: TextEntryTiming.readinessTimeout) {
      return
    }
    guard let settled = safely("TEXT_ENTRY_READINESS_FRAME", {
      ResolvedTextEntryInput(reading: element, contentTranslation: liveContentTranslation(app: app))
    }) else {
      return
    }
    try retapAt(read: settled, app: app, element: element)
#endif
  }


  func retapAt(read: ResolvedTextEntryInput, app: XCUIApplication, element: XCUIElement) throws {
    guard let frame = read.frameOnScreen, !frame.isEmpty else {
      NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_RETAP skipped reason=%@", read.frameOnScreen == nil ? "no-screen-frame" : "empty-frame")
      return
    }
    NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_RETAP x=%.1f y=%.1f", frame.midX, frame.midY)
    _ = try tapAt(app: app, x: frame.midX, y: frame.midY)
    _ = waitForTextEntryFocus(app: app, element: element, timeout: TextEntryTiming.readinessTimeout)
  }

  private func waitForTextEntryFocus(app: XCUIApplication, element: XCUIElement, timeout: TimeInterval) -> Bool {
    let deadline = Date().addingTimeInterval(timeout)
    while Date() < deadline {
      if keyboardFocusConfirmed(app: app, element: element) {
        return true
      }
      sleepFor(TextEntryTiming.pollInterval)
    }
    return keyboardFocusConfirmed(app: app, element: element)
  }

  func keyboardBecameVisible(app: XCUIApplication, wasVisibleAtEntry: Bool) -> Bool {
    return !wasVisibleAtEntry && isKeyboardVisible(app: app)
  }












  func keyboardFocusConfirmed(app: XCUIApplication, element: XCUIElement) -> Bool {
#if os(iOS)

    return ResolvedTextEntryInput(reading: element, contentTranslation: .unknown)
      .map { keyboardFocusConfirmed(app: app, read: $0) } ?? false
#else
    return false
#endif
  }

#if os(iOS)

  func keyboardFocusConfirmed(app: XCUIApplication, read: ResolvedTextEntryInput) -> Bool {



    guard let expected = read.snapshot, !expected.frame.isEmpty else {
      return false
    }
    return safely("TEXT_ENTRY_FOCUS_CONFIRMED", false) {
      let focused = app
        .descendants(matching: .any)
        .matching(NSPredicate(format: "hasKeyboardFocus == 1"))
        .firstMatch
      guard focused.exists, let observed = try? focused.snapshot() else {
        return false
      }
      return observed.identifier == expected.identifier && observed.frame == expected.frame
    }
  }
#endif

  private func keyboardElementExists(app: XCUIApplication) -> Bool {
#if os(iOS)
    return safely("KEYBOARD_EXISTS", false) { app.keyboards.firstMatch.exists }
#else
    return false
#endif
  }
}
