import XCTest




extension RunnerTests {
  enum TextEntryFailure: String {
    case notFocused = "TEXT_INPUT_NOT_FOCUSED"
    case synthesisUnavailable = "TEXT_INPUT_SYNTHESIS_UNAVAILABLE"
    case commitNotObserved = "TEXT_INPUT_COMMIT_NOT_OBSERVED"
    case clearNotObserved = "TEXT_INPUT_CLEAR_NOT_OBSERVED"
    case synthesisBudgetExceeded = "TEXT_INPUT_SYNTHESIS_BUDGET_EXCEEDED"

    var message: String {
      switch self {
      case .notFocused:
        return "No focused text input was available for typing."
      case .synthesisUnavailable:
        return "Reliable text synthesis is unavailable while the software keyboard is hidden."
      case .commitNotObserved:
        return "The runner could not confirm the typed text reached the field."
      case .clearNotObserved:
        return "The runner could not clear the field before typing, so it typed nothing."
      case .synthesisBudgetExceeded:
        return "The text is longer than one runner command can type at this pace."
      }
    }

    var hint: String {
      switch self {
      case .notFocused:
        return "Focus a visible text input, then retry type or fill. If the input is not exposed by accessibility, use a coordinate focus command before typing."
      case .synthesisUnavailable:
        return "Show the software keyboard, then retry type."
      case .commitNotObserved:
        return "The field may hold none, part, or all of the text. Run snapshot -i and inspect the field: if it already matches, continue; otherwise retry fill with the full text quoted and --delay-ms \(TextEntryTiming.recoveryDelayMilliseconds). Do not use type, which appends to whatever committed."
      case .clearNotObserved:
        return "The field may still hold some or all of its old text. Run snapshot -i and inspect the field, then retry fill. Do not use type, which appends to whatever the field holds."
      case .synthesisBudgetExceeded:
        let recoveryDelay = TextEntryTiming.recoveryDelayMilliseconds
        let recoveryBudget = SynthesizedDeliveryBudget.maxTextLength(
          delaySeconds: Double(recoveryDelay) / 1000
        )




        return "Fill at most \(SynthesizedDeliveryBudget.maxTextLength(delaySeconds: 0)) characters per command without --delay-ms and append the rest with separate type commands. --delay-ms lowers the limit: each character then gets its own synthesize call and each gap pays the delay, so \(recoveryDelay) ms fits \(recoveryBudget). This route is chosen when the accessibility channel is already degraded, so a longer timeout does not help."
      }
    }
  }

  enum TextTypingRepairMode {
    case none
    case append
    case replacement
  }

  enum TextEntryTiming {
    static let focusTimeout: TimeInterval = 0.4
    static let readinessTimeout: TimeInterval = 2.0
    static let hardwareKeyboardFallbackTimeout: TimeInterval = 0.35
    static let pollInterval: TimeInterval = 0.02
    static let warmupValueTimeout: TimeInterval = 0.4
    static let verificationStabilityWindow: TimeInterval = 0.2

    static let replacementSettleCeiling: TimeInterval = 1.0



    static let synthesizedCommitStallTimeout: TimeInterval = 3.0


    static let synthesizedCommitCeiling: TimeInterval = 10.0




    static let synthesizedReplacementFocusAllowance: TimeInterval = 4.0




    static let synthesizedClearReadAllowance: TimeInterval = 0.9




    static let synthesizedDeliveryCeiling: TimeInterval = RunnerTests.mainThreadExecutionTimeout
      - synthesizedReplacementFocusAllowance
      - synthesizedCommitCeiling














    static let synthesizedCharactersPerSecond: UInt = 12

    static let synthesizedCharacterInterval: TimeInterval = 1.0 / Double(synthesizedCharactersPerSecond)



    static let synthesizeCallOverhead: TimeInterval = 0.15

    static let recoveryDelayMilliseconds = 80
    static let synthesizedCommitPollInterval: TimeInterval = 0.2
  }

