import XCTest



extension RunnerTests {
  enum SynthesizedReplacementRouteOutcome {
    case notApplicable
    case completed(TextEntryResult)
    case fallback(TextEntryTarget)
  }

  struct SynthesizedReplacementRequest {
    let app: XCUIApplication
    let target: TextEntryTarget
    let text: String
    let delaySeconds: Double
    let synthesizer: any TextEntrySynthesizing
    let commandId: String?
    let startedAt: Date
  }

  enum SynthesizedTextEntryAction: Equatable {
    case continueTyping
    case fallback
    case raise(String?)
  }

  protocol TextEntrySynthesizing {
    func enterText(
      app: XCUIApplication,
      text: String,
      replacingExistingText: Bool
    ) -> SynthesizedTextEntryAction
  }

  struct PrivateXCTestTextEntrySynthesizer: TextEntrySynthesizing {
    func enterText(
      app: XCUIApplication,
      text: String,
      replacingExistingText: Bool
    ) -> SynthesizedTextEntryAction {
#if os(iOS)
      let postStartedAt = Date()
      let result = replacingExistingText
        ? RunnerSynthesizedTextEntry.replaceText(
          withApplication: app,
          text: text,
          charactersPerSecond: TextEntryTiming.synthesizedCharactersPerSecond
        )
        : RunnerSynthesizedTextEntry.synthesizeText(
          withApplication: app,
          text: text,
          charactersPerSecond: TextEntryTiming.synthesizedCharactersPerSecond
        )
      NSLog(
        "[DEBUG-1874] synthesize posted %d chars status=%d tookMs=%.0f",
        text.count, result.status.rawValue, postStartedAt.timeIntervalSinceNow * -1000
      )
      return Self.action(status: result.status, message: result.message)
#else
      return .fallback
#endif
    }

#if os(iOS)
    static func action(
      status: RunnerSynthesizedTextEntryStatus,
      message: String?
    ) -> SynthesizedTextEntryAction {
      switch status {
      case .succeeded:
        return .continueTyping
      case .unavailable:
        return .fallback
      case .failed:
        return .raise(message)
      @unknown default:
        return .raise(message)
      }
    }
#endif
  }





  struct SynthesizedTextPlan: Equatable {

    struct Step: Equatable {
      let characterCount: Int


      var replacesExistingText = false




      var pauseAfterSeconds: TimeInterval = 0

      var warmsUpField = false






      static let maxClearPassCount = 4

      static let unreadableClearPassCount = 2


      var synthesizeCallCount: Int {
        replacesExistingText ? 2 * Self.maxClearPassCount + 1 : 1
      }


      var keystrokeCount: Int {
        characterCount + clearReadCount
      }


      var clearReadCount: Int {
        replacesExistingText ? Self.maxClearPassCount : 0
      }
    }

    let steps: [Step]



    static func spacedSteps(
      characterCount: Int,
      delaySeconds: Double,
      replacesExistingTextOnFirstPost: Bool = false
    ) -> [Step] {
      (0..<characterCount).map { index in
        Step(
          characterCount: 1,
          replacesExistingText: replacesExistingTextOnFirstPost && index == 0,
          pauseAfterSeconds: index + 1 < characterCount ? delaySeconds : 0
        )
      }
    }



    var seconds: TimeInterval {
      steps.reduce(0) { total, step in
        total
          + Double(step.keystrokeCount) * TextEntryTiming.synthesizedCharacterInterval
          + Double(step.synthesizeCallCount) * TextEntryTiming.synthesizeCallOverhead
          + Double(step.clearReadCount) * TextEntryTiming.synthesizedClearReadAllowance
          + step.pauseAfterSeconds
      }
    }




    var pacesEveryCharacter: Bool {
      steps.count > 1 && !steps.contains(where: \.warmsUpField)
    }
  }



  static func synthesizedDeliveryIsSpaced(characterCount: Int, delaySeconds: Double) -> Bool {
    delaySeconds > 0 && characterCount > 1
  }









  static func synthesizedTextPlan(
    characterCount: Int,
    delaySeconds: Double,
    selectsExistingText: Bool,
    peelsWarmupCharacter: Bool = false
  ) -> SynthesizedTextPlan {
    if synthesizedDeliveryIsSpaced(characterCount: characterCount, delaySeconds: delaySeconds) {
      return SynthesizedTextPlan(
        steps: SynthesizedTextPlan.spacedSteps(
          characterCount: characterCount,
          delaySeconds: delaySeconds,
          replacesExistingTextOnFirstPost: selectsExistingText
        )
      )
    }
    guard peelsWarmupCharacter && characterCount > 1 else {
      return SynthesizedTextPlan(
        steps: [
          SynthesizedTextPlan.Step(
            characterCount: characterCount,
            replacesExistingText: selectsExistingText
          ),
        ]
      )
    }
    return SynthesizedTextPlan(
      steps: [
        SynthesizedTextPlan.Step(
          characterCount: 1,
          pauseAfterSeconds: TextEntryTiming.pollInterval,
          warmsUpField: true
        ),
        SynthesizedTextPlan.Step(characterCount: characterCount - 1),
      ]
    )
  }



