import XCTest
import AgentDeviceSnapshotPresentation











enum SnapshotQualityState: String, Codable, CaseIterable {

  case healthy

  case recovered

  case sparse
}


struct SnapshotQuality: Codable {
  let state: SnapshotQualityState

  let backend: String


  let reason: String?


  let reasonCode: String?

  let effectiveDepth: Int?

  let collapsedLeafIndexes: [Int]?

  let customActions: SnapshotCustomActionCoverage?

  var timing: SnapshotCaptureTiming? = nil
}






enum SnapshotTierOutcome: Equatable {
  case completed
  case deadlineExhausted
}



struct EffectiveSnapshotCapturePlan {
  let steps: [SnapshotCaptureStep]
  let xCTestChannelState: SnapshotXCTestChannelPlanState


  let preferredBackend: SnapshotBackendKind?
}


enum SnapshotCaptureTerminalPolicy {



  case sparseWithFatalOnAXFailure

  case throwOnAXFailure
}

struct SnapshotBackendCapture {
  let payload: DataPayload
  let effectiveDepth: Int?
  var customActions: SnapshotCustomActionCoverage? = nil
  var qualityPayload: DataPayload? = nil
  var timing: SnapshotCaptureTiming? = nil
  var qualityNotes: [SnapshotQualityNote] = []



  var keyboardBand: KeyboardBandFactPayload? = nil



  var presentedSurface: PresentedSurface? = nil
}

extension RunnerTests {




  static func makeSnapshotBackendCapture(
    from result: AgentDeviceSnapshotPresentation.SnapshotPresentationResult,
    acquired acquisition: SnapshotAcquisition
  ) -> SnapshotBackendCapture {
    SnapshotBackendCapture(
      payload: DataPayload(
        nodes: result.nodes,
        truncated: result.truncated,
        snapshotViewport: SnapshotViewportPayload(acquisition.viewport)
      ),
      effectiveDepth: result.effectiveDepth,
      customActions: result.customActions,
      qualityPayload: result.qualityNodes.map {
        DataPayload(nodes: $0, truncated: result.truncated)
      },
      qualityNotes: result.qualityNotes,
      presentedSurface: SnapshotPresentedSurface.classify(acquisition)
    )
  }

  static let sparseRecoveryTruncatedNodeThreshold = 8



  static let snapshotPlanBudget: TimeInterval = 20
  static let collapsedLeafMinimumSegments = 10

  static func payloadNodeCount(_ payload: DataPayload?) -> Int {
    payload?.nodes?.count ?? 0
  }



  static let regularVisiblePlan: [SnapshotBackendKind] = [.recursiveTree, .querySweep, .privateAX]



  static let rawDiagnosticPlan: [SnapshotBackendKind] = regularVisiblePlan.filter(\.supportsRawProjection)

  func shouldSkipSnapshotBackendForAbandonedMainThreadWork(_ kind: SnapshotBackendKind) -> Bool {
    kind.usesXCTestAccessibilityChannel && hasAbandonedMainThreadWork()
  }