  struct TextEntryResult {
    let verified: Bool?
    let repaired: Bool
    let expectedText: String?
    let observedText: String?
    var textEntryRoute: String? = nil
    var failure: TextEntryFailure? = nil
    var unconfirmed: TextEntryUnconfirmedEvidence? = nil
  }






  struct TextEntryInputIdentity: Equatable {
    let elementType: XCUIElement.ElementType
    let identifier: String

    var isDistinguishable: Bool { !identifier.isEmpty }
  }




  struct TextInputAtPoint {
    let element: XCUIElement
    let identity: TextEntryInputIdentity
  }



  enum TextEntryContentTranslation {
    case known(CGSize)

    case none

    case unknown
  }

  struct TextEntryTarget {
    let element: XCUIElement?
    let refreshPoint: CGPoint?
    let prefersFocusedElement: Bool
    let contentTranslation: TextEntryContentTranslation
    let fromTapWitness: Bool
    let reusesCurrentFocus: Bool

    let boundIdentity: TextEntryInputIdentity?





    let inputAtRefreshPoint: TextInputAtPoint?


    let postFocusRead: ResolvedTextEntryInput?

    init(
      element: XCUIElement?,
      refreshPoint: CGPoint?,
      prefersFocusedElement: Bool,
      contentTranslation: TextEntryContentTranslation,
      fromTapWitness: Bool = false,
      reusesCurrentFocus: Bool = false,
      boundIdentity: TextEntryInputIdentity? = nil,
      inputAtRefreshPoint: TextInputAtPoint? = nil,
      postFocusRead: ResolvedTextEntryInput? = nil
    ) {
      self.element = element
      self.refreshPoint = refreshPoint
      self.prefersFocusedElement = prefersFocusedElement
      self.contentTranslation = contentTranslation
      self.fromTapWitness = fromTapWitness
      self.reusesCurrentFocus = reusesCurrentFocus
      self.boundIdentity = boundIdentity ?? inputAtRefreshPoint?.identity
      self.inputAtRefreshPoint = inputAtRefreshPoint
      self.postFocusRead = postFocusRead
    }



    func withResolvedInput(_ input: ResolvedTextEntryInput?) -> TextEntryTarget {
      guard let input else {
        return self
      }
      let frame = input.frameOnScreen ?? .zero
      return TextEntryTarget(
        element: input.element,
        refreshPoint: frame.isEmpty ? refreshPoint : CGPoint(x: frame.midX, y: frame.midY),
        prefersFocusedElement: prefersFocusedElement,
        contentTranslation: contentTranslation,
        fromTapWitness: fromTapWitness,
        reusesCurrentFocus: reusesCurrentFocus,
        boundIdentity: boundIdentity ?? input.identity,
        inputAtRefreshPoint: inputAtRefreshPoint
      )
    }
  }







  struct ResolvedTextEntryInput {
    let element: XCUIElement

    let snapshot: XCUIElementSnapshot?
    let contentTranslation: TextEntryContentTranslation

    private init(element: XCUIElement, snapshot: XCUIElementSnapshot?, contentTranslation: TextEntryContentTranslation) {
      self.element = element
      self.snapshot = snapshot
      self.contentTranslation = contentTranslation
    }




    init?(reading element: XCUIElement, contentTranslation: TextEntryContentTranslation) {
      var exists = false
      var snapshot: XCUIElementSnapshot?
      if let exception = RunnerObjCExceptionCatcher.catchException({
        exists = element.exists
        snapshot = exists ? try? element.snapshot() : nil
      }) {
        NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_READ_IGNORED_EXCEPTION=%@", exception)
        return nil
      }
      guard exists else { return nil }
      self.init(element: element, snapshot: snapshot, contentTranslation: contentTranslation)
    }



    init?(readingListed element: XCUIElement, contentTranslation: TextEntryContentTranslation) {
      let snapshot = try? element.snapshot()
      guard snapshot != nil || element.exists else { return nil }
      self.init(element: element, snapshot: snapshot, contentTranslation: contentTranslation)
    }

    var identity: TextEntryInputIdentity? {
      snapshot.map { TextEntryInputIdentity(elementType: $0.elementType, identifier: $0.identifier) }
    }

