import Foundation

extension RunnerTests {



  static let snapshotBridgeQueue = DispatchQueue(
    label: "agent-device.runner.snapshot-bridge",
    attributes: .concurrent
  )



  static let snapshotBridgeMaximumResponseBytes = Int(RunnerSnapshotBridgeMaximumFrameBytes())



  static let snapshotBridgeFrameHeaderBytes = MemoryLayout<UInt32>.size



  func executeSnapshotBridge(command: Command) -> Response {
    guard
      let payload = command.snapshotBridge,
      let bundleId = command.appBundleId?.trimmingCharacters(in: .whitespacesAndNewlines),
      !bundleId.isEmpty
    else {
      return Response(
        ok: false,
        error: ErrorPayload(
          code: "INVALID_ARGS",
          message: "snapshotBridge requires appBundleId and a snapshotBridge payload"
        )
      )
    }
    let envelope = RunnerSnapshotBridgeHandle(
      payload.verb,
      bundleId,
      Self.snapshotBridgeReaderRequest(payload)
    )
    let limit = payload.maxResponseBytes ?? Self.snapshotBridgeMaximumResponseBytes
    return Response(
      ok: true,
      data: DataPayload(snapshotBridgeEnvelope: Self.serializedSnapshotBridgeEnvelope(
        envelope,
        requestId: payload.requestId,
        maxBytes: limit
      ))
    )
  }



  static func snapshotBridgeReaderRequest(
    _ payload: SnapshotBridgeCommandPayload,
    simulatorUdid: String? = ProcessInfo.processInfo.environment["SIMULATOR_UDID"]
  ) -> [String: Any] {
    var request: [String: Any] = [
      "verb": "describe",
      "requestId": payload.requestId,
      "snapshotTree": true,
      "automationMode": true,
    ]

    if let generation = payload.generation { request["generation"] = generation }
    if let expectedPid = payload.expectedPid { request["expectedPid"] = expectedPid }
    if let expectedProcessStartTime = payload.expectedProcessStartTime {
      request["expectedProcessStartTime"] = expectedProcessStartTime
    }
    if let maxDepth = payload.maxDepth { request["maxDepth"] = maxDepth }
    if let maxNodes = payload.maxNodes { request["maxNodes"] = maxNodes }
    if let maxDurationMs = payload.maxDurationMs { request["maxDurationMs"] = maxDurationMs }
    if let maxResponseBytes = payload.maxResponseBytes {
      request["maxResponseBytes"] = maxResponseBytes
    }
    if let nativeLevelsHint = payload.nativeLevelsHint {
      request["nativeLevelsHint"] = nativeLevelsHint
    }
    if let executables = payload.surfaceHostExecutables {


      request["surfaceHostExecutables"] = executables
      if let simulatorUdid, !simulatorUdid.isEmpty { request["simulatorUdid"] = simulatorUdid }
    }
    return request
  }




  static func serializedSnapshotBridgeEnvelope(
    _ envelope: [AnyHashable: Any],
    requestId: String,
    maxBytes: Int
  ) -> String {
    let data = JSONSerialization.isValidJSONObject(envelope)
      ? try? JSONSerialization.data(withJSONObject: envelope) : nil
    if let data, data.count + snapshotBridgeFrameHeaderBytes <= maxBytes,
      let text = String(data: data, encoding: .utf8) {
      return text
    }
    var refusal: [String: Any] = data == nil
      ? [
        "requestId": requestId, "ok": false, "error_kind": "malformed_tree",
        "error_code": "response-not-json-safe", "error": "response was not JSON serializable",
      ]
      : [
        "requestId": requestId, "ok": false, "error_kind": "response_limit_exceeded",
        "error_code": "response-too-large",
        "error": "snapshot response exceeds the per-request response bound",
      ]
    for key in ["protocolVersion", "sourceVersion", "pid", "generation", "processStartTime"] {
      if let value = envelope[key] { refusal[key] = value }
    }
    let encoded = (try? JSONSerialization.data(withJSONObject: refusal)) ?? Data("{}".utf8)
    return String(data: encoded, encoding: .utf8) ?? "{}"
  }
}
