import Foundation





enum SnapshotCaptureStep {

  case ordinary(SnapshotBackendKind)

  case boundedRecovery(SnapshotBackendKind, claimsPeriodicProbe: Bool)




  static let boundedTreeSliceBudget: TimeInterval = 1

  var backend: SnapshotBackendKind {
    switch self {
    case let .ordinary(kind): return kind
    case let .boundedRecovery(kind, _): return kind
    }
  }

  var treeCaptureSliceBudgetOverride: TimeInterval? {
    guard backend == .recursiveTree, case .boundedRecovery = self else { return nil }
    return Self.boundedTreeSliceBudget
  }

  var claimsPeriodicRecoveryProbe: Bool {
    if case let .boundedRecovery(_, claims) = self { return claims }
    return false
  }
}

enum SnapshotXCTestChannelPlanState: Equatable {
  case normal
  case deferredToIndependentBackend
  case boundedXCTestProbe
}





struct SnapshotXCTestChannelPenalty: Equatable {
  static let duration: TimeInterval = 120
  static let recoveryProbeInterval: TimeInterval = 30

  private(set) var bundleId: String?
  private(set) var until = Date.distantPast
  private(set) var probeDueAt = Date.distantFuture


  func isActive(for bundleId: String?, at now: Date) -> Bool {
    guard now < until else { return false }
    guard let penalized = self.bundleId else { return true }
    return penalized == bundleId
  }

  func isProbeDue(for bundleId: String?, at now: Date) -> Bool {
    isActive(for: bundleId, at: now) && now >= probeDueAt
  }

  mutating func arm(bundleId: String?, at now: Date) {
    self.bundleId = bundleId
    until = now.addingTimeInterval(Self.duration)
    probeDueAt = now.addingTimeInterval(Self.recoveryProbeInterval)
  }


  mutating func claimProbe(at now: Date) {
    probeDueAt = now.addingTimeInterval(Self.recoveryProbeInterval)
  }

  mutating func clear() {
    self = SnapshotXCTestChannelPenalty()
  }
}

extension RunnerTests {
  func penalizeSnapshotXCTestChannel(bundleId: String?, reason: String) {
    snapshotXCTestChannelPenaltyLock.lock()
    snapshotXCTestChannelPenalty.arm(bundleId: bundleId, at: Date())
    snapshotXCTestChannelPenaltyLock.unlock()
    NSLog(
      "AGENT_DEVICE_RUNNER_SNAPSHOT_XCTEST_CHANNEL_PENALIZED bundle=%@ reason=%@",
      bundleId ?? "",
      reason
    )
  }

  func clearSnapshotXCTestChannelPenalty(reason: String) {
    snapshotXCTestChannelPenaltyLock.lock()
    let hadActivePenalty = Date() < snapshotXCTestChannelPenalty.until
    snapshotXCTestChannelPenalty.clear()
    snapshotXCTestChannelPenaltyLock.unlock()
    if hadActivePenalty {
      NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_XCTEST_CHANNEL_PENALTY_CLEARED reason=%@", reason)
    }
  }

  func isSnapshotXCTestChannelPenalized(bundleId: String?) -> Bool {
    snapshotXCTestChannelPenaltyLock.lock()
    defer { snapshotXCTestChannelPenaltyLock.unlock() }
    return snapshotXCTestChannelPenalty.isActive(for: bundleId, at: Date())
  }

  func isSnapshotXCTestRecoveryProbeDue(bundleId: String?) -> Bool {
    snapshotXCTestChannelPenaltyLock.lock()
    defer { snapshotXCTestChannelPenaltyLock.unlock() }
    return snapshotXCTestChannelPenalty.isProbeDue(for: bundleId, at: Date())
  }

  func claimSnapshotXCTestRecoveryProbe(bundleId: String?) {
    snapshotXCTestChannelPenaltyLock.lock()
    snapshotXCTestChannelPenalty.claimProbe(at: Date())
    snapshotXCTestChannelPenaltyLock.unlock()
    NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_XCTEST_RECOVERY_PROBE bundle=%@", bundleId ?? "")
  }



  static func xcTestChannelStateFirstFailure(
    _ state: SnapshotXCTestChannelPlanState,
    requestPinnedBackend: Bool = false
  ) -> (reason: String, code: String)? {
    switch state {
    case .normal:
      return nil
    case .deferredToIndependentBackend:
      if requestPinnedBackend {
        return nil
      }
      return (
        "XCTest-backed snapshot tiers were deferred after recent slow accessibility work on this screen",
        "deferred"
      )
    case .boundedXCTestProbe:
      return (
        "XCTest-backed snapshot tiers are running with a short recovery probe after recent slow accessibility work on this screen",
        "budget"
      )
    }
  }



