






import AgentDeviceSnapshotPresentation
import XCTest
import Network
#if canImport(UIKit)
import UIKit
typealias RunnerImage = UIImage
#elseif canImport(AppKit)
import AppKit
typealias RunnerImage = NSImage
#endif

final class RunnerTests: XCTestCase {
  enum RunnerErrorDomain {
    static let general = "AgentDeviceRunner"
    static let exception = "AgentDeviceRunner.NSException"
  }

  enum RunnerErrorCode {
    static let noResponseFromMainThread = 1
    static let commandReturnedNoResponse = 2
    static let mainThreadExecutionTimedOut = 3
    static let objcException = 1
  }




















  enum RunnerWireErrorCode {
    static let mainThreadTimeout = "MAIN_THREAD_TIMEOUT"
    static let appNotRunning = "APP_NOT_RUNNING"
    static let noTextInputAtPoint = "NO_TEXT_INPUT_AT_POINT"
    static let textInputProbeUnavailable = "TEXT_INPUT_PROBE_UNAVAILABLE"
    static let alertButtonNotFound = "ALERT_BUTTON_NOT_FOUND"
    static let alertUnresolved = "ALERT_UNRESOLVED"

    static let synthesizedGestureNotDispatched = "SYNTHESIZED_GESTURE_NOT_DISPATCHED"

    static let synthesizedGestureOutcomeUnknown = "SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN"
    static let backSwipeNoChange = "BACK_SWIPE_NO_CHANGE"
    static let backSwipeUnverified = "BACK_SWIPE_UNVERIFIED"
    static let backSwipeNotDispatched = "BACK_SWIPE_NOT_DISPATCHED"

    static let keyboardDismissUnavailable = "KEYBOARD_DISMISS_UNAVAILABLE"

    static let keyboardReturnUnavailable = "KEYBOARD_RETURN_UNAVAILABLE"





    static let hardwareControlUnavailable = "HARDWARE_CONTROL_UNAVAILABLE"


    static let inAppBackControlUnavailable = "IN_APP_BACK_CONTROL_UNAVAILABLE"




    static let commandAlreadyFinished = "COMMAND_ALREADY_FINISHED"
  }


  static func thrownErrorPayload(for error: Error) -> ErrorPayload {
    let nsError = error as NSError
    let abandoned = nsError.domain == RunnerErrorDomain.general
      && nsError.code == RunnerErrorCode.mainThreadExecutionTimedOut
    return ErrorPayload(
      code: abandoned ? RunnerWireErrorCode.mainThreadTimeout : "COMMAND_FAILED",
      message: error.localizedDescription,
      hint: abandoned
        ? "The runner abandoned this command's main-thread work past its execution watchdog and it is still draining. Wait and retry, or use a screenshot and interact by coordinates."
        : "Check the runner log for XCTest details, then retry after the app is foregrounded if this was a timeout or activation failure."
    )
  }

  static let springboardBundleId = "com.apple.springboard"


  static let hasSpringBoardSystemModalHost: Bool = {
    #if os(tvOS) || os(macOS) || os(watchOS)
      return false
    #else
      return true
    #endif
  }()
  static let defaultRecordingFps: Int32 = 15
  var listener: NWListener?
  var listenerToken: RunnerListenerToken?
  var acceptsForwardedConnections = false
  var doneExpectation: XCTestExpectation?
  var transportConnections: [ObjectIdentifier: NWConnection] = [:]
  let shutdownResponseWrites = DispatchGroup()
  let transportQueue = DispatchQueue(label: "agent-device.runner.transport")
  let commandExecutionQueue = DispatchQueue(label: "agent-device.runner.commands")
  let app = XCUIApplication()
  lazy var springboard = XCUIApplication(bundleIdentifier: Self.springboardBundleId)
  let mainOwned = RunnerMainOwnedState()
  let litPanelState = RunnerLitPanelState()


  var pendingTargetActivation: TargetActivationFactPayload?