    var attributes: any XCUIElementAttributes {
      if let snapshot {
        return snapshot
      }
      return element
    }




    var frameOnScreen: CGRect? {
      guard let frame = snapshot?.frame else { return nil }
      switch contentTranslation {
      case .known(let offset): return frame.offsetBy(dx: offset.width, dy: offset.height)
      case .none: return frame
      case .unknown: return nil
      }
    }
  }





  struct TextEntryReader {
    private(set) var target: TextEntryTarget
    private var lastRead: ResolvedTextEntryInput?
    private let resolve: (TextEntryTarget) throws -> ResolvedTextEntryInput?

    init(target: TextEntryTarget, resolve: @escaping (TextEntryTarget) throws -> ResolvedTextEntryInput?) {
      self.target = target.withResolvedInput(target.postFocusRead)
      lastRead = target.postFocusRead
      self.resolve = resolve
    }

    mutating func input() throws -> ResolvedTextEntryInput? {
      if let lastRead {
        return lastRead
      }
      let read = try resolve(target)
      target = target.withResolvedInput(read)
      lastRead = read
      return read
    }


    mutating func dispatch<T>(_ dispatch: () throws -> T) rethrows -> T {
      lastRead = nil
      return try dispatch()
    }
  }


  enum TextEntryInputProbe: Equatable {
    case input(TextEntryInputIdentity)

    case noMatch

    case unavailable
  }

  static let xCTestUITestingErrorDomain = "com.apple.dt.xctest.ui-testing.error"


  static let xCTestNoMatchesErrorCode = 10008


  static func textEntryInputProbe(snapshotError error: Error) -> TextEntryInputProbe {
    let error = error as NSError
    return error.domain == xCTestUITestingErrorDomain && error.code == xCTestNoMatchesErrorCode
      ? .noMatch
      : .unavailable
  }



  static func textEntryRepairCanTarget(boundIdentity: TextEntryInputIdentity?) -> Bool {
    boundIdentity?.isDistinguishable ?? true
  }


  enum TextEntryFocusEvidence {

    case focusEngine

    case focusedInput


    case inputReportsKeyboardFocus(ResolvedTextEntryInput)

    case keyboardAppeared

    case focusQueryMatchesInput


    static let logMarker = "AGENT_DEVICE_RUNNER_TEXT_ENTRY_FOCUS evidence="
    static let inputReportsKeyboardFocusName = "input-reports-keyboard-focus"


    var name: String {
      switch self {
      case .focusEngine: return "focus-engine"
      case .focusedInput: return "focused-input"
      case .inputReportsKeyboardFocus: return Self.inputReportsKeyboardFocusName
      case .keyboardAppeared: return "keyboard-appeared"
      case .focusQueryMatchesInput: return "focus-query-matches-input"
      }
    }
  }

  struct TextEntryStabilization {
    let element: XCUIElement?

    let evidence: TextEntryFocusEvidence?

    let polls: Int

    var focusConfirmed: Bool { evidence != nil }
  }

  struct TextEntryTapWitness {
    let element: XCUIElement
    let bundleId: String?
    let processIdentifier: Int?

    func matches(bundleId: String?, processIdentifier: Int?) -> Bool {
      self.bundleId == bundleId && self.processIdentifier == processIdentifier
    }
  }







  func clearTextInput(app: XCUIApplication, reader: inout TextEntryReader) throws {
    guard let input = try reader.input() else {
      return
    }









    let existing = textValueForClear(input.attributes)
    if existing?.isEmpty == true {
      return
    }
    let defersCaretTap = reader.target.reusesCurrentFocus
    var valueLength = normalizedElementText(input.attributes.value).count
#if os(iOS)




    if textValueRead(for: input.attributes) == .unreadable {



      if input.snapshot.map({ snapshotHasKeyboardFocus($0) }) != true {
        try reader.dispatch { try retapAt(read: input, app: app, element: input.element) }
      }
      if maskedTextShown(by: input) == .empty {
        NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_CLEAR route=masked-skip shown=empty")
        return
      }
      let burst = Self.textClearBurst(valueLength: valueLength)
      reader.dispatch { input.element.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: burst)) }