  func runSnapshotCapturePlan(
    _ plan: [SnapshotBackendKind],
    target: SnapshotCaptureTarget,
    options: PresentationOptions,
    terminal: SnapshotCaptureTerminalPolicy,
    deadline: Date? = nil
  ) throws -> DataPayload {
    var best: (kind: SnapshotBackendKind, capture: SnapshotBackendCapture)?
    var firstFailure: (reason: String, code: String)?
    var axFailure: SnapshotCaptureFailure?

    let deadline = deadline ?? Date().addingTimeInterval(Self.snapshotPlanBudget)
    let suppressXCTestPenalty = snapshotXCTestPenaltyWarmupExemption.consume()
    var xCTestTierRan = false



    var xCTestChannelPenalized = false
    var breakerPenalized = false
    var xCTestRecoveryProbeDue = false
#if os(iOS)
    breakerPenalized = isSnapshotXCTestChannelPenalized(bundleId: target.bundleId)
    xCTestRecoveryProbeDue = isSnapshotXCTestRecoveryProbeDue(bundleId: target.bundleId)
    xCTestChannelPenalized = Self.snapshotXCTestChannelTreatedAsPenalized(
      penalized: breakerPenalized,
      preferredBackend: options.preferredBackend
    )
#endif


    let surfacePlan = target.litPanelSurface == nil ? plan : [.recursiveTree]
    let effective = Self.effectiveSnapshotCapturePlan(
      surfacePlan,
      xCTestChannelPenalized: xCTestChannelPenalized,
      xCTestRecoveryProbeDue: xCTestRecoveryProbeDue,
      availableBackends: Set(SnapshotBackendKind.allCases.filter(\.isAvailableOnCurrentPlatform)),
      preferredBackend: options.preferredBackend
    )




    let requestPinnedBackend = options.customActions && !breakerPenalized
    firstFailure = Self.xcTestChannelStateFirstFailure(
      effective.xCTestChannelState,
      requestPinnedBackend: requestPinnedBackend
    )
    let preSelectionReason = Self.snapshotPlanPreSelectionReason(
      effective.xCTestChannelState,
      requestPinnedBackend: requestPinnedBackend,
      preferredBackend: effective.preferredBackend?.rawValue
    )
    switch effective.xCTestChannelState {
    case .normal:
      break
    case .deferredToIndependentBackend:
      NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_XCTEST_CHANNEL_DEFERRED bundle=%@", target.bundleId ?? "")
    case .boundedXCTestProbe:
      NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_XCTEST_CHANNEL_PROBE_BOUNDED bundle=%@", target.bundleId ?? "")
    }

    for step in effective.steps {
      let kind = step.backend
      if kind != effective.steps.first?.backend && Date() >= deadline {
        NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_PLAN_BUDGET_EXHAUSTED skipped=%@", kind.rawValue)
        if firstFailure == nil {
          firstFailure = ("the capture plan ran out of its time budget", "budget")
        }
        break
      }


      if shouldSkipSnapshotBackendForAbandonedMainThreadWork(kind) {
        NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_TIER_SKIPPED_XCTEST_OCCUPIED tier=%@", kind.rawValue)
        if firstFailure == nil {
          firstFailure = (
            "the XCTest capture channel is occupied by abandoned main-thread work",
            "budget"
          )
        }
        continue
      }

      if step.claimsPeriodicRecoveryProbe {
        claimSnapshotXCTestRecoveryProbe(bundleId: target.bundleId)
      }
      if kind.usesXCTestAccessibilityChannel { xCTestTierRan = true }
      let attempt = try captureWithBackend(
        step,
        target: target,
        options: options,
        deadline: deadline
      )
      recordXCTestSnapshotBackendAttemptIfNeeded(
        attempt: attempt,
        bundleId: target.bundleId,
        penaltySuppressed: suppressXCTestPenalty
      )
      if case let .failed(failure, phase: _) = attempt.outcome {
        if Self.isAxSnapshotFailure(failure) { axFailure = failure }
        if firstFailure == nil {
          firstFailure = (failure.message, Self.snapshotQualityReasonCode(for: failure))
        }
        NSLog(
          "AGENT_DEVICE_RUNNER_SNAPSHOT_BACKEND_FAILED backend=%@ error=%@",
          kind.rawValue,
          failure.message
        )
        continue
      }
      guard case let .captured(capture) = attempt.outcome else { continue }

      if attempt.tierOutcome == .deadlineExhausted {
        NSLog(
          "AGENT_DEVICE_RUNNER_SNAPSHOT_TIER_DEADLINE_EXHAUSTED backend=%@ nodes=%d",
          kind.rawValue,
          Self.payloadNodeCount(capture.payload)
        )
      }
      if let rejection = Self.snapshotTierRejectionReason(
        outcome: attempt.tierOutcome,
        kind: kind,
        payload: capture.qualityPayload ?? capture.payload
      ) {
        if firstFailure == nil { firstFailure = rejection }
        if Self.payloadNodeCount(capture.payload) > Self.payloadNodeCount(best?.capture.payload) {
          best = (kind, capture)
        }
        continue
      }

      let recovered = kind != effective.steps.first?.backend || effective.xCTestChannelState != .normal
      let verdictReason = Self.planVerdictReason(
        xCTestTierRan: kind.usesXCTestAccessibilityChannel,
        state: effective.xCTestChannelState,
        firstFailure: firstFailure,
        preSelection: preSelectionReason
      )
      if recovered {
        NSLog(
          "AGENT_DEVICE_RUNNER_SNAPSHOT_RECOVERED backend=%@ reason=%@",
          kind.rawValue,
          verdictReason?.reason ?? "sparse tree"
        )
      }
      return stampedSnapshotPayload(
        capture,
        backend: kind,
        state: recovered ? .recovered : .healthy,
        reason: recovered || verdictReason?.code == "requested-backend" ? verdictReason : nil
      )
    }

    if let axFailure {
      switch Self.resolveSnapshotPlanTerminal(
        terminal: terminal,
        interactiveOnly: options.interactiveOnly
      ) {
      case .throwAxFailure:
        throw axFailure
      case .failClosed:





        return snapshotAccessibilityUnavailable(failure: axFailure)
      case .sparseBest:
        break
      }
    }

    let terminalReason = Self.planVerdictReason(
      xCTestTierRan: xCTestTierRan,
      state: effective.xCTestChannelState,
      firstFailure: firstFailure,
      preSelection: preSelectionReason
    )
    let fallbackPayload =
      best.map { stampedSnapshotPayload($0.capture, backend: $0.kind, state: .sparse, reason: terminalReason) }
      ?? stampedSnapshotPayload(
        SnapshotBackendCapture(payload: sparseTruncatedSnapshotPayload(), effectiveDepth: nil),
        backend: effective.steps.last?.backend ?? plan.last ?? .recursiveTree,
        state: .sparse,
        reason: terminalReason
      )
    return fallbackPayload
  }

