import XCTest
import AgentDeviceSnapshotPresentation

extension RunnerTests {
  private static let privateAXSnapshotMaxNodes = 5_000





  static let privateAXDeepExtensionCallLimit = 8





  private static let privateAXCustomActionLimit = 12






  static func privateAXDepthLimited(
    effectiveDepth: Int,
    requestedDepth: Int,
    pendingFrontiers: Int?,
    missedFrontiers: Int?
  ) -> Bool {
    guard effectiveDepth < requestedDepth else { return false }
    guard let pendingFrontiers, let missedFrontiers else { return true }
    return pendingFrontiers > 0 || missedFrontiers > 0
  }






  static let privateAXSnapshotDepthLadder = [56, 40, 24, 12]




  static func privateAXAttemptDepths(requestedDepth: Int, rememberedDepth: Int?) -> [Int] {
    var depths = [requestedDepth]
    depths.append(contentsOf: privateAXSnapshotDepthLadder.filter { $0 < requestedDepth })
    guard let remembered = rememberedDepth, remembered < requestedDepth else { return depths }
    return depths.filter { $0 <= remembered }
  }




  static func privateAXCustomActionCoverage(_ raw: Any?) -> SnapshotCustomActionCoverage? {
    guard let coverage = raw as? [String: Any],
      let read = (coverage[RunnerAXSnapshotCustomActionsReadKey] as? NSNumber)?.intValue,
      let candidates = (coverage[RunnerAXSnapshotCustomActionsCandidatesKey] as? NSNumber)?.intValue,
      let truncated = (coverage[RunnerAXSnapshotCustomActionsTruncatedKey] as? NSNumber)?.intValue,
      let blocked = (coverage[RunnerAXSnapshotCustomActionsBlockedKey] as? NSNumber)?.boolValue
    else { return nil }
    return SnapshotCustomActionCoverage(
      read: read, candidates: candidates, truncated: truncated, blocked: blocked)
  }

  struct PrivateAXLadderOutcome {
    let response: [String: Any]
    let effectiveDepth: Int
    let deadlineSpent: Bool
    let lastError: String

    var succeeded: Bool { response["ok"] as? Bool == true }
  }




  static func privateAXLadderCapture(
    attemptDepths: [Int],
    deadline: Date,
    capture: (Int) -> [String: Any]
  ) -> PrivateAXLadderOutcome {
    var response: [String: Any] = [:]
    var effectiveDepth = attemptDepths.first ?? 0
    var lastError = "unknown private AX snapshot failure"
    for depth in attemptDepths {
      if depth != attemptDepths.first, Date() >= deadline {
        NSLog("AGENT_DEVICE_RUNNER_PRIVATE_AX_SNAPSHOT_BUDGET_EXHAUSTED depth=%ld", depth)
        return PrivateAXLadderOutcome(
          response: response, effectiveDepth: effectiveDepth, deadlineSpent: true,
          lastError: lastError)
      }
      response = capture(depth)
      if response["ok"] as? Bool == true {
        effectiveDepth = depth
        break
      }
      lastError = response["error"] as? String ?? lastError
      NSLog(
        "AGENT_DEVICE_RUNNER_PRIVATE_AX_SNAPSHOT_DEPTH_RETRY depth=%ld error=%@",
        depth,
        lastError
      )
    }
    return PrivateAXLadderOutcome(
      response: response, effectiveDepth: effectiveDepth, deadlineSpent: false, lastError: lastError)
  }




  func recordPrivateAXAcceptedDepth(
    bundleId: String?,
    processIdentifier: Int?,
    exactDepthRequested: Bool,
    effectiveDepth: Int,
    attemptDepths: [Int]
  ) {
    guard !exactDepthRequested, effectiveDepth != attemptDepths.first else { return }
    rememberPrivateAXAcceptedDepth(
      bundleId: bundleId,
      processIdentifier: processIdentifier,
      depth: effectiveDepth
    )
  }

  func rememberPrivateAXAcceptedDepth(bundleId: String?, processIdentifier: Int?, depth: Int) {


    guard let processIdentifier else { return }
    privateAXAcceptedDepthLock.lock()
    privateAXAcceptedDepthBundleId = bundleId
    privateAXAcceptedDepthProcessIdentifier = processIdentifier
    privateAXAcceptedDepth = depth
    privateAXAcceptedDepthUntil = Date().addingTimeInterval(SnapshotXCTestChannelPenalty.duration)
    privateAXAcceptedDepthLock.unlock()
    NSLog("AGENT_DEVICE_RUNNER_PRIVATE_AX_DEPTH_REMEMBERED depth=%ld bundle=%@", depth, bundleId ?? "")
  }