      if let cleared = try reader.input() {
        let shown = maskedTextShown(by: cleared)
        NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_CLEAR route=masked-deletes shown=%@", String(describing: shown))
        if shown != .text {
          return
        }
      }
    }
#endif

#if !os(tvOS)
    if !defersCaretTap {
      try reader.dispatch { try moveCaretToEnd(app: app, input: input) }
    }
#endif

    guard try reader.input() != nil else {
      let burst = Self.textClearBurst(valueLength: valueLength)
      reader.dispatch { input.element.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: burst)) }
      return
    }
#if os(iOS)




    if existing != nil {
      var passes = 0
      let outcome = try Self.clearUntilEmpty(
        clearOnce: {
          guard let input = try reader.input() else {
            return .stop
          }
          passes += 1
          reader.dispatch {
            input.element.typeKey("a", modifierFlags: .command)
            input.element.typeText(XCUIKeyboardKey.delete.rawValue)
          }
          return .posted
        },
        read: {
          textValueRead(for: try reader.input()?.attributes, treatingPlaceholderAsEmpty: true)
        }
      )
      NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_CLEAR route=element passes=%d outcome=%@", passes, String(describing: outcome))

      guard outcome == .notCleared,
            let remaining = try reader.input().flatMap({ editableTextValue(for: $0.attributes, treatingPlaceholderAsEmpty: true) })
      else {
        return
      }
      valueLength = remaining.count
    }