  var textEntryTapWitness: TextEntryTapWitness?
  static let mainThreadExecutionTimeout: TimeInterval = 30
  let appExistenceTimeout: TimeInterval = 30
  let retryCooldown: TimeInterval = 0.2
  let postSnapshotInteractionDelay: TimeInterval = 0.2
  let firstInteractionAfterActivateDelay: TimeInterval = 0.25
  let interactionIdleTimeoutDefault: TimeInterval = 1.0
  let tvRemoteDoublePressDelayDefault: TimeInterval = 0.0

  let xctestIdleKeepaliveInterval: TimeInterval = 60.0
  let minRecordingFps = 1
  let maxRecordingFps = 120



  let recordingFrameCaptureTimeout: TimeInterval = 1




  var lastLoggedFastAppGuardLine: String?
  var lastLoggedGesturePolicyLines: [SynthesizedGesturePolicyKind: String] = [:]
  var runnerMarkerWriter: @MainActor (String) -> Void = { NSLog("%@", $0) }




  var firstInteractionWindow: FirstInteractionWindow?
  var activeRecording: ScreenRecorder?
  let commandJournal = RunnerCommandJournal()
  let inFlightCommandLock = NSLock()





  var inFlightCommandWaiters: [Int: [@Sendable ((response: RunnerHttpResponse, shouldFinish: Bool)) -> Void]] = [:]




  let mainThreadWorkLock = NSLock()
  var abandonedMainThreadWorkCount = 0


  var mainThreadWorkInFlightCount = 0
  var abandonedMainThreadWorkSince: Date?


  let mainThreadWedgeThreshold: TimeInterval = 120




  let snapshotXCTestChannelPenaltyLock = NSLock()
  var snapshotXCTestChannelPenalty = SnapshotXCTestChannelPenalty()
  let snapshotXCTestPenaltyWarmupExemption = SnapshotXCTestPenaltyWarmupExemption()





  let privateAXAcceptedDepthLock = NSLock()
  var privateAXAcceptedDepthBundleId: String?



  var privateAXAcceptedDepthProcessIdentifier: Int?
  var privateAXAcceptedDepth: Int?
  var privateAXAcceptedDepthUntil = Date.distantPast


  let snapshotXCTestSlowCaptureThreshold: TimeInterval = 3



  let treeCaptureSliceBudget: TimeInterval = 8


  let systemModalProbeBudget: TimeInterval = 4

































































































  var textInputProbeIssues: TextInputProbeIssues?
  let suppressedIssueLock = NSLock()
  var suppressedAxSnapshotIssueCount = 0
  let actionableTypes: Set<XCUIElement.ElementType> = Set(
    RunnerTests.elementTypeNamesByRawValue.compactMap { rawValue, name in
      AlertSurface.actionableTypes.contains(name) ? XCUIElement.ElementType(rawValue: rawValue) : nil
    }
  )



#if os(macOS)


  override class func setUp() {
    super.setUp()
    MainActor.assumeIsolated { _ = NSApplication.shared }
  }

#endif
  override func setUp() {
    continueAfterFailure = true
  }

  override func tearDown() {
    transportQueue.sync { closeTransport() }
    super.tearDown()
  }







  static let axServerRejectionFetchWordings = [
    "Failed to get matching snapshot",
    "Failed to resolve query"
  ]



  static let hungQueryIssueWording = "Timed out while evaluating UI query"

  static func isHungQueryIssueDescription(_ description: String) -> Bool {
    description.contains(hungQueryIssueWording)
  }







  static func isSuppressedAxSnapshotIssueDescription(_ description: String) -> Bool {
    guard description.contains("kAXError") else { return false }
    return axServerRejectionFetchWordings.contains { description.contains($0) }
  }