  static func snapshotPlanPreSelectionReason(
    _ state: SnapshotXCTestChannelPlanState,
    requestPinnedBackend: Bool = false,
    preferredBackend: String? = nil
  ) -> (reason: String, code: String)? {
    if state == .normal && preferredBackend == SnapshotBackendKind.recursiveTree.rawValue {
      return (
        "the recursive XCTest tree backend was explicitly selected for this capture",
        "requested-backend"
      )
    }
    if state == .deferredToIndependentBackend && requestPinnedBackend {
      return (
        "the private AX backend was selected because this capture asked for accessibility custom actions",
        "requested-backend"
      )
    }
    return nil
  }



  static func planVerdictReason(
    xCTestTierRan: Bool,
    state: SnapshotXCTestChannelPlanState,
    firstFailure: (reason: String, code: String)?,
    preSelection: (reason: String, code: String)?
  ) -> (reason: String, code: String)? {
    guard xCTestTierRan, state == .deferredToIndependentBackend else { return firstFailure ?? preSelection }
    return xcTestChannelStateFirstFailure(.boundedXCTestProbe)
  }


  static func snapshotXCTestChannelTreatedAsPenalized(
    penalized: Bool,
    preferredBackend: String?
  ) -> Bool {
    penalized || preferredBackend == SnapshotBackendKind.privateAX.rawValue
  }






  static func effectiveSnapshotCapturePlan(
    _ plan: [SnapshotBackendKind],
    xCTestChannelPenalized: Bool,
    xCTestRecoveryProbeDue: Bool = false,
    availableBackends: Set<SnapshotBackendKind> = Set(SnapshotBackendKind.allCases),
    preferredBackend: String? = nil
  ) -> EffectiveSnapshotCapturePlan {
    var ordered = plan
    var state: SnapshotXCTestChannelPlanState = .normal
    var preferred: SnapshotBackendKind?
    var probeLeads = false
    if
      plan == Self.regularVisiblePlan,
      let candidate = preferredBackend.flatMap(SnapshotBackendKind.init(rawValue:)),
      candidate.isForceable,
      availableBackends.contains(candidate)
    {
      ordered = [candidate]
      preferred = candidate
      state = candidate == .privateAX ? .deferredToIndependentBackend : .normal
    } else if xCTestChannelPenalized, plan == Self.regularVisiblePlan {
      let availablePlan = plan.filter { availableBackends.contains($0) }
      let recoveryPlan = availablePlan.filter { !$0.usesXCTestAccessibilityChannel }
      if !recoveryPlan.isEmpty {




        let boundedTree = availablePlan.filter { $0 == .recursiveTree }
        probeLeads = xCTestRecoveryProbeDue && !boundedTree.isEmpty
        ordered = probeLeads ? boundedTree + recoveryPlan : recoveryPlan + boundedTree
        state = .deferredToIndependentBackend
      } else {
        ordered = availablePlan.filter(\.usesXCTestAccessibilityChannel)
        state = .boundedXCTestProbe
      }
    }



    let steps = ordered.enumerated().map { offset, kind -> SnapshotCaptureStep in
      guard state != .normal else { return .ordinary(kind) }
      let claims = probeLeads && offset == 0 && kind.usesXCTestAccessibilityChannel
      return .boundedRecovery(kind, claimsPeriodicProbe: claims)
    }
    return EffectiveSnapshotCapturePlan(
      steps: steps,
      xCTestChannelState: state,
      preferredBackend: preferred
    )
  }




  static func snapshotXCTestPenaltyReason(
    for attempt: SnapshotBackendAttempt,
    slowThresholdMs: Double
  ) -> String? {
    guard case .ordinary(let kind) = attempt.step else { return nil }
    guard kind.usesXCTestAccessibilityChannel else { return nil }
    if case let .failed(failure, phase: .acquisition) = attempt.outcome,
      failure.code == Self.xCTestSnapshotTimeoutCode
    {
      return "\(kind.rawValue)_backend_timeout"
    }
    if attempt.tierOutcome == .deadlineExhausted {
      return "\(kind.rawValue)_backend_timeout"
    }
    guard attempt.timing.acquisitionMs > slowThresholdMs else { return nil }
    return "slow_\(kind.rawValue)_capture_\(Int(attempt.timing.acquisitionMs))ms"
  }



  static func snapshotBoundedRecoveryRestoredChannel(_ attempt: SnapshotBackendAttempt) -> Bool {
    guard case .boundedRecovery(.recursiveTree, _) = attempt.step,
      attempt.timing.acquisitionMs <= SnapshotCaptureStep.boundedTreeSliceBudget * 1_000,
      case let .captured(capture) = attempt.outcome
    else { return false }
    return Self.snapshotTierRejectionReason(
      outcome: attempt.tierOutcome,
      kind: .recursiveTree,
      payload: capture.qualityPayload ?? capture.payload
    ) == nil
  }
}