  enum SynthesizedDeliveryBudget {
    static func exceeds(_ plan: SynthesizedTextPlan) -> Bool {
      plan.seconds > TextEntryTiming.synthesizedDeliveryCeiling
    }




    static func maxTextLength(delaySeconds: TimeInterval) -> Int {
      var length = 1
      while !exceeds(
        synthesizedTextPlan(
          characterCount: length + 1,
          delaySeconds: delaySeconds,
          selectsExistingText: true
        )
      ) {
        length += 1
      }
      return length
    }
  }



  enum SynthesizedStepDispatch {
    case posted
    case stop
  }


  enum SynthesizedClearOutcome: Equatable {
    case cleared

    case unverified


    case notCleared

    case stopped
  }



  static func clearUntilEmpty(
    clearOnce: () throws -> SynthesizedStepDispatch,
    read: () throws -> TextValueRead
  ) rethrows -> SynthesizedClearOutcome {
    for pass in 1...SynthesizedTextPlan.Step.maxClearPassCount {
      guard try clearOnce() == .posted else { return .stopped }
      switch try read() {
      case .text(let value) where value.isEmpty:
        return .cleared
      case .text:
        continue
      case .unreadable:
        if pass >= SynthesizedTextPlan.Step.unreadableClearPassCount { return .unverified }
      case .unavailable:
        return .notCleared
      }
    }
    return .notCleared
  }

  struct SynthesizedPlanRun {
    let postedCharacterCount: Int

    let stoppedEarly: Bool
  }











  @MainActor
  func runSynthesizedTextPlan(
    _ plan: SynthesizedTextPlan,
    text: String,
    post: (_ characters: String, _ step: SynthesizedTextPlan.Step) throws -> SynthesizedStepDispatch,
    waitAfterWarmupCharacter: (_ characters: String) throws -> Void,
    didPostStep: (_ step: SynthesizedTextPlan.Step) -> Void = { _ in }
  ) rethrows -> SynthesizedPlanRun {
    let characters = Array(text)
    var postedCount = 0
    for step in plan.steps {
      let nextCount = postedCount + step.characterCount
      if try post(String(characters[postedCount..<nextCount]), step) == .stop {

        return SynthesizedPlanRun(postedCharacterCount: postedCount, stoppedEarly: true)
      }
      postedCount = nextCount
      didPostStep(step)
      if step.warmsUpField {
        try waitAfterWarmupCharacter(String(characters[postedCount - step.characterCount..<postedCount]))
      } else if step.pauseAfterSeconds > 0 {
        sleepFor(step.pauseAfterSeconds)
      }
    }
    return SynthesizedPlanRun(postedCharacterCount: postedCount, stoppedEarly: false)
  }

  @MainActor
  func runSynthesizedReplacementRoute(
    _ request: SynthesizedReplacementRequest
  ) throws -> SynthesizedReplacementRouteOutcome {
#if os(iOS)
    NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_ROUTE route=synthesized-first-responder-replacement")
    let plan = Self.synthesizedTextPlan(
      characterCount: request.text.count,
      delaySeconds: request.delaySeconds,
      selectsExistingText: true
    )
    if SynthesizedDeliveryBudget.exceeds(plan) {
      NSLog(
        "AGENT_DEVICE_RUNNER_TEXT_ENTRY_ROUTE route=synthesized-first-responder-replacement "
          + "reason=delivery-budget-refused chars=%d budgetChars=%d",
        request.text.count,
        SynthesizedDeliveryBudget.maxTextLength(delaySeconds: request.delaySeconds)
      )
      return .completed(
        TextEntryResult(
          verified: nil,
          repaired: false,
          expectedText: request.text,
          observedText: nil,
          textEntryRoute: "synthesized-first-responder-replacement",
          failure: .synthesisBudgetExceeded
        )
      )
    }
    var clearOutcome: SynthesizedClearOutcome?


    let synthesisAvailable = try runSynthesizedTextPlan(
      plan,
      text: request.text,
      post: { slice, step in
        func enter(_ text: String, replacingExistingText: Bool) throws -> SynthesizedStepDispatch {
          switch request.synthesizer.enterText(
            app: request.app,
            text: text,
            replacingExistingText: replacingExistingText
          ) {
          case .continueTyping:
            return .posted
          case .fallback:
            return .stop
          case .raise(let message):
            NSException(
              name: NSExceptionName.internalInconsistencyException,
              reason: message ?? "private XCTest text synthesis failed"
            ).raise()
            return .stop
          }
        }
        if step.replacesExistingText {
          var passes = 0
          let outcome = try Self.clearUntilEmpty(
            clearOnce: {
              passes += 1
              return try enter(XCUIKeyboardKey.delete.rawValue, replacingExistingText: true)
            },
            read: { try self.clearedFieldRead(app: request.app, target: request.target) }
          )
          clearOutcome = outcome
          NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_CLEAR passes=%d outcome=%@", passes, String(describing: outcome))
          guard outcome == .cleared || outcome == .unverified else { return .stop }
        }
        return try enter(slice, replacingExistingText: false)
      },

      waitAfterWarmupCharacter: { _ in }
    )
    if clearOutcome == .notCleared {
      logTextEntryPhase(
        commandId: request.commandId,
        phase: "total",
        startedAt: request.startedAt,
        chars: request.text.count,
        mode: .replacement
      )
      return .completed(
        TextEntryResult(
          verified: nil,
          repaired: false,
          expectedText: request.text,
          observedText: nil,
          textEntryRoute: "synthesized-first-responder-replacement",
          failure: .clearNotObserved
        )
      )
    }
    if synthesisAvailable.stoppedEarly {
      NSLog("AGENT_DEVICE_RUNNER_TEXT_ENTRY_ROUTE route=verified-fallback reason=synthesis-unavailable")


      if let input = request.target.inputAtRefreshPoint,
         let read = textInputIfStillResolves(input, contentTranslation: request.target.contentTranslation),
         let snapshot = read.snapshot, snapshotHasKeyboardFocus(snapshot) {
        return .fallback(
          TextEntryTarget(
            element: nil,
            refreshPoint: request.target.refreshPoint,
            prefersFocusedElement: false,
            contentTranslation: request.target.contentTranslation,
            inputAtRefreshPoint: input,
            postFocusRead: read
          )
        )
      }
      guard let point = request.target.refreshPoint else { return .notApplicable }
      return .fallback(
        try focusTextInputForTextEntry(app: request.app, x: point.x, y: point.y)
      )
    }





    let commit = try awaitSynthesizedReplacementCommit(
      app: request.app,
      target: request.target,
      expectedText: request.text
    )
    logTextEntryPhase(
      commandId: request.commandId,
      phase: "total",
      startedAt: request.startedAt,
      chars: request.text.count,
      mode: .replacement
    )
    return .completed(
      TextEntryResult(
        verified: nil,
        repaired: false,
        expectedText: request.text,
        observedText: nil,
        textEntryRoute: "synthesized-first-responder-replacement",
        failure: Self.textEntryFailure(forCommitOutcome: commit)
      )
    )
#else
    return .notApplicable
#endif
  }

