import XCTest







extension RunnerTests {



















  struct SynthesizedCommitDeadline {
    private let startedAt: Date
    private let stallBudget: TimeInterval
    private let ceiling: TimeInterval

    private var bestPrefixLength = 0
    private var lastProgressAt: Date

    init(startedAt: Date, stallBudget: TimeInterval, ceiling: TimeInterval) {
      self.startedAt = startedAt
      self.stallBudget = stallBudget
      self.ceiling = ceiling
      self.lastProgressAt = startedAt
    }





    mutating func record(expectedPrefixLength: Int, at now: Date) {
      guard expectedPrefixLength > bestPrefixLength else { return }
      bestPrefixLength = expectedPrefixLength
      lastProgressAt = now
    }

    func isExpired(at now: Date) -> Bool {
      now.timeIntervalSince(startedAt) >= ceiling
        || now.timeIntervalSince(lastProgressAt) >= stallBudget
    }
  }













  func awaitSynthesizedReplacementCommit(
    app: XCUIApplication,
    target: TextEntryTarget,
    expectedText: String
  ) throws -> SynthesizedTextCommitOutcome {
    guard !expectedText.contains("\n"), !expectedText.contains("\r") else {
      return .unobservable
    }
    let waitStartedAt = Date()
    NSLog("[DEBUG-1874] wait start expectedLen=%ld route=replacement", expectedText.count)
    let ingredients = try synthesizedCommitPollingIngredients(app: app, target: target, expectedText: expectedText)
    let outcome = try Self.awaitSynthesizedReplacementCommitOutcome(
      expectedText: expectedText,
      placeholder: ingredients.placeholder,
      fieldIsUnreadable: ingredients.fieldIsUnreadable,
      now: { Date() },
      observe: ingredients.observe,
      waitForNextObservation: ingredients.waitForNextObservation
    )
    NSLog(
      "[DEBUG-1874] wait outcome=%@ elapsedMs=%.0f route=replacement",
      String(describing: outcome),
      waitStartedAt.timeIntervalSinceNow * -1000
    )
    return outcome
  }




  static func commitCadenceLogLine(
    elapsedMs: Int,
    observedLen: Int,
    expectedPrefixLen: Int
  ) -> String {
    "[DEBUG-1874] poll t=\(elapsedMs)ms observedLen=\(observedLen) expectedPrefixLen=\(expectedPrefixLen)"
  }




  static func logCommitCadence(
    elapsedMs: Int,
    observedLen: Int,
    expectedPrefixLen: Int
  ) {
    NSLog(
      "%@",
      commitCadenceLogLine(
        elapsedMs: elapsedMs,
        observedLen: observedLen,
        expectedPrefixLen: expectedPrefixLen
      )
    )
  }




  private func synthesizedCommitPollingIngredients(
    app: XCUIApplication,
    target: TextEntryTarget,
    expectedText: String
  ) throws -> (
    placeholder: String?,
    fieldIsUnreadable: Bool,
    observe: () throws -> TextValueRead,
    waitForNextObservation: () -> Void
  ) {
    let field = try resolveTextEntryInput(app: app, target: target)?.attributes
    let placeholder = field?.placeholderValue
    let waitStartedAt = Date()
    return (
      placeholder: placeholder,
      fieldIsUnreadable: textValueRead(for: field) == .unreadable,
      observe: {
        let observed = self.textValueRead(
          for: try self.resolveTextEntryInput(app: app, target: target)?.attributes,
          treatingPlaceholderAsEmpty: true
        )
        var observedText: String?
        if case .text(let value) = observed {
          observedText = value
        }



        Self.logCommitCadence(
          elapsedMs: Int(waitStartedAt.timeIntervalSinceNow * -1000),
          observedLen: observedText?.count ?? -1,
          expectedPrefixLen: observedText.map { Self.commonPrefixLength($0, expectedText) } ?? -1
        )
        return observed
      },


      waitForNextObservation: { self.sleepFor(TextEntryTiming.synthesizedCommitPollInterval) }
    )
  }
}