  override func record(_ issue: XCTIssue) {
    if containTextInputProbeIssue(issue) { return }
    let description = issue.compactDescription
    if Self.isSuppressedAxSnapshotIssueDescription(description) {
      suppressedIssueLock.lock()
      suppressedAxSnapshotIssueCount += 1
      let count = suppressedAxSnapshotIssueCount
      suppressedIssueLock.unlock()
      NSLog(
        "AGENT_DEVICE_RUNNER_AX_SNAPSHOT_ISSUE_SUPPRESSED count=%ld description=%@",
        count,
        description
      )
      return
    }
    super.record(issue)
  }

  @MainActor
  func testCommand() throws {
    doneExpectation = expectation(description: "agent-device command handled")
    NSLog("AGENT_DEVICE_RUNNER_HEADLESS_STARTUP=1")
    guard let configuration = RunnerListenerConfiguration.fromEnvironment() else {
      NSLog("AGENT_DEVICE_RUNNER_LISTENER_CONFIGURATION_MISSING")
      XCTFail("runner listener port, token, or bind address is missing or invalid; refusing to listen")
      return
    }
    listenerToken = configuration.token
    acceptsForwardedConnections = configuration.bindAddress != nil
    NSLog("AGENT_DEVICE_RUNNER_AUTH=required")
    NSLog("AGENT_DEVICE_RUNNER_DESIRED_PORT=%d", configuration.port.rawValue)
    listener = try Self.makeRunnerListener(port: configuration.port, bindAddress: configuration.bindAddress)

    DispatchQueue.global(qos: .utility).async { _ = RunnerAlertLabelVocabulary.system }
    DispatchQueue.global(qos: .utility).async { _ = RunnerLaunchConfirmationPrompt.system }
    listener?.stateUpdateHandler = { [weak self] state in
      switch state {
      case .ready:
        NSLog("AGENT_DEVICE_RUNNER_LISTENER_READY")
        if let listenerPort = self?.listener?.port {
          NSLog("AGENT_DEVICE_RUNNER_PORT=%d", listenerPort.rawValue)
        } else {
          NSLog("AGENT_DEVICE_RUNNER_PORT_NOT_SET")
        }
      case .failed(let error):
        NSLog("AGENT_DEVICE_RUNNER_LISTENER_FAILED=%@", String(describing: error))
        self?.doneExpectation?.fulfill()
      default:
        break
      }
    }
    listener?.newConnectionHandler = { [weak self] conn in
      self?.handle(connection: conn)
    }
    listener?.start(queue: transportQueue)
    let idleKeepaliveTimer = DispatchSource.makeTimerSource(queue: transportQueue)
    idleKeepaliveTimer.schedule(
      deadline: .now() + xctestIdleKeepaliveInterval,
      repeating: xctestIdleKeepaliveInterval
    )
    idleKeepaliveTimer.setEventHandler { @Sendable in
      NSLog("AGENT_DEVICE_RUNNER_IDLE_KEEPALIVE")
    }
    idleKeepaliveTimer.resume()
    defer {
      idleKeepaliveTimer.cancel()
    }

    guard let expectation = doneExpectation else {
      XCTFail("runner expectation was not initialized")
      return
    }
    NSLog("AGENT_DEVICE_RUNNER_WAITING")
    let result = XCTWaiter.wait(for: [expectation], timeout: 24 * 60 * 60)
    NSLog("AGENT_DEVICE_RUNNER_WAIT_RESULT=%@", String(describing: result))
    if result != .completed {
      XCTFail("runner wait ended with \(result)")
    }
  }



  static func makeRunnerListener(port: NWEndpoint.Port, bindAddress: IPv4Address? = nil) throws -> NWListener {
    if let bindAddress {
      let parameters = NWParameters.tcp
      parameters.requiredLocalEndpoint = .hostPort(host: .ipv4(bindAddress), port: port)
      return try NWListener(using: parameters)
    }
    #if targetEnvironment(simulator) || os(macOS)
      let parameters = NWParameters.tcp
      parameters.requiredLocalEndpoint = .hostPort(host: .ipv4(.loopback), port: port)
      return try NWListener(using: parameters)
    #else
      return try NWListener(using: .tcp, on: port)
    #endif
  }
}