  private func captureWithBackend(
    _ step: SnapshotCaptureStep,
    target: SnapshotCaptureTarget,
    options: PresentationOptions,
    deadline: Date
  ) throws -> SnapshotBackendAttempt {
    let kind = step.backend
    let app = target.app
    let hint = SnapshotPresentation.captureHint(for: options)
    var timer = SnapshotPhaseTimer()
    let acquisition: SnapshotAcquisition?
    let tierOutcome: SnapshotTierOutcome


    var keyboardBand: RunnerKeyboardBandFact?
    do {
      let measured = try timer.measure(.acquisition) { () -> (SnapshotAcquisition?, SnapshotTierOutcome) in
        switch kind {
        case .recursiveTree:
          guard
            let context = try self.makeSnapshotTraversalContext(
              app: app,
              hint: hint,
              captureDeadline: deadline,
              treeCaptureSliceBudgetOverride: step.treeCaptureSliceBudgetOverride,
              litPanelSurface: target.litPanelSurface
            )
          else {
            return (nil, .completed)
          }
          keyboardBand = context.keyboardBand
          let processingSlice = min(self.treeCaptureSliceBudget, max(0.5, deadline.timeIntervalSinceNow))
          let processingDeadline = Date().addingTimeInterval(processingSlice)
          let tree = try self.runMainThreadWork(
            "tree_processing",
            timeout: processingSlice,
            timeoutError: self.snapshotMainThreadTimeoutError("processing tree snapshot")
          ) {
            hint.isRaw
              ? (try self.rawTreeSnapshotAcquisition(context: context, hint: hint), .completed)
              : try self.recursiveTreeSnapshotAcquisition(
                context: context,
                hint: hint,
                processingDeadline: processingDeadline
              )
          }
          return (tree.acquisition, tree.outcome)
        case .querySweep:
          let sliceDeadline = Self.querySweepSliceDeadline(startedAt: Date(), planDeadline: deadline)
          let sweep = try self.runMainThreadWork(
            "query_sweep",
            timeout: max(0.1, sliceDeadline.timeIntervalSinceNow),
            timeoutError: self.snapshotMainThreadTimeoutError("running query-sweep snapshot")
          ) {
            try self.querySweepSnapshotAcquisition(
              app: app,
              hint: hint,
              sliceDeadline: sliceDeadline
            )
          }
          return (sweep.acquisition, sweep.outcome)
        case .privateAX:





          return (
            self.privateAXSnapshotAcquisition(
              target: target,
              hint: hint,
              deadline: deadline
            ),
            .completed
          )
        }
      }
      acquisition = measured.0
      tierOutcome = measured.1
    } catch let failure as SnapshotCaptureFailure {
      return SnapshotBackendAttempt(
        step: step,
        outcome: .failed(failure, phase: .acquisition),
        timing: timer.timing
      )
    }
    guard let acquisition else {
      return SnapshotBackendAttempt(
        step: step,
        outcome: .noCapture,
        timing: timer.timing,
        tierOutcome: tierOutcome
      )
    }




    let normalizedAcquisition = acquisition.replacingNodes(
      SnapshotGeometrySpace.normalized(
        nodes: acquisition.nodes,
        viewport: acquisition.viewport
      )
    )

    let presented: SnapshotBackendCapture
    do {
      presented = try timer.measure(.presentation) {
        guard let result = try SnapshotPresentation.present(normalizedAcquisition, options: options) else {
          NSLog(
            "AGENT_DEVICE_RUNNER_SNAPSHOT_PROJECTION_MISMATCH requested=%@ acquired=%@",
            hint.projection.rawValue,
            normalizedAcquisition.hint.projection.rawValue
          )
          throw Self.snapshotProjectionMismatchFailure(
            kind,
            requested: hint.projection,
            acquired: normalizedAcquisition.hint.projection
          )
        }
        return Self.makeSnapshotBackendCapture(from: result, acquired: normalizedAcquisition)
      }
    } catch let failure as SnapshotPresentationFailure {
      return SnapshotBackendAttempt(
        step: step,
        outcome: .failed(Self.snapshotCaptureFailure(for: failure), phase: .presentation),
        timing: timer.timing,
        tierOutcome: tierOutcome
      )
    } catch let failure as SnapshotCaptureFailure {
      return SnapshotBackendAttempt(
        step: step,
        outcome: .failed(failure, phase: .presentation),
        timing: timer.timing,
        tierOutcome: tierOutcome
      )
    }

    var capture = presented
    capture.timing = timer.timing
    capture.keyboardBand = keyboardBand?.payload
    return SnapshotBackendAttempt(
      step: step,
      outcome: .captured(capture),
      timing: timer.timing,
      tierOutcome: tierOutcome
    )
  }