#endif
    if defersCaretTap {
      guard let fallbackInput = try reader.input() else {
        return
      }
#if !os(tvOS)
      try reader.dispatch { try moveCaretToEnd(app: app, input: fallbackInput) }
#endif
      guard try reader.input() != nil else {
        let burst = Self.textClearBurst(valueLength: valueLength)
        reader.dispatch { fallbackInput.element.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: burst)) }
        return
      }
    }
    for _ in 0...(valueLength / Self.maxTextClearBurst + 1) {
      guard let input = try reader.input() else {
        return
      }
      let burst = Self.textClearBurst(valueLength: valueLength)
      reader.dispatch { input.element.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: burst)) }

      guard burst < valueLength + Self.textClearSlack,
            let remaining = try reader.input().flatMap({ editableTextValue(for: $0.attributes, treatingPlaceholderAsEmpty: true) }),
            Self.textClearContinues(clearedLength: valueLength, remainingLength: remaining.count)
      else {
        return
      }
      valueLength = remaining.count
    }
  }


  private static let textClearSlack = 8


  private static let maxTextClearBurst = 120



  static func textClearBurst(valueLength: Int) -> Int {
    let base = valueLength == 0 ? 24 : valueLength + textClearSlack
    return max(24, min(maxTextClearBurst, base))
  }





  static func textClearContinues(clearedLength: Int, remainingLength: Int) -> Bool {
    remainingLength > 0 && remainingLength < clearedLength
  }


  enum MaskedTextShown: Equatable {

    case empty

    case maskPlaceholder

    case text
  }

  static func maskedTextShown(value: String, showsPlaceholder: Bool) -> MaskedTextShown {
    let shown = value.trimmingCharacters(in: .whitespacesAndNewlines)
    if shown.isEmpty {
      return .empty
    }
    if showsPlaceholder {
      return isMaskedTextValue(shown) ? .maskPlaceholder : .empty
    }
    return .text
  }


  func maskedTextShown(by input: ResolvedTextEntryInput) -> MaskedTextShown {
    let value = normalizedElementText(input.attributes.value)
    return Self.maskedTextShown(value: value, showsPlaceholder: isPlaceholderValue(value, for: input.attributes))
  }

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

  func resolveTextEntryMode(_ command: Command) -> TextTypingRepairMode {
    switch command.textEntryMode {
    case "append":
      return .append
    case "replace":
      return .replacement
    default:
      return .none
    }
  }





  func resolveTextEntryInput(app: XCUIApplication, target: TextEntryTarget) throws -> ResolvedTextEntryInput? {
    guard let boundIdentity = target.boundIdentity else {
      return try resolveUnboundTextEntryInput(app: app, target: target)
    }
    func boundInput(_ candidate: XCUIElement) -> ResolvedTextEntryInput? {
      guard let input = ResolvedTextEntryInput(reading: candidate, contentTranslation: target.contentTranslation),
        input.identity == boundIdentity else { return nil }
      return input
    }
    if target.prefersFocusedElement, let focused = focusedTextInput(app: app), let input = boundInput(focused) {
      return input
    }
    if let element = target.element, let input = boundInput(element) {
      return input
    }
    if let input = target.inputAtRefreshPoint,
       let read = textInputIfStillResolves(input, contentTranslation: target.contentTranslation) {
      return read
    }
    if target.inputAtRefreshPoint == nil,
       let refreshPoint = target.refreshPoint,
       case .matches(let candidates) = try probeTextInputs(app: app, point: refreshPoint, contentTranslation: target.contentTranslation),
       let match = candidates.first(where: { $0.identity == boundIdentity }) {
      return match
    }
    if let focused = focusedTextInput(app: app), let input = boundInput(focused) {
      return input
    }
    if let byIdentifier = try boundTextEntryInputQuery(app: app, identity: boundIdentity),
       let input = boundInput(byIdentifier) {
      return input
    }
    return nil
  }





  func boundTextEntryInputIsGone(app: XCUIApplication, target: TextEntryTarget) throws -> Bool {
    guard let boundIdentity = target.boundIdentity else {
      return false
    }
    let byIdentifier = try boundTextEntryInputQuery(app: app, identity: boundIdentity)
    guard let query = byIdentifier ?? target.element else {
      return false
    }
    switch probeTextEntryInput(query) {
    case .input(let identity) where identity != boundIdentity:
      break
    case .noMatch:
      break
    case .input, .unavailable:
      return false
    }
    guard let refreshPoint = target.refreshPoint else {
      return true
    }
    switch try probeTextInputs(app: app, point: refreshPoint, contentTranslation: target.contentTranslation) {
    case .absent:
      return true
    case .matches(let candidates):
      return candidates.allSatisfy { $0.identity != boundIdentity }
    case .unavailable:
      return false
    }
  }


  private func boundTextEntryInputQuery(app: XCUIApplication, identity: TextEntryInputIdentity) throws -> XCUIElement? {
    guard identity.isDistinguishable else {
      return nil
    }
    let queries = try elementQueries(app: app, matching: identity.elementType).map {
      $0.matching(identifier: identity.identifier)
    }
    return (queries.count == 1 ? queries.first : queries.first { $0.count > 0 })?.element
  }


  func probeTextEntryInput(_ element: XCUIElement) -> TextEntryInputProbe {
    var probe = TextEntryInputProbe.unavailable
    let (_, exception) = catchingObjCException(fallback: ()) {
      do {
        let snapshot = try element.snapshot()
        probe = .input(TextEntryInputIdentity(elementType: snapshot.elementType, identifier: snapshot.identifier))
      } catch {
        probe = Self.textEntryInputProbe(snapshotError: error)
      }
    }
    return exception == nil ? probe : .unavailable
  }


  private func resolveUnboundTextEntryInput(app: XCUIApplication, target: TextEntryTarget) throws -> ResolvedTextEntryInput? {
    let read = { (element: XCUIElement) in
      ResolvedTextEntryInput(reading: element, contentTranslation: target.contentTranslation)
    }
    if target.prefersFocusedElement, let focused = focusedTextInput(app: app).flatMap(read) {
      return focused
    }
    if let element = target.element, let input = read(element) {
      return input
    }
    if let refreshPoint = target.refreshPoint,
       let refreshed = try textInputCandidatesAt(app: app, point: refreshPoint, contentTranslation: target.contentTranslation).first {
      return refreshed
    }
    return focusedTextInput(app: app).flatMap(read)
  }

  private func moveCaretToEnd(app: XCUIApplication, input: ResolvedTextEntryInput) throws {
#if os(tvOS)
    return
#else












    guard let frame = input.frameOnScreen, !frame.isEmpty else {
      return
    }
    _ = try tapAt(
      app: app,
      x: frame.minX + max(2, frame.width - 4),
      y: frame.minY + max(2, frame.height / 2)
    )
#endif
  }

  private func normalizedElementText(_ value: Any?) -> String {
    String(describing: value ?? "")
      .trimmingCharacters(in: .whitespacesAndNewlines)
  }


  enum TextValueRead: Equatable {
    case text(String)

    case unreadable

    case unavailable

    func warmupReadIsPending(expectedText: String) -> Bool {
      switch self {
      case .text(let value): return value != expectedText
      case .unreadable: return false
      case .unavailable: return true
      }
    }
  }





  func textValueRead(
    for element: (any XCUIElementAttributes)?,
    treatingPlaceholderAsEmpty: Bool = false
  ) -> TextValueRead {
    guard let element else {
      return .unavailable
    }
    let elementType = element.elementType
    switch elementType {
    case .textField, .searchField, .textView:
      let value = String(describing: element.value ?? "")
      if treatingPlaceholderAsEmpty && isPlaceholderValue(value, for: element) {
        return .text("")
      }
      return Self.textValueRead(elementType: elementType, value: value)
    default:
      return Self.textValueRead(elementType: elementType, value: "")
    }
  }



  static func textValueRead(elementType: XCUIElement.ElementType, value: String) -> TextValueRead {
    switch elementType {
    case .secureTextField:
      return .unreadable
    case .textField, .searchField, .textView:
      return isMaskedTextValue(value) ? .unreadable : .text(value)
    default:
      return .unavailable
    }
  }



  func editableTextValue(
    for element: (any XCUIElementAttributes)?,
    treatingPlaceholderAsEmpty: Bool = false
  ) -> String? {
    guard case .text(let value) = textValueRead(
      for: element,
      treatingPlaceholderAsEmpty: treatingPlaceholderAsEmpty
    ) else {
      return nil
    }
    return value
  }





  func textValueForClear(_ attributes: (any XCUIElementAttributes)?) -> String? {
    guard let value = editableTextValue(for: attributes, treatingPlaceholderAsEmpty: true) else {
      return nil
    }
    if value.isEmpty, Self.isMaskedTextValue(normalizedElementText(attributes?.value)) {
      return nil
    }
    return value
  }





  static func isMaskedTextValue(_ value: String) -> Bool {
    let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
    guard !trimmed.isEmpty else {
      return false
    }
    return trimmed.allSatisfy { Self.passwordMaskCharacters.contains($0) }
  }



  private static let passwordMaskCharacters: Set<Character> = ["\u{2022}", "\u{25CF}"]

  private func isPlaceholderValue(_ value: String, for element: any XCUIElementAttributes) -> Bool {
    if Self.textMatchesPlaceholder(value, placeholder: element.placeholderValue) {
      return true
    }
    let normalizedValue = value.trimmingCharacters(in: .whitespacesAndNewlines)
    guard !normalizedValue.isEmpty else {
      return false
    }
    if isGenericTextInputLabel(normalizedValue) {
      return true
    }
    let normalizedLabel = element.label.trimmingCharacters(in: .whitespacesAndNewlines)
    return normalizedLabel == normalizedValue && isGenericTextInputLabel(normalizedLabel)
  }

  static func textMatchesPlaceholder(_ text: String, placeholder: String?) -> Bool {
    let normalizedText = text.trimmingCharacters(in: .whitespacesAndNewlines)
    guard !normalizedText.isEmpty else { return false }
    let normalizedPlaceholder = placeholder?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
    return !normalizedPlaceholder.isEmpty && normalizedText == normalizedPlaceholder
  }

  private func isGenericTextInputLabel(_ value: String) -> Bool {
    switch value {
    case "Text input field":
      return true
    default:
      return false
    }
  }
}
