import XCTest
import AgentDeviceSnapshotPresentation

extension RunnerTests {
  func executeSnapshotDispatched(command: Command) throws -> Response {
    try executeDispatchedWithRecovery(command: command) {
      try self.executeSnapshotDispatchedOnce(command: command)
    }
  }

  private func executeSnapshotDispatchedOnce(command: Command) throws -> Response {
    let preparation: SnapshotCommandPreparation = try runMainThreadWork(
      "command_preparation",
      timeout: Self.mainThreadExecutionTimeout,
      timeoutError: Self.mainThreadExecutionTimeoutError
    ) { () -> SnapshotCommandPreparation in
      switch try self.prepareActiveCommandContextSafely(command: command, routeToSpringboard: false) {
      case .response(let response):
        return .response(response)
      case .context(let context):
        if let refusal = self.prepareCommandSurface(command: command, app: context.app) {
          return .response(refusal.response)
        }
        if self.requestLitPanel != nil, let refusal = Self.litPanelBackendPinRefusal(command) {
          return .response(refusal)
        }
        var target = context.observation == nil
          ? self.takeSnapshotCaptureTarget(app: context.app)
          : SnapshotCaptureTarget(
            app: context.app,
            bundleId: command.appBundleId?.trimmedNonEmpty,
            processIdentifier: Self.processIdentifier(of: context.app)
          )
        target.litPanelSurface = self.litPanelState.surface
        target.refusesSystemAlertSubstitution = context.observation != nil
        return .capture(
          target,
          systemSurface: context.systemSurface,
          observation: context.observation
        )
      }
    }
    switch preparation {
    case .response(let response):
      return response
    case .capture(let target, let systemSurface, let observation):
      return try executeSnapshotPrepared(
        command: command,
        target: target,
        systemSurface: systemSurface,
        observation: observation
      )
    }
  }

  @MainActor
  private func prepareActiveCommandContextSafely(
    command: Command,
    routeToSpringboard: Bool
  ) throws -> ActiveCommandPreparation {
    var preparation: ActiveCommandPreparation?
    let exceptionMessage = RunnerObjCExceptionCatcher.catchException({
      preparation = self.prepareActiveCommandContext(
        command: command,
        routeToSpringboard: routeToSpringboard
      )
    })
    if let exceptionMessage {
      throw NSError(
        domain: RunnerErrorDomain.exception,
        code: RunnerErrorCode.objcException,
        userInfo: [NSLocalizedDescriptionKey: exceptionMessage]
      )
    }
    guard let preparation else {
      throw NSError(
        domain: RunnerErrorDomain.general,
        code: RunnerErrorCode.commandReturnedNoResponse,
        userInfo: [NSLocalizedDescriptionKey: "snapshot preflight returned no response"]
      )
    }
    return preparation
  }



  static func presentationOptions(from command: Command) -> PresentationOptions {
    let customActions = command.customActions ?? false
    return PresentationOptions(
      interactiveOnly: command.interactiveOnly ?? false,
      depth: command.depth,
      scope: command.scope,
      raw: command.raw ?? false,



      preferredBackend: command.preferredBackend
        ?? (customActions ? SnapshotBackendKind.privateAX.rawValue : nil),
      customActions: customActions
    )
  }

  private func executeSnapshotPrepared(
    command: Command,
    target: SnapshotCaptureTarget,
    systemSurface: SystemSurfaceHost?,
    observation: SnapshotObservationPayload?
  ) throws -> Response {
    let options = Self.presentationOptions(from: command)
    do {
      var payload: DataPayload
      if options.raw {
        payload = try snapshotRaw(target: target, options: options)
      } else {
        payload = try snapshotFast(target: target, options: options)
      }
      if let systemSurface {
        payload.systemSurface = SystemSurfaceProvenancePayload(
          bundleId: systemSurface.bundleId,
          kind: systemSurface.kind.rawValue
        )
      }
      if let observation {
        guard let capturedProcessIdentifier = target.processIdentifier else {
          return observeOnlyUnavailableResponse()
        }
        let unchanged = try runMainThreadWork(
          "observe_only_state",
          timeout: Self.mainThreadExecutionTimeout,
          timeoutError: Self.mainThreadExecutionTimeoutError
        ) {
          target.app.state == .runningForeground
            && Self.processIdentifier(of: target.app) == capturedProcessIdentifier
        }
        guard unchanged else { return observeOnlyUnavailableResponse() }
        payload.observation = observation
      }
      setNeedsPostSnapshotInteractionDelay()
      return Response(ok: true, data: payload)
    } catch let refusal as RunnerAppScreenCaptureFailure {
      return refusal.response
    } catch is SystemAlertSubstitutionRefused {
      return observeOnlyUnavailableResponse(
        hint: "A system alert is presented over the session app. Resolve it with alert, or read it with a regular snapshot."
      )
    } catch let failure as SnapshotCaptureFailure {
      invalidateCachedTargetAfterSnapshotFailure()
      return Response(
        ok: false,
        error: ErrorPayload(
          code: failure.code,
          message: failure.message,
          hint: failure.hint
        )
      )
    }
  }

  func setNeedsPostSnapshotInteractionDelay() {
    guard !hasAbandonedMainThreadWork() else {
      NSLog("AGENT_DEVICE_RUNNER_POST_SNAPSHOT_DELAY_MARK_SKIPPED_XCTEST_OCCUPIED")
      return
    }
    do {
      try runMainThreadWork(
        "post_snapshot_delay_mark",
        timeout: 1,
        timeoutError: Self.mainThreadExecutionTimeoutError
      ) {
        self.mainOwned.needsPostSnapshotInteractionDelay = true
      }
    } catch {
      NSLog("AGENT_DEVICE_RUNNER_POST_SNAPSHOT_DELAY_MARK_FAILED=%@", String(describing: error))
    }
  }



  static func litPanelBackendPinRefusal(_ command: Command) -> Response? {
    guard let pinned = presentationOptions(from: command).preferredBackend,
      pinned != SnapshotBackendKind.recursiveTree.rawValue
    else {
      return nil
    }
    let cause = command.preferredBackend == nil ? "customActions" : "the \(pinned) backend pin"
    return Response(
      ok: false,
      error: ErrorPayload(
        code: "UNSUPPORTED_OPERATION",
        message: "a multi-panel snapshot runs only the tree backend, so \(cause) cannot be served",
        hint: "Snapshot without \(cause): only the tree backend proves which panel a window is on (ADR 0025)."
      )
    )
  }

  func invalidateCachedTargetAfterSnapshotFailure() {
    applyMainOwnedSnapshotState("target_invalidation") {
      self.invalidateCachedTarget(reason: "ax_snapshot_failure")
    }
  }
}
