import XCTest
#if canImport(AppKit)
import AppKit
#endif

func runnerPngData(for image: RunnerImage) -> Data? {
#if canImport(UIKit)
  return image.pngData()
#elseif canImport(AppKit)
  guard let cgImage = runnerCGImage(from: image) else { return nil }
  let bitmap = NSBitmapImageRep(cgImage: cgImage)
  return bitmap.representation(using: .png, properties: [:])
#endif
}

func runnerCGImage(from image: RunnerImage) -> CGImage? {
#if canImport(UIKit)
  return image.cgImage
#elseif canImport(AppKit)
  return image.cgImage(forProposedRect: nil, context: nil, hints: nil)
#endif
}








enum RunnerInteractionIdleWaits {



  case bothSkipped



  case preEventSkipped
}

extension RunnerTests {











  func captureRunnerFrame(app: XCUIApplication) -> RunnerImage? {
    switch captureRunnerFrameResult(app: app, litPanel: requestLitPanel) {
    case .success(let captured):
      return captured.image
    case .failure:
      return nil
    }
  }





  func captureRunnerFrameResult(
    app: XCUIApplication,
    litPanel: RunnerLitPanel?
  ) -> Result<CapturedAppScreen, RunnerAppScreenCaptureFailure> {
#if os(iOS)
    return captureObservedScreen(app: app, litPanel: litPanel)
#else
    var outcome: Result<CapturedAppScreen, RunnerAppScreenCaptureFailure> = .failure(
      .unrenderableImage
    )
    let capture = {
      let image = XCUIScreen.main.screenshot().image
      if let cgImage = runnerCGImage(from: image) {


        outcome = .success(
          CapturedAppScreen(
            image: image,
            displayID: 0,
            pixelWidth: cgImage.width,
            pixelHeight: cgImage.height,
            pixelsPerPoint: 1
          )
        )
      }
    }
    if Thread.isMainThread {
      capture()
    } else {
      DispatchQueue.main.sync(execute: capture)
    }
    return outcome
#endif
  }

  func screenshotRoot(app: XCUIApplication) -> XCUIElement {
#if os(macOS)
    let windows = app.windows.allElementsBoundByIndex
    if let window = windows.first(where: { $0.exists && !$0.frame.isNull && !$0.frame.isEmpty }) {
      return window
    }
#endif
    return app
  }





  func screenshotResponse(
    pngData: Data,
    inlineScreenshot: Bool,
    metadata: ScreenshotMetadataPayload? = nil
  ) -> Response {
    if inlineScreenshot {
      return Response(
        ok: true,
        data: DataPayload(imageBase64: pngData.base64EncodedString(), screenshotMetadata: metadata)
      )
    }
    let fileName = "screenshot-\(Int(Date().timeIntervalSince1970 * 1000)).png"
#if os(iOS)


    let temporaryDirectory = URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)
      .appendingPathComponent("tmp", isDirectory: true)
#else
    let temporaryDirectory = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
#endif
    let filePath = temporaryDirectory.appendingPathComponent(fileName).path
    do {
      try FileManager.default.createDirectory(at: temporaryDirectory, withIntermediateDirectories: true)
      try pngData.write(to: URL(fileURLWithPath: filePath))
    } catch {
      return Response(
        ok: false,
        error: ErrorPayload(message: "Failed to write screenshot: \(error.localizedDescription)")
      )
    }
#if os(macOS)
    return Response(ok: true, data: DataPayload(message: filePath, screenshotMetadata: metadata))
#else

