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
}

extension RunnerTests {
  // MARK: - Recording

  func captureRunnerFrame() -> RunnerImage? {
    var image: RunnerImage?
    let capture = {
      let screenshot = XCUIScreen.main.screenshot()
      image = screenshot.image
    }
    if Thread.isMainThread {
      capture()
    } else {
      DispatchQueue.main.sync(execute: capture)
    }
    return image
  }

  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 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)
  }

  // MARK: - Target Activation

  /// The application that is actually on screen, resolved through the
  /// same private accessibility surface WebDriverAgent uses: active
  /// applications carry PIDs, and XCUIApplication can be built from a
  /// PID. Returns nil when the private interface is unavailable so
  /// callers fall back to the placeholder host app.
  func frontmostApplication() -> XCUIApplication? {
    guard let interface = XCUIDevice.shared.value(forKey: "accessibilityInterface") as? NSObject else {
      NSLog("AGENT_DEVICE_RUNNER_FRONTMOST_MISS step=interface")
      return nil
    }
    guard interface.responds(to: NSSelectorFromString("activeApplications")) else {
      NSLog("AGENT_DEVICE_RUNNER_FRONTMOST_MISS step=responds class=%@", NSStringFromClass(type(of: interface)))
      return nil
    }
    guard let raw = interface.perform(NSSelectorFromString("activeApplications"))?.takeUnretainedValue() else {
      NSLog("AGENT_DEVICE_RUNNER_FRONTMOST_MISS step=perform")
      return nil
    }
    guard let elements = raw as? [XCAccessibilityElement], let frontmost = elements.first else {
      NSLog("AGENT_DEVICE_RUNNER_FRONTMOST_MISS step=cast raw=%@", String(describing: raw))
      return nil
    }
    let pid = frontmost.processIdentifier
    guard pid > 0 else {
      NSLog("AGENT_DEVICE_RUNNER_FRONTMOST_MISS step=pid")
      return nil
    }
    guard let bundleId = Self.bundleID(forPID: pid) else {
      NSLog("AGENT_DEVICE_RUNNER_FRONTMOST_MISS step=bundleID pid=%d", pid)
      return nil
    }
    NSLog("AGENT_DEVICE_RUNNER_FRONTMOST_TARGET pid=%d bundle=%@", pid, bundleId)
    return XCUIApplication(bundleIdentifier: bundleId)
  }

  /// Resolves a simulator process to its app bundle identifier: the
  /// process's executable lives inside its .app bundle on the host
  /// filesystem, and Info.plist names the identifier.
  static func bundleID(forPID pid: pid_t) -> String? {
    var buf = [CChar](repeating: 0, count: 4096)
    guard proc_pidpath(pid, &buf, UInt32(buf.count)) > 0 else { return nil }
    let bundleURL = URL(fileURLWithPath: String(cString: buf)).deletingLastPathComponent()
    guard bundleURL.pathExtension == "app",
      let plist = NSDictionary(contentsOf: bundleURL.appendingPathComponent("Info.plist")),
      let bundleId = plist["CFBundleIdentifier"] as? String
    else { return nil }
    return bundleId
  }

  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()
    }
    currentApp = app
    currentBundleId = nil
  }

  /// The app to snapshot when the caller named none: `target` while it is
  /// still in front, otherwise whatever is in front now. The target was
  /// chosen when the command arrived; an app that has since left the screen
  /// (Home, the app switcher, a crash) stops answering accessibility
  /// queries, and XCTest then waits 30s to find it, and retries twice,
  /// holding every later command behind it.
  func foregroundTarget(_ target: XCUIApplication) -> XCUIApplication {
    if target.state == .runningForeground {
      return target
    }
    guard let front = frontmostApplication() else {
      return target
    }
    NSLog("AGENT_DEVICE_RUNNER_RETARGET from_state=%d", target.state.rawValue)
    currentApp = front
    return front
  }

  /// The command's appBundleId, trimmed; nil when absent or blank.
  func normalizedBundleId(_ command: Command) -> String? {
    let trimmed = command.appBundleId?.trimmingCharacters(in: .whitespacesAndNewlines)
    return (trimmed?.isEmpty ?? true) ? nil : trimmed
  }

  /// Where a read-only command (see isPassiveReadCommand) reads from.
  enum PassiveReadTarget {
    case app(XCUIApplication)
    /// No app could be named without launching one; this is the reply.
    case refused(Response)
  }

  /// Resolves the app a read-only command reads without activating,
  /// launching or waiting for anything. A named app is read in whatever
  /// state it is in — the command reports that state rather than changing
  /// it; bringing it forward would make every settle poll yank a
  /// backgrounded app back on screen. With no name, the frontmost app is
  /// read. If that cannot be resolved the command fails: the old fallback,
  /// launching the placeholder host app, would cover the real screen.
  func passiveReadTarget(requestedBundleId: String?) -> PassiveReadTarget {
    if let bundleId = requestedBundleId {
      if currentBundleId == bundleId, let current = currentApp {
        return .app(current)
      }
      return .app(XCUIApplication(bundleIdentifier: bundleId))
    }
    if let front = frontmostApplication() {
      return .app(front)
    }
    return .refused(
      Response(
        ok: false,
        error: ErrorPayload(
          code: "NO_TARGET_APP",
          message: "no appBundleId given and the frontmost app could not be resolved"
        )
      )
    )
  }

  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 canUseFastForegroundAppGuard(
    activeApp: XCUIApplication,
    requestedBundleId: String?,
    command: CommandType
  ) -> Bool {
    guard let requestedBundleId, currentBundleId == requestedBundleId, currentApp != nil else {
      return false
    }
    guard activeApp.state == .runningForeground else { return false }
    NSLog(
      "AGENT_DEVICE_RUNNER_FAST_APP_GUARD command=%@ bundle=%@ state=%d",
      String(describing: command),
      requestedBundleId,
      activeApp.state.rawValue
    )
    return true
  }

  func activateTarget(bundleId: String, reason: String) -> XCUIApplication {
    let target = XCUIApplication(bundleIdentifier: bundleId)
    NSLog(
      "AGENT_DEVICE_RUNNER_ACTIVATE bundle=%@ state=%d reason=%@",
      bundleId,
      target.state.rawValue,
      reason
    )
    let resuming = isBackgrounded(target.state)
    // activate avoids terminating and relaunching the target app
    target.activate()
    if resuming {
      waitForSpringBoardAfterResume()
    }
    currentApp = target
    currentBundleId = bundleId
    needsFirstInteractionDelay = true
    return target
  }

  /// True for an app that is running but not on screen: activating it is a
  /// resume, not a launch.
  func isBackgrounded(_ state: XCUIApplication.State) -> Bool {
#if os(iOS)
    return state == .runningBackground || state == .runningBackgroundSuspended
#else
    return false
#endif
  }

  /// Waits, capped at resumeSpringBoardIdleTimeout, for SpringBoard to go
  /// idle with its animations done. After a backgrounded app is brought back
  /// the app itself can already look idle while SpringBoard is still
  /// finishing the switch, and the next tap was reported as performed but
  /// never reached the app. Waiting on SpringBoard, only on this resume path,
  /// is the fix WebDriverAgent took (appium/appium-ios#82, Apache-2.0).
  func waitForSpringBoardAfterResume() {
    let started = ProcessInfo.processInfo.systemUptime
    let outcome = RunnerXCTestTimeouts.waitForQuiescence(
      of: springboard,
      timeout: resumeSpringBoardIdleTimeout
    )
    NSLog(
      "AGENT_DEVICE_RUNNER_RESUME_WAIT outcome=%d waited_ms=%.0f",
      outcome.rawValue,
      (ProcessInfo.processInfo.systemUptime - started) * 1000
    )
  }

  func withTemporaryScrollIdleTimeoutIfSupported(
    _ target: XCUIApplication,
    operation: () -> 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(scrollInteractionIdleTimeoutDefault, forKey: "waitForIdleTimeout")
    }
    defer {
      if let previous {
        target.setValue(previous.doubleValue, forKey: "waitForIdleTimeout")
      }
    }
    performWithQuiescenceSkippedIfSupported(target, operation: operation)
  }

  // Some apps never report post-gesture quiescence, even after XCTest has synthesized the event.
  private func performWithQuiescenceSkippedIfSupported(
    _ target: XCUIApplication,
    operation: () -> 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)
    withoutActuallyEscaping(operation) { escapableOperation in
      let block: @convention(block) () -> Void = escapableOperation
      performWithOptions(
        target,
        selector,
        skipPreEventQuiescence | skipPostEventQuiescence,
        block
      )
    }
  }

  func shouldRetryCommand(_ command: Command) -> Bool {
    if RunnerEnv.isTruthy("AGENT_DEVICE_RUNNER_DISABLE_READONLY_RETRY") {
      return false
    }
    return isReadOnlyCommand(command)
  }

  func shouldRetryException(_ command: Command, message: String) -> Bool {
    guard shouldRetryCommand(command) else { return false }
    let normalized = message.lowercased()
    if normalized.contains("kaxerrorservernotfound") {
      return true
    }
    if normalized.contains("main thread execution timed out") {
      return true
    }
    if normalized.contains("timed out") && command.command == .snapshot {
      return true
    }
    return false
  }

  // MARK: - Command Classification

  func isReadOnlyCommand(_ command: Command) -> Bool {
    switch command.command {
    case .interactionFrame, .findText, .readText, .snapshot, .screenshot, .idle:
      return true
    case .alert:
      let action = (command.action ?? "get").lowercased()
      return action == "get"
    default:
      return false
    }
  }

  func shouldRetryResponse(_ response: Response) -> Bool {
    guard response.ok == false else { return false }
    guard let message = response.error?.message.lowercased() else { return false }
    return message.contains("is not available")
  }

  /// Commands that only observe the target app. They never activate or
  /// launch it (see passiveReadTarget): a caller polls them many times a
  /// second while a screen settles, and an observation that moves the app
  /// changes the thing it observes.
  func isPassiveReadCommand(_ command: CommandType) -> Bool {
    command == .snapshot || command == .idle
  }

  func isInteractionCommand(_ command: CommandType) -> Bool {
    switch command {
    case
      .tap,
      .longPress,
      .drag,
      .remotePress,
      .type,
      .swipe,
      .back,
      .backInApp,
      .backSystem,
      .rotate,
      .appSwitcher,
      .keyboardDismiss,
      .pinch:
      return true
    default:
      return false
    }
  }

  func isRunnerLifecycleCommand(_ command: CommandType) -> Bool {
    switch command {
    case .shutdown, .recordStop, .screenshot, .uptime, .idleCheck, .awaitIdle, .settle:
      return true
    default:
      return false
    }
  }

  // MARK: - Idle

  /// Runs the idle command against `app` (already resolved without
  /// activation). The wait happens only for a foreground app: XCTest skips
  /// its quiescence check for any other and leaves the flags stale, so there
  /// is nothing honest to report but idle: false.
  func executeIdle(app: XCUIApplication, command: Command) -> Response {
    let capMs = min(max(command.timeoutMs ?? Self.idleDefaultTimeoutMs, 0), Self.idleMaxTimeoutMs)
    let state = app.state
    if capMs == 0 || state != .runningForeground {
      let reason = capMs == 0 ? "not waited: timeoutMs is 0" : "not waited: app is not in the foreground"
      return idleResponse(idle: false, waitedMs: 0, app: app, message: reason)
    }
    let started = ProcessInfo.processInfo.systemUptime
    let outcome = RunnerXCTestTimeouts.waitForQuiescence(of: app, timeout: capMs / 1000)
    let waitedMs = (ProcessInfo.processInfo.systemUptime - started) * 1000
    switch outcome {
    case .idle:
      return idleResponse(idle: true, waitedMs: waitedMs, app: app, message: "quiescent")
    case .busy:
      return idleResponse(idle: false, waitedMs: waitedMs, app: app, message: "not quiescent within timeoutMs")
    default:
      return idleResponse(idle: false, waitedMs: waitedMs, app: app, message: "quiescence API unavailable")
    }
  }

  private func idleResponse(idle: Bool, waitedMs: Double, app: XCUIApplication, message: String) -> Response {
    Response(
      ok: true,
      data: DataPayload(message: message, appState: appStateString(app), idle: idle, waitedMs: waitedMs)
    )
  }

  // MARK: - Interaction Stabilization

  func applyInteractionStabilizationIfNeeded() {
    if needsFirstInteractionDelay {
      sleepFor(firstInteractionAfterActivateDelay)
      needsFirstInteractionDelay = false
    }
  }

  func sleepFor(_ delay: TimeInterval) {
    guard delay > 0 else { return }
    // Keep XCTest/UI sources moving during command-local pauses such as delayed typing.
    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))
  }
}
