import XCTest









struct SnapshotCaptureTarget {
  let app: XCUIApplication
  let bundleId: String?
  let processIdentifier: Int?

  var litPanelSurface: LitPanelSurface? = nil


  var refusesSystemAlertSubstitution = false
}


struct SystemAlertSubstitutionRefused: Error {}


enum SnapshotCommandPreparation {
  case response(Response)
  case capture(SnapshotCaptureTarget, systemSurface: SystemSurfaceHost?, observation: SnapshotObservationPayload?)
}








enum SnapshotProbePenaltyTarget: Equatable {

  case prepared(bundleId: String?)

  case mainOwnedTarget
}



final class SnapshotProbePenaltyIdentity {
  private let lock = NSLock()
  private var bundleId: String?
  private let readsMainOwnedTarget: Bool

  init(_ target: SnapshotProbePenaltyTarget) {
    readsMainOwnedTarget = target == .mainOwnedTarget
    if case .prepared(let bundleId) = target {
      self.bundleId = bundleId
    }
  }



  func captureFromMain(bundleId: String?) {
    guard readsMainOwnedTarget else { return }
    lock.lock()
    self.bundleId = bundleId
    lock.unlock()
  }

  var penalizedBundleId: String? {
    lock.lock()
    defer { lock.unlock() }
    return bundleId
  }
}

extension RunnerTests {

  @MainActor
  func takeSnapshotCaptureTarget(app: XCUIApplication) -> SnapshotCaptureTarget {
    SnapshotCaptureTarget(
      app: app,
      bundleId: mainOwned.bundleId,
      processIdentifier: mainOwned.processIdentifier
    )
  }




  func applyMainOwnedSnapshotState(_ operation: String, _ write: @escaping @MainActor () -> Void) {
    if Thread.isMainThread {
      _ = runOnMainActor(write)
      return
    }
    guard !hasAbandonedMainThreadWork() else {
      NSLog("AGENT_DEVICE_RUNNER_SNAPSHOT_STATE_DEFERRED_XCTEST_OCCUPIED operation=%@", operation)
      DispatchQueue.main.async {
        _ = runOnMainActor(write)
      }
      return
    }
    do {
      try runMainThreadWork(
        operation,
        timeout: 1,
        timeoutError: Self.mainThreadExecutionTimeoutError,
        write
      )
    } catch {
      NSLog(
        "AGENT_DEVICE_RUNNER_SNAPSHOT_STATE_FAILED operation=%@ error=%@",
        operation,
        String(describing: error)
      )
    }
  }
}
