import XCTest
import AgentDeviceSnapshotPresentation

extension RunnerTests {
  func currentUptimeMs() -> Double {
    ProcessInfo.processInfo.systemUptime * 1000
  }

  func measureGesture(_ action: () throws -> Void) rethrows -> (gestureStartUptimeMs: Double, gestureEndUptimeMs: Double) {
    let gestureStartUptimeMs = currentUptimeMs()
    try action()
    return (gestureStartUptimeMs, currentUptimeMs())
  }

  func synthesizedSwipeFallbackHoldDuration(durationMs: Double) -> TimeInterval {
    min(max((durationMs / 5.0) / 1000.0, 0.016), 0.120)
  }

  func coordinateDragHoldDuration() -> TimeInterval {
    0.050
  }


  func unsupportedResponse(for outcome: RunnerInteractionOutcome) -> Response? {
    if case .performed = outcome { return nil }
    return refusalResponse(outcome)
  }



  func refusalResponse(_ refusal: RunnerInteractionOutcome) -> Response {
    switch refusal {
    case .performed:
      preconditionFailure("a performed gesture is not a refusal")
    case .unsupported(let message, let hint):
      return unsupportedResponse(message: message, hint: hint)
    case .notDispatched(let message, let hint):
      return Response(
        ok: false,
        error: ErrorPayload(code: RunnerWireErrorCode.synthesizedGestureNotDispatched, message: message, hint: hint)
      )
    }
  }

  func unsupportedResponse(message: String, hint: String?) -> Response {
    Response(
      ok: false,
      error: ErrorPayload(code: "UNSUPPORTED_OPERATION", message: message, hint: hint)
    )
  }


  enum GestureFrame {
    case none
    case touch(TouchVisualizationFrame?)
    case drag(DragVisualizationFrame)
  }

  struct GestureFallback {
    let strategy: String
    let message: String
    let hint: String?

    static func coordinateTap(_ message: String, hint: String?) -> Self {
      Self(strategy: "xctest-coordinate-tap", message: message, hint: hint)
    }
  }









  @MainActor
  func performGesture(
    _ app: XCUIApplication,
    idleTimeout: Bool = true,
    _ action: () throws -> RunnerInteractionOutcome
  ) throws -> (timing: (gestureStartUptimeMs: Double, gestureEndUptimeMs: Double), outcome: RunnerInteractionOutcome) {
    var outcome: Result<RunnerInteractionOutcome, Error> = .success(.performed)
    let timing = measureGesture {
      if idleTimeout {
        withBoundedInteractionIdleTimeoutIfSupported(app, waits: .bothSkipped) {
          outcome = Result { try action() }
        }
      } else {
        outcome = Result { try action() }
      }
    }
    return (timing, try outcome.get())
  }



  func gestureResponse(
    message: String,
    timing: (gestureStartUptimeMs: Double, gestureEndUptimeMs: Double),
    frame: GestureFrame = .none,
    fallback: GestureFallback? = nil,
    maestroNonHittableCoordinateFallbackUsed: Bool? = nil
  ) -> Response {
    let data: DataPayload
    switch frame {
    case .none:
      data = DataPayload(
        message: message,
        gestureStartUptimeMs: timing.gestureStartUptimeMs,
        gestureEndUptimeMs: timing.gestureEndUptimeMs,
        gestureFallback: fallback?.strategy,
        gestureFallbackMessage: fallback?.message,
        gestureFallbackHint: fallback?.hint,
        maestroNonHittableCoordinateFallbackUsed: maestroNonHittableCoordinateFallbackUsed
      )
    case .touch(let f):
      data = DataPayload(
        message: message,
        gestureStartUptimeMs: timing.gestureStartUptimeMs,
        gestureEndUptimeMs: timing.gestureEndUptimeMs,
        x: f?.x,
        y: f?.y,
        referenceWidth: f?.referenceWidth,
        referenceHeight: f?.referenceHeight,
        gestureFallback: fallback?.strategy,
        gestureFallbackMessage: fallback?.message,
        gestureFallbackHint: fallback?.hint,
        maestroNonHittableCoordinateFallbackUsed: maestroNonHittableCoordinateFallbackUsed
      )
    case .drag(let f):
      data = DataPayload(
        message: message,
        gestureStartUptimeMs: timing.gestureStartUptimeMs,
        gestureEndUptimeMs: timing.gestureEndUptimeMs,
        x: f.x,
        y: f.y,
        x2: f.x2,
        y2: f.y2,
        referenceWidth: f.referenceWidth,
        referenceHeight: f.referenceHeight,
        gestureFallback: fallback?.strategy,
        gestureFallbackMessage: fallback?.message,
        gestureFallbackHint: fallback?.hint
      )
    }
    return Response(ok: true, data: data)
  }




  func canonicalPlannedGestureResponse(_ response: Response) -> Response {
    guard response.ok, let data = response.data else { return response }
    return Response(
      ok: true,
      data: DataPayload(
        message: data.message,
        gestureStartUptimeMs: data.gestureStartUptimeMs,
        gestureEndUptimeMs: data.gestureEndUptimeMs,
        gestureFallback: data.gestureFallback,
        gestureFallbackMessage: data.gestureFallbackMessage,
        gestureFallbackHint: data.gestureFallbackHint
      )
    )
  }


  static func reportingSchedule(_ schedule: String?, in response: Response) -> Response {
    guard response.ok, var data = response.data, let schedule else { return response }
    data.executionProfile = schedule
    return Response(ok: true, data: data)
  }

  func plannedGestureResponse(
    plan: RunnerGesturePlan,
    timing: (gestureStartUptimeMs: Double, gestureEndUptimeMs: Double),
    outcome: RunnerInteractionOutcome
  ) -> Response {
    if let response = unsupportedResponse(for: outcome) {
      return response
    }
    return gestureResponse(message: plan.intent, timing: timing)
  }
}