  func rememberedPrivateAXAcceptedDepth(bundleId: String?, processIdentifier: Int?) -> Int? {
    privateAXAcceptedDepthLock.lock()
    defer { privateAXAcceptedDepthLock.unlock() }
    guard Date() < privateAXAcceptedDepthUntil else { return nil }
    guard privateAXAcceptedDepthBundleId == bundleId else { return nil }
    guard let processIdentifier, privateAXAcceptedDepthProcessIdentifier == processIdentifier else {
      return nil
    }
    return privateAXAcceptedDepth
  }

  func clearPrivateAXAcceptedDepth(reason: String) {
    privateAXAcceptedDepthLock.lock()
    let hadMemory = privateAXAcceptedDepth != nil && Date() < privateAXAcceptedDepthUntil
    privateAXAcceptedDepthBundleId = nil
    privateAXAcceptedDepthProcessIdentifier = nil
    privateAXAcceptedDepth = nil
    privateAXAcceptedDepthUntil = .distantPast
    privateAXAcceptedDepthLock.unlock()
    if hadMemory {
      NSLog("AGENT_DEVICE_RUNNER_PRIVATE_AX_DEPTH_MEMORY_CLEARED reason=%@", reason)
    }
  }

  func privateAXSnapshotAcquisition(
    target: SnapshotCaptureTarget,
    hint: CaptureHint,
    deadline: Date = .distantFuture
  ) -> SnapshotAcquisition? {
    #if os(iOS) && targetEnvironment(simulator)
      let app = target.app
      let requestedDepth = hint.rawTraversalDepth ?? 64


      let exactDepthRequested = hint.rawTraversalDepth != nil
      let rememberedDepth =
        exactDepthRequested
        ? nil
        : rememberedPrivateAXAcceptedDepth(
          bundleId: target.bundleId,
          processIdentifier: target.processIdentifier
        )
      let attemptDepths = Self.privateAXAttemptDepths(
        requestedDepth: requestedDepth,
        rememberedDepth: rememberedDepth
      )




      let ladder = Self.privateAXLadderCapture(attemptDepths: attemptDepths, deadline: deadline) {
        depth in
        RunnerAXSnapshotBridge.snapshotTree(
          for: app,
          maxDepth: depth,
          maxNodes: Self.privateAXSnapshotMaxNodes,
          deepExtensionCallLimit: exactDepthRequested ? 0 : Self.privateAXDeepExtensionCallLimit,
          customActionLimit: hint.customActions ? Self.privateAXCustomActionLimit : 0,
          deadline: deadline
        )
      }
      let response = ladder.response
      let effectiveDepth = ladder.effectiveDepth
      guard ladder.succeeded else {
        NSLog("AGENT_DEVICE_RUNNER_PRIVATE_AX_SNAPSHOT_FAILED=%@", ladder.lastError)
        return nil
      }
      recordPrivateAXAcceptedDepth(
        bundleId: target.bundleId,
        processIdentifier: target.processIdentifier,
        exactDepthRequested: exactDepthRequested,
        effectiveDepth: effectiveDepth,
        attemptDepths: attemptDepths
      )
      guard let root = response["root"] as? [String: Any] else {
        NSLog("AGENT_DEVICE_RUNNER_PRIVATE_AX_SNAPSHOT_FAILED=missing root")
        return nil
      }

      let rootFrame = privateAXRect(root["frame"])
      let viewport = privateAXSnapshotViewport(
        app: app,
        bundleId: target.bundleId,
        rootFrame: rootFrame
      )
      let nodes = privateAXAcquisition(
        rawRoot: root,
        hint: hint
      )


      if nodes.count <= 1 {
        NSLog("AGENT_DEVICE_RUNNER_PRIVATE_AX_SNAPSHOT_SPARSE=%ld", nodes.count)
        return nil
      }





      let deepExtension = response[RunnerAXSnapshotDeepExtensionKey] as? [String: Any]
      let depthLimited = Self.privateAXDepthLimited(
        effectiveDepth: effectiveDepth,
        requestedDepth: requestedDepth,
        pendingFrontiers: deepExtension?[RunnerAXSnapshotDeepExtensionPendingKey] as? Int,
        missedFrontiers: deepExtension?[RunnerAXSnapshotDeepExtensionMissedKey] as? Int
      )
      NSLog(
        "AGENT_DEVICE_RUNNER_PRIVATE_AX_SNAPSHOT_USED nodes=%ld depth=%ld extended=%ld",
        nodes.count,
        effectiveDepth,
        deepExtension?[RunnerAXSnapshotDeepExtensionNodesAddedKey] as? Int ?? 0
      )
      return SnapshotAcquisition(
        hint: hint,
        nodes: nodes,
        truncated: (response["truncated"] as? Bool) == true,
        effectiveDepth: depthLimited ? effectiveDepth : nil,
        customActions: Self.privateAXCustomActionCoverage(
          response[RunnerAXSnapshotCustomActionsKey]
        ),
        viewport: viewport
      )
    #else
      return nil
    #endif
  }