  static func snapshotProjectionMismatchFailure(
    _ kind: SnapshotBackendKind,
    requested: CaptureHint.Projection,
    acquired: CaptureHint.Projection
  ) -> SnapshotCaptureFailure {
    SnapshotCaptureFailure(
      code: "IOS_SNAPSHOT_PROJECTION_MISMATCH",
      message:
        "the \(kind.rawValue) backend returned a \(acquired.rawValue) capture for a \(requested.rawValue) snapshot request",
      hint: "This is a runner bug: report it with the failing command and the app under test."
    )
  }







  static func snapshotTierRejectionReason(
    outcome: SnapshotTierOutcome,
    kind: SnapshotBackendKind,
    payload: DataPayload
  ) -> (reason: String, code: String)? {
    if outcome == .deadlineExhausted {
      return (
        "the \(kind.rawValue) backend spent its capture slice with the collection unfinished",
        "budget"
      )
    }
    return sparsePayloadReason(payload)
  }


  static func sparsePayloadReason(_ payload: DataPayload) -> (reason: String, code: String)? {
    guard let nodes = payload.nodes, !nodes.isEmpty else {
      return ("snapshot returned no nodes", "no-nodes")
    }
    if isSparseApplicationWindowTree(nodes) {
      return ("snapshot returned no semantic controls or content", "sparse-tree")
    }
    if payload.truncated == true && nodes.count <= sparseRecoveryTruncatedNodeThreshold {
      return ("snapshot was cut off by its budget with almost nothing collected", "budget")
    }
    return nil
  }