    return Response(
      ok: true,
      data: DataPayload(message: "tmp/\(fileName)", screenshotMetadata: metadata)
    )
#endif
  }


  func screenshotResponse(
    image: RunnerImage,
    inlineScreenshot: Bool,
    metadata: ScreenshotMetadataPayload? = nil
  ) -> Response {
    guard let pngData = runnerPngData(for: image) else {
      return Response(ok: false, error: ErrorPayload(message: "Failed to encode screenshot as PNG"))
    }
    return screenshotResponse(pngData: pngData, inlineScreenshot: inlineScreenshot, metadata: metadata)
  }

  func stopRecordingIfNeeded() {
    guard let recorder = activeRecording else { return }
    do {
      try recorder.stop()
    } catch {
      NSLog("AGENT_DEVICE_RUNNER_RECORD_STOP_FAILED=%@", String(describing: error))
    }
    activeRecording = nil
  }

  func resolveRecordingOutPath(_ requestedOutPath: String) -> String {
#if os(macOS)
    if requestedOutPath.hasPrefix("/") {
      return requestedOutPath
    }
#endif
    let fileName = URL(fileURLWithPath: requestedOutPath).lastPathComponent
    let fallbackName = "agent-device-recording-\(Int(Date().timeIntervalSince1970 * 1000)).mp4"
    let safeFileName = fileName.isEmpty ? fallbackName : fileName
    return (NSTemporaryDirectory() as NSString).appendingPathComponent(safeFileName)
  }



  @MainActor
  func ensureRunnerHostAppActive(reason: String) {
    NSLog(
      "AGENT_DEVICE_RUNNER_HOST_ACTIVATE state=%d reason=%@",
      app.state.rawValue,
      reason
    )
    if app.state == .unknown || app.state == .notRunning {
      app.launch()
    } else if app.state != .runningForeground {
      app.activate()
    }
    mainOwned.app = app
    mainOwned.bundleId = nil
    mainOwned.processIdentifier = nil
    resetTargetBoundState()
  }




  func resetTargetBoundState() {
    clearRememberedTextEntryTap()
    snapshotXCTestPenaltyWarmupExemption.isPending = false
    lastLoggedFastAppGuardLine = nil
    lastLoggedGesturePolicyLines.removeAll()
  }

  @MainActor
  func invalidateCachedTarget(reason: String) {
    if mainOwned.app != nil || mainOwned.bundleId != nil {
      NSLog("AGENT_DEVICE_RUNNER_TARGET_CACHE_INVALIDATE reason=%@", reason)
    }
    mainOwned.app = nil
    mainOwned.bundleId = nil
    mainOwned.processIdentifier = nil
    resetTargetBoundState()

    firstInteractionWindow = firstInteractionWindow?.attributedToActivation()
  }

  @MainActor
  func resetTargetAfterExternalRelaunch() -> Response {


    let announcedBundleId = mainOwned.bundleId
    invalidateCachedTarget(reason: "external_app_relaunch")



    clearSnapshotXCTestChannelPenalty(reason: "external_app_relaunch")
    clearPrivateAXAcceptedDepth(reason: "external_app_relaunch")
    beginFirstInteractionStabilization(origin: .announcedRelaunch(bundleId: announcedBundleId))
    return Response(ok: true, data: DataPayload(message: "target reset"))
  }

  @MainActor
  func refreshCachedTargetIfProcessChanged(bundleId: String) {
    guard mainOwned.bundleId == bundleId, mainOwned.app != nil else { return }
    let candidate = XCUIApplication(bundleIdentifier: bundleId)
    let observedProcessIdentifier = Self.processIdentifier(of: candidate)
    guard Self.shouldRefreshCachedTarget(
      cachedProcessIdentifier: mainOwned.processIdentifier,
      observedProcessIdentifier: observedProcessIdentifier
    ) else { return }
    NSLog(
      "AGENT_DEVICE_RUNNER_TARGET_CACHE_REFRESH bundle=%@ previousPid=%d currentPid=%d",
      bundleId,
      mainOwned.processIdentifier ?? 0,
      observedProcessIdentifier ?? 0
    )
    mainOwned.app = candidate
    mainOwned.processIdentifier = observedProcessIdentifier
    resetTargetBoundState()
    clearSnapshotXCTestChannelPenalty(reason: "target_process_changed")
    clearPrivateAXAcceptedDepth(reason: "target_process_changed")
    snapshotXCTestPenaltyWarmupExemption.isPending = true
    beginFirstInteractionStabilization()
  }

  static func processIdentifier(of target: XCUIApplication) -> Int? {
    let value = RunnerAXSnapshotBridge.processIdentifier(for: target)
    return value > 0 ? value : nil
  }

  static func shouldRefreshCachedTarget(
    cachedProcessIdentifier: Int?,
    observedProcessIdentifier: Int?
  ) -> Bool {
    guard let cachedProcessIdentifier, let observedProcessIdentifier else { return false }
    return cachedProcessIdentifier != observedProcessIdentifier
  }

  func targetNeedsActivation(_ target: XCUIApplication) -> Bool {
    let state = target.state
#if os(macOS)
    if state == .unknown || state == .notRunning || state == .runningBackground {
      return true
    }
#else
    if state == .unknown || state == .notRunning || state == .runningBackground
      || state == .runningBackgroundSuspended
    {
      return true
    }
#endif
    return false
  }




  func macAppCaptureNeedsRaise(fullscreen: Bool?, targetState: XCUIApplication.State) -> Bool {
    guard targetState != .runningForeground else { return false }
    return fullscreen != true || targetState == .notRunning
  }

  @MainActor
  func canUseFastForegroundAppGuard(
    activeApp: XCUIApplication,
    requestedBundleId: String?
  ) -> Bool {
    guard let requestedBundleId, mainOwned.bundleId == requestedBundleId, mainOwned.app != nil else {
      return false
    }
    guard activeApp.state == .runningForeground else { return false }
    writeFastAppGuardMarker(bundleId: requestedBundleId, state: activeApp.state)
    return true
  }

  @MainActor
  func writeFastAppGuardMarker(bundleId: String, state: XCUIApplication.State) {


    let line = "AGENT_DEVICE_RUNNER_FAST_APP_GUARD bundle=\(bundleId) state=\(state.rawValue)"
    if lastLoggedFastAppGuardLine != line {
      lastLoggedFastAppGuardLine = line
      runnerMarkerWriter(line)
    }
  }







  func soleOtherActiveApplicationPid(excluding sessionPid: Int?) -> Int? {
    let pids = RunnerAXSnapshotBridge.activeApplicationProcessIdentifiers().compactMap {
      ($0 as? NSNumber)?.intValue
    }
    let foreign = Set(pids.filter { $0 > 0 && $0 != sessionPid })
    return foreign.count == 1 ? foreign.first : nil
  }




  func notRunningRefusal(command: Command, bundleId: String) -> Response? {
#if os(iOS)
    guard command.traits.launchPolicy == .existingApp,
      XCUIApplication(bundleIdentifier: bundleId).state == .notRunning
    else { return nil }
    NSLog(
      "AGENT_DEVICE_RUNNER_READ_TARGET_NOT_RUNNING bundle=%@ command=%@",
      bundleId,
      command.command.rawValue
    )
    return Response(
      ok: false,
      error: ErrorPayload(
        code: RunnerWireErrorCode.appNotRunning,
        message: "app '\(bundleId)' is not running",
        hint: "Reads do not launch the app. Relaunch it with open; if a system prompt such as a deep-link confirmation holds its launch, answer it with alert accept."
      )
    )
#else
    return nil
#endif
  }

  @MainActor
  func activateTarget(bundleId: String, reason: String) -> XCUIApplication {
    let target = XCUIApplication(bundleIdentifier: bundleId)
    let initialState = target.state
    NSLog(
      "AGENT_DEVICE_RUNNER_ACTIVATE bundle=%@ state=%d reason=%@",
      bundleId,
      initialState.rawValue,
      reason
    )
    var performedActivation = false

    if initialState == .runningForeground {
      NSLog(
        "AGENT_DEVICE_RUNNER_ACTIVATE_SKIPPED bundle=%@ reason=already_foreground",
        bundleId
      )
    } else {


      let otherActiveApplicationPid = soleOtherActiveApplicationPid(excluding: Self.processIdentifier(of: target))
      target.activate()
      performedActivation = true
      pendingTargetActivation = TargetActivationFactPayload(
        reason: reason,
        priorState: Int(initialState.rawValue),
        otherActiveApplicationPid: otherActiveApplicationPid
      )
      NSLog(
        "AGENT_DEVICE_RUNNER_ACTIVATE_FACT bundle=%@ reason=%@ priorState=%d otherActiveApplicationPid=%@",
        bundleId,
        reason,
        initialState.rawValue,
        otherActiveApplicationPid.map(String.init) ?? "-"
      )
    }
    mainOwned.app = target
    mainOwned.bundleId = bundleId
    mainOwned.processIdentifier = Self.processIdentifier(of: target)
    resetTargetBoundState()
    let announcedRelaunchCoversBinding =
      !performedActivation
      && firstInteractionWindow?.origin.announcesRelaunch(of: bundleId) == true
    if !announcedRelaunchCoversBinding {
      beginFirstInteractionStabilization(origin: .activation)
    }
    return target
  }






  @MainActor
  func withBoundedInteractionIdleTimeoutIfSupported(
    _ target: XCUIApplication,
    waits: RunnerInteractionIdleWaits,
    operation: @MainActor () -> Void
  ) {
    let setter = NSSelectorFromString("setWaitForIdleTimeout:")
    let supportsWaitForIdleTimeout = target.responds(to: setter)
    let previous = supportsWaitForIdleTimeout
      ? (target.value(forKey: "waitForIdleTimeout") as? NSNumber)
      : nil
    if supportsWaitForIdleTimeout {
      target.setValue(interactionIdleTimeoutDefault, forKey: "waitForIdleTimeout")
    }
    defer {
      if let previous {
        target.setValue(previous.doubleValue, forKey: "waitForIdleTimeout")
      }
    }
    performWithQuiescenceSkippedIfSupported(target, waits: waits, operation: operation)
  }


  @MainActor
  private func performWithQuiescenceSkippedIfSupported(
    _ target: XCUIApplication,
    waits: RunnerInteractionIdleWaits,
    operation: @MainActor () -> Void
  ) {
    let selector = NSSelectorFromString("_performWithInteractionOptions:block:")
    guard target.responds(to: selector) else {
      operation()
      return
    }
    typealias PerformWithInteractionOptions = @convention(c) (
      NSObject,
      Selector,
      UInt,
      @convention(block) () -> Void
    ) -> Void
    let implementation = target.method(for: selector)
    let performWithOptions = unsafeBitCast(
      implementation,
      to: PerformWithInteractionOptions.self
    )
    let skipPreEventQuiescence = UInt(1)
    let skipPostEventQuiescence = UInt(2)
    let options: UInt
    switch waits {
    case .bothSkipped:
      options = skipPreEventQuiescence | skipPostEventQuiescence
    case .preEventSkipped:
      options = skipPreEventQuiescence
    }
    withoutActuallyEscaping(operation) { escapableOperation in
      let block: @convention(block) () -> Void = { _ = runOnMainActor(escapableOperation) }
      performWithOptions(
        target,
        selector,
        options,
        block
      )
    }
  }



  func shouldRetryException(_ command: Command, message: String) -> Bool {
    guard command.traits.retryOnSessionLoss else { return false }

    return message.lowercased().contains("kaxerrorservernotfound")
  }

  func shouldRetryResponse(_ response: Response) -> Bool {
    guard response.ok == false else { return false }
    return response.error?.retryableFailure != nil
  }



  @MainActor
  func applyInteractionStabilizationIfNeeded() {
    if mainOwned.needsPostSnapshotInteractionDelay {
      sleepFor(postSnapshotInteractionDelay)
      mainOwned.needsPostSnapshotInteractionDelay = false
    }
    if let window = firstInteractionWindow {
      sleepFor(window.readyUptime - ProcessInfo.processInfo.systemUptime)
      firstInteractionWindow = nil
    }
  }

  struct FirstInteractionWindow {


    enum Origin: Equatable {

      case activation


      case announcedRelaunch(bundleId: String?)

      func announcesRelaunch(of bundleId: String) -> Bool {
        guard case .announcedRelaunch(let announcedBundleId) = self else { return false }
        return announcedBundleId == nil || announcedBundleId == bundleId
      }
    }

    let readyUptime: TimeInterval
    let origin: Origin

    func attributedToActivation() -> FirstInteractionWindow {
      FirstInteractionWindow(readyUptime: readyUptime, origin: .activation)
    }
  }



  func beginFirstInteractionStabilization(origin: FirstInteractionWindow.Origin = .activation) {
    firstInteractionWindow = FirstInteractionWindow(
      readyUptime: ProcessInfo.processInfo.systemUptime + firstInteractionAfterActivateDelay,
      origin: origin
    )
  }

  func sleepFor(_ delay: TimeInterval) {
    guard delay > 0 else { return }

    if Thread.isMainThread {
      let deadline = Date().addingTimeInterval(delay)
      while Date() < deadline {
        let slice = min(max(deadline.timeIntervalSinceNow, 0), 0.02)
        if slice <= 0 {
          break
        }
        let handledSource = RunLoop.current.run(
          mode: .default,
          before: Date().addingTimeInterval(slice)
        )
        if !handledSource {
          usleep(useconds_t(slice * 1_000_000))
        }
      }
      return
    }
    usleep(useconds_t(delay * 1_000_000))
  }
}