  func shouldReadPrivateAXViewportViaXCTest(bundleId: String?) -> Bool {
    !hasAbandonedMainThreadWork() && !isSnapshotXCTestChannelPenalized(bundleId: bundleId)
  }




  private func privateAXSnapshotViewport(
    app: XCUIApplication,
    bundleId: String?,
    rootFrame: CGRect
  ) -> SnapshotViewport {
    let fallback = {
      let fullScreenFrame = Self.fullScreenFrame(of: app)
      let viewport = Self.privateAXRootViewport(rootFrame: rootFrame, fullScreenFrame: fullScreenFrame)
      let kind: String
      switch viewport {
      case .reported: kind = "reported"
      case .derived: kind = "derived"
      case .missing: kind = "missing"
      }
      NSLog(
        "AGENT_DEVICE_RUNNER_PRIVATE_AX_ROOT_VIEWPORT kind=%@ root=%@ fullScreen=%@",
        kind,
        String(describing: rootFrame),
        fullScreenFrame.isNull ? "none" : String(describing: fullScreenFrame)
      )
      return viewport
    }
    guard shouldReadPrivateAXViewportViaXCTest(bundleId: bundleId) else {
      return fallback()
    }
    do {
      let reported = try runMainThreadWork(
        "private_ax_viewport",
        timeout: 1,
        timeoutError: snapshotMainThreadTimeoutError("reading private AX viewport")
      ) {
        try self.safeSnapshotViewport(app: app, readingOrientation: true)
      }
      if case .missing = reported {
        return fallback()
      }
      return reported
    } catch {
      NSLog("AGENT_DEVICE_RUNNER_PRIVATE_AX_VIEWPORT_FALLBACK=%@", String(describing: error))
      return fallback()
    }
  }


  static func fullScreenFrame(of app: XCUIApplication) -> CGRect {
    #if os(iOS)
      return RunnerFullScreenApplicationFrame(app)
    #else
      return .null
    #endif
  }





  static func privateAXRootViewport(rootFrame: CGRect, fullScreenFrame: CGRect) -> SnapshotViewport {


    guard Self.isFullScreenAtOrigin(rootFrame, fullScreenFrame: fullScreenFrame) else {
      return .derived(box: rootFrame)
    }
    return .reported(box: rootFrame, interfaceOrientation: RunnerInterfaceOrientation.unknown)
  }




  static func isFullScreenAtOrigin(_ frame: CGRect, fullScreenFrame: CGRect) -> Bool {
    !fullScreenFrame.isNull && frame.origin == .zero && frame == fullScreenFrame
  }

  func privateAXRect(_ value: Any?) -> CGRect {
    guard let frame = value as? [String: Any] else {
      return .zero
    }
    return CGRect(
      x: privateAXDouble(frame["x"]) ?? 0,
      y: privateAXDouble(frame["y"]) ?? 0,
      width: privateAXDouble(frame["width"]) ?? 0,
      height: privateAXDouble(frame["height"]) ?? 0
    )
  }

  private func privateAXDouble(_ value: Any?) -> Double? {
    if let value = value as? Double { return value }
    if let value = value as? NSNumber { return value.doubleValue }
    return nil
  }
}