  enum SnapshotPlanTerminalAction: Equatable {
    case throwAxFailure
    case failClosed
    case sparseBest
  }

  static func resolveSnapshotPlanTerminal(
    terminal: SnapshotCaptureTerminalPolicy,
    interactiveOnly: Bool
  ) -> SnapshotPlanTerminalAction {
    switch terminal {
    case .throwOnAXFailure:
      return .throwAxFailure
    case .sparseWithFatalOnAXFailure:
      return interactiveOnly ? .failClosed : .sparseBest
    }
  }

  static func isSparseApplicationWindowTree(_ nodes: [PresentedNode]) -> Bool {
    guard !nodes.isEmpty else { return false }
    let rootRects = nodes.compactMap { node in
      node.type == "Application" || node.type == "Window" ? node.rect : nil
    }
    return nodes.allSatisfy { node in


      let isRootContainer = node.type == "Application" || node.type == "Window"
      guard Self.structuralOnlyNodeTypes.contains(node.type) else { return false }
      guard !isRootContainer else { return true }

      let isFullScreenContainer = node.hittable != true && rootRects.contains { rootRect in
        rootRect.x == node.rect.x && rootRect.y == node.rect.y
          && rootRect.width == node.rect.width && rootRect.height == node.rect.height
      }
      let hasAddressableIdentifier = node.identifier?.isEmpty == false && !isFullScreenContainer
      return !Self.isSemanticSnapshotText(node.label)
        && !Self.isSemanticSnapshotText(node.value)
        && !hasAddressableIdentifier
    }
  }




  static func isSemanticSnapshotText(_ text: String?) -> Bool {
    guard let text else { return false }
    let normalized = text.trimmingCharacters(in: .whitespacesAndNewlines)
    return !normalized.isEmpty && normalized.lowercased() != "[object object]"
  }




  static func collapsedLeafIndexes(_ nodes: [PresentedNode]) -> [Int]? {
    let parents = Set(nodes.compactMap { $0.parentIndex })
    let collapsed = nodes.filter { node in
      guard !parents.contains(node.index) else { return false }
      guard !(node.type.lowercased().contains("text")) else { return false }
      let label = node.label ?? ""
      return label.split(separator: ",").count > collapsedLeafMinimumSegments
    }
    return collapsed.isEmpty ? nil : collapsed.map(\.index)
  }



  func stampedSnapshotPayload(
    _ capture: SnapshotBackendCapture,
    backend: SnapshotBackendKind,
    state: SnapshotQualityState,
    reason: (reason: String, code: String)?
  ) -> DataPayload {
    let health: RunnerAccessibilityHealth = reason?.code == "ax-rejected" ? .unavailable : .healthy
    applyMainOwnedSnapshotState("accessibility_health") {
      self.mainOwned.accessibilityHealth = health
    }
    let payload = capture.payload
    let quality = SnapshotQuality(
      state: state,
      backend: backend.rawValue,
      reason: reason?.reason,
      reasonCode: reason?.code,
      effectiveDepth: capture.effectiveDepth,
      collapsedLeafIndexes: Self.collapsedLeafIndexes(payload.nodes ?? []),
      customActions: capture.customActions,
      timing: capture.timing
    )
    return DataPayload(
      message: payload.message,
      nodes: payload.nodes,




      truncated: payload.truncated == true || state == .sparse || capture.effectiveDepth != nil,
      qualityPayload: capture.qualityPayload.flatMap { quality in
        guard let nodes = quality.nodes else { return nil }
        return SnapshotQualityPayload(nodes: nodes, truncated: quality.truncated == true)
      },
      snapshotQuality: quality,
      snapshotQualityNotes: capture.qualityNotes.isEmpty ? nil : capture.qualityNotes,
      snapshotViewport: payload.snapshotViewport,
      presentedSurface: capture.presentedSurface,
      keyboard: capture.keyboardBand,
      runnerFatal: payload.runnerFatal,
      runnerFatalReason: payload.runnerFatalReason
    )
  }
}
