import XCTest
import AgentDeviceSnapshotPresentation

extension RunnerTests {
  func invalidScrollDirectionResponse(commandName: String) -> Response {
    Response(
      ok: false,
      error: ErrorPayload(
        code: "INVALID_ARGS",
        message: "\(commandName) requires direction up|down|left|right"
      )
    )
  }

  func scrollDurationIsValid(_ durationMs: Double?) -> Bool {
    guard let durationMs else { return true }
    return durationMs.isFinite && durationMs >= 0 && durationMs <= 10000
  }

  func invalidScrollDurationResponse(commandName: String) -> Response {
    return Response(
      ok: false,
      error: ErrorPayload(
        code: "INVALID_ARGS",
        message: "\(commandName) durationMs must be between 0 and 10000"
      )
    )
  }

  @MainActor
  func executeScrollDragGesture(
    activeApp: XCUIApplication,
    x: Double,
    y: Double,
    x2: Double,
    y2: Double,
    durationMs: Double,
    message: String,
    context: SynthesizedCoordinateContext,
    releaseBehavior: ScrollReleaseBehavior?
  ) throws -> Response {
#if os(iOS)
    return try executeDragGesture(
      activeApp: activeApp,
      x: x,
      y: y,
      x2: x2,
      y2: y2,
      durationMs: durationMs,
      message: message,
      synthesizedContext: context,
      synthesized: (profile: scrollDragProfile(releaseBehavior: releaseBehavior), policyKind: .scroll)
    )
#else
    return try executeDragGesture(
      activeApp: activeApp,
      x: x,
      y: y,
      x2: x2,
      y2: y2,
      durationMs: durationMs,
      message: message
    )
#endif
  }



  @MainActor
  func executeDragGesture(
    activeApp: XCUIApplication,
    x: Double,
    y: Double,
    x2: Double,
    y2: Double,
    durationMs: Double?,
    message: String,
    synthesizedContext: SynthesizedCoordinateContext? = nil,
    synthesized: (profile: SynthesizedDragProfile, policyKind: SynthesizedGesturePolicyKind)? = nil
  ) throws -> Response {
    let durationMs = durationMs ?? runnerDefaultDragDurationMs
    let commandName = dragCommandName(message: message)
    guard x.isFinite, y.isFinite, x2.isFinite, y2.isFinite else {
      return Response(
        ok: false,
        error: ErrorPayload(code: "INVALID_ARGS", message: "\(commandName) requires finite coordinates")
      )
    }
    if let synthesized, let synthesizedResponse = try executeSynthesizedDragGesture(
      activeApp: activeApp,
      x: x,
      y: y,
      x2: x2,
      y2: y2,
      durationMs: durationMs,
      message: message,
      context: synthesizedContext,
      policyKind: synthesized.policyKind,
      profile: synthesized.profile
    ) {
      return synthesizedResponse
    }
    return try executeCoordinateDrag(
      activeApp: activeApp,
      x: x,
      y: y,
      x2: x2,
      y2: y2,
      holdDuration: synthesized == nil
        ? coordinateDragHoldDuration()
        : synthesizedSwipeFallbackHoldDuration(durationMs: durationMs),
      message: message
    )
  }


  @MainActor
  private func executeCoordinateDrag(
    activeApp: XCUIApplication,
    x: Double,
    y: Double,
    x2: Double,
    y2: Double,
    holdDuration: TimeInterval,
    message: String,
    fallback: GestureFallback? = nil
  ) throws -> Response {
    let dragPoints = try keyboardAvoidingDragPoints(app: activeApp, x: x, y: y, x2: x2, y2: y2)
    let dragFrame = try resolvedDragVisualizationFrame(
      app: activeApp,
      x: dragPoints.x,
      y: dragPoints.y,
      x2: dragPoints.x2,
      y2: dragPoints.y2
    )
    let (timing, outcome) = try performGesture(activeApp) {
      try dragAt(
        app: activeApp,
        x: dragPoints.x,
        y: dragPoints.y,
        x2: dragPoints.x2,
        y2: dragPoints.y2,
        holdDuration: holdDuration
      )
    }
    if let response = unsupportedResponse(for: outcome) {
      return response
    }
    return gestureResponse(message: message, timing: timing, frame: .drag(dragFrame), fallback: fallback)
  }

  @MainActor
  private func executeSynthesizedDragGesture(
    activeApp: XCUIApplication,
    x: Double,
    y: Double,
    x2: Double,
    y2: Double,
    durationMs: Double,
    message: String,
    context: SynthesizedCoordinateContext?,
    policyKind: SynthesizedGesturePolicyKind,
    profile: SynthesizedDragProfile
  ) throws -> Response? {
#if os(iOS)
    let context = try context ?? synthesizedCoordinateContext(app: activeApp)
    guard let plan = try axFreeSynthesizedDragPlan(
      app: activeApp,
      x: x,
      y: y,
      x2: x2,
      y2: y2,
      context: context
    )
    else {
      logSynthesizedGesturePolicyDecision(kind: policyKind, context: context, fallbackAttempted: false)
      return Response(
        ok: false,
        error: ErrorPayload(
          code: "INVALID_ARGS",
          message: "\(dragCommandName(message: message)) could not resolve a finite synthesized coordinate frame"
        )
      )
    }
    let durationMs = min(max(durationMs, 16), 10000)
    let dragFrame = DragVisualizationFrame(
      x: plan.points.x,
      y: plan.points.y,
      x2: plan.points.x2,
      y2: plan.points.y2,
      referenceWidth: Double(plan.context.geometry.windowOnScreen.rect.width),
      referenceHeight: Double(plan.context.geometry.windowOnScreen.rect.height)
    )
    switch try performSynthesizedGesture(activeApp, kind: policyKind, context: plan.context, synthesize: {
      try synthesizedDragAt(
        app: activeApp,
        x: plan.points.x,
        y: plan.points.y,
        x2: plan.points.x2,
        y2: plan.points.y2,
        durationMs: durationMs,
        profile: profile,
        context: plan.context
      )
    }) {
    case .performed(let timing):
      return gestureResponse(message: message, timing: timing, frame: .drag(dragFrame))
    case .xctestFallback(let fallbackMessage, let hint):
      return try executeCoordinateDrag(
        activeApp: activeApp,
        x: plan.points.x,
        y: plan.points.y,
        x2: plan.points.x2,
        y2: plan.points.y2,
        holdDuration: synthesizedSwipeFallbackHoldDuration(durationMs: durationMs),
        message: message,
        fallback: GestureFallback(strategy: "xctest-coordinate-drag", message: fallbackMessage, hint: hint)
      )
    case .refused(_, let refusal):
      return refusalResponse(refusal)
    }
#else
    return nil
#endif
  }








  func scrollKeyboardOccludedResponse(
    direction: String,
    keyboardMinY: Double,
    visibleHeight: Double
  ) -> Response {
    return Response(
      ok: false,
      error: ErrorPayload(
        code: ScrollViewportPolicy.occlusionRunnerCode,
        message: String(
          format:
            "scroll %@ refused: the keyboard leaves %.0fpt of visible surface above it, too little to swipe",
          direction,
          visibleHeight
        )
      )
    )
  }

  private func dragCommandName(message: String) -> String {
    return message == "scrolled" ? "scroll" : "drag"
  }
}