  static func shouldUseSynthesizedFirstResponderReplacement(
    hasResolvedElement: Bool,
    hasRefreshPoint: Bool,
    xCTestUnavailable: Bool
  ) -> Bool {
    !hasResolvedElement && hasRefreshPoint && xCTestUnavailable
  }




  static func shouldUseSynthesizedFirstResponderType(
    repairMode: TextTypingRepairMode,
    text: String,
    fromTapWitness: Bool,
    softwareKeyboardVisible: @autoclosure () -> Bool
  ) -> Bool {
    repairMode == .none && text == "\n" && fromTapWitness && !softwareKeyboardVisible()
  }




  static func commonPrefixLength(_ lhs: String, _ rhs: String) -> Int {
    var length = 0
    for (l, r) in zip(lhs, rhs) {
      if l != r { break }
      length += 1
    }
    return length
  }



  enum SynthesizedTextCommitOutcome: Equatable {

    case settled

    case unobservable

    case notObserved
  }



  static func textEntryFailure(
    forCommitOutcome outcome: SynthesizedTextCommitOutcome
  ) -> TextEntryFailure? {
    switch outcome {
    case .settled, .unobservable:
      return nil
    case .notObserved:
      return .commitNotObserved
    }
  }








  static func awaitSynthesizedReplacementCommitOutcome(
    expectedText: String,
    placeholder: String?,
    fieldIsUnreadable: Bool = false,
    stallBudget: TimeInterval = TextEntryTiming.synthesizedCommitStallTimeout,
    ceiling: TimeInterval = TextEntryTiming.synthesizedCommitCeiling,
    now: () -> Date = { Date() },
    observe: () throws -> TextValueRead,
    waitForNextObservation: () -> Void
  ) rethrows -> SynthesizedTextCommitOutcome {




    if fieldIsUnreadable {
      return .unobservable
    }



    if Self.textMatchesPlaceholder(expectedText, placeholder: placeholder) {
      return .notObserved
    }
    var deadline = SynthesizedCommitDeadline(startedAt: now(), stallBudget: stallBudget, ceiling: ceiling)



    while true {
      let observedText: String?
      switch try observe() {
      case .unreadable:
        return .unobservable
      case .text(let value):
        observedText = value
      case .unavailable:
        observedText = nil
      }
      if observedText == expectedText {
        return .settled
      }



      let sampledAt = now()
      deadline.record(
        expectedPrefixLength: Self.commonPrefixLength(observedText ?? "", expectedText),
        at: sampledAt
      )
      if deadline.isExpired(at: sampledAt) { return .notObserved }
      waitForNextObservation()
    }
  }

  static func shouldUseResolvedCoordinateTextEntryRoute(
    repairMode: TextTypingRepairMode,
    hasX: Bool,
    hasY: Bool,
    xCTestUnavailable: Bool
  ) -> Bool {
    repairMode == .replacement && hasX && hasY && xCTestUnavailable
  }
}
