import XCTest
import AgentDeviceSnapshotPresentation







enum RunnerAccessibilityHealth: String, Equatable {
  case unknown
  case healthy
  case unavailable
}

enum SynthesizedGesturePolicyKind: String, Equatable, Hashable {
  case coordinateTap
  case coordinateLongPress
  case scroll
  case synthesizedDrag









  func allowsXCTestCoordinateFallback(
    accessibilityHealth: RunnerAccessibilityHealth,
    treeUnreadable: Bool = false
  ) -> Bool {
    switch self {
    case .coordinateTap:
      return !treeUnreadable
    case .coordinateLongPress, .synthesizedDrag:
      return accessibilityHealth != .unavailable
    case .scroll:
      return false
    }
  }
}

struct SynthesizedCoordinateContext {
  let geometry: SurfaceGeometry
  let resolvedWindow: XCUIElement?
  let accessibilityHealth: RunnerAccessibilityHealth


  var treeUnreadable: Bool = false





  var allowsKeyboardProbe: Bool {
    accessibilityHealth != .unavailable
  }
}

func shouldProbeCoordinateTapTextInput(
  xCTestChannelPenalized: Bool,
  evidence: CoordinateTapTextInputEvidence?,
  point: CGPoint?,
  targetBundleId: String?
) -> Bool {
  if xCTestChannelPenalized { return false }
  guard let evidence, let point, point.x.isFinite, point.y.isFinite,
    !evidence.targetBundleId.isEmpty, evidence.targetBundleId == targetBundleId,
    evidence.point.x == point.x, evidence.point.y == point.y
  else { return true }
  for input in evidence.textInputRects {
    let rect = CGRect(x: input.x, y: input.y, width: input.width, height: input.height)
    guard SnapshotGeometry.isPositiveFinite(rect) else { return true }
    if isCoordinateTextInputCandidate(enabled: true, frame: rect, point: point) { return true }
  }
  return false
}



func synthesizedPolicyKind(forSequenceStep step: SequenceStep) -> SynthesizedGesturePolicyKind? {
  switch step.kind {
  case "tap":
    return step.synthesized == true ? .coordinateTap : nil
#if os(iOS)
  case "longPress":
    return .coordinateLongPress
#endif
  default:
    return nil
  }
}


enum SynthesizedGestureAttempt {
  case performed(timing: (gestureStartUptimeMs: Double, gestureEndUptimeMs: Double))

  case xctestFallback(message: String, hint: String?)


  case refused(
    timing: (gestureStartUptimeMs: Double, gestureEndUptimeMs: Double),
    refusal: RunnerInteractionOutcome
  )
}

extension RunnerTests {
  @MainActor
  func synthesizedSequenceCoordinateContext(
    steps: [SequenceStep],
    app: XCUIApplication
  ) throws -> SynthesizedCoordinateContext? {
    guard steps.lazy.contains(where: { synthesizedPolicyKind(forSequenceStep: $0) != nil }) else {
      return nil
    }
    return try synthesizedCoordinateContext(app: app)
  }

  @MainActor
  func performSynthesizedTapGesture(
    app: XCUIApplication,
    x: Double,
    y: Double,
    context: SynthesizedCoordinateContext? = nil
  ) throws -> SynthesizedGestureAttempt {
    let context = try context ?? synthesizedCoordinateContext(app: app)
    return try performSynthesizedGesture(app, kind: .coordinateTap, context: context) {
      try synthesizedTapAt(app: app, x: x, y: y, context: context)
    }
  }



  @MainActor
  func performSynthesizedGesture(
    _ app: XCUIApplication,
    kind: SynthesizedGesturePolicyKind,
    context: SynthesizedCoordinateContext?,
    synthesize: () throws -> RunnerInteractionOutcome?
  ) throws -> SynthesizedGestureAttempt {
    var outcome: RunnerInteractionOutcome?
    let timing: (gestureStartUptimeMs: Double, gestureEndUptimeMs: Double)
    do {
      timing = try measureGesture { outcome = try synthesize() }
    } catch let unknown as RunnerGestureOutcomeUnknown {

      logSynthesizedGesturePolicyDecision(kind: kind, context: context, fallbackAttempted: false)
      throw unknown
    }
    guard let outcome else {
      logSynthesizedGesturePolicyDecision(kind: kind, context: context, fallbackAttempted: false)
      return .refused(
        timing: timing,
        refusal: .unsupported(message: "synthesized gesture deadline expired before dispatch", hint: nil)
      )
    }
    guard case let (message, hint)? = outcome.refusalText else {
      logSynthesizedGesturePolicyDecision(kind: kind, context: context, fallbackAttempted: false)
      return .performed(timing: timing)
    }
    let fallbackAllowed = kind.allowsXCTestCoordinateFallback(
      accessibilityHealth: context?.accessibilityHealth ?? mainOwned.accessibilityHealth,
      treeUnreadable: context?.treeUnreadable ?? false
    )
    logSynthesizedGesturePolicyDecision(
      kind: kind,
      context: context,
      fallbackAttempted: fallbackAllowed
    )
    return fallbackAllowed
      ? .xctestFallback(message: message, hint: hint)
      : .refused(timing: timing, refusal: outcome)
  }

  @MainActor
  func logSynthesizedGesturePolicyDecision(
    kind: SynthesizedGesturePolicyKind,
    context: SynthesizedCoordinateContext?,
    fallbackAttempted: Bool
  ) {
#if os(iOS)
    let line = Self.synthesizedGesturePolicyLine(
      kind: kind,
      context: context,
      fallbackAttempted: fallbackAttempted
    )


    if lastLoggedGesturePolicyLines[kind] != line {
      lastLoggedGesturePolicyLines[kind] = line
      runnerMarkerWriter(line)
    }
#endif
  }

  static func synthesizedGesturePolicyLine(
    kind: SynthesizedGesturePolicyKind,
    context: SynthesizedCoordinateContext?,
    fallbackAttempted: Bool
  ) -> String {
    guard let context else {
      return "AGENT_DEVICE_RUNNER_SYNTHESIZED_GESTURE_POLICY kind=\(kind.rawValue)"
        + " context=unavailable fallbackAttempted=\(fallbackAttempted)"
    }
    return "AGENT_DEVICE_RUNNER_SYNTHESIZED_GESTURE_POLICY kind=\(kind.rawValue)"
      + " axHealth=\(context.accessibilityHealth.rawValue)"
      + " fallbackAllowed=\(kind.allowsXCTestCoordinateFallback(accessibilityHealth: context.accessibilityHealth, treeUnreadable: context.treeUnreadable))"
      + " fallbackAttempted=\(fallbackAttempted)"
  }
}

extension SynthesizedCoordinateContext {

  init?(
    validating geometry: SurfaceGeometry,
    resolvedWindow: XCUIElement?,
    accessibilityHealth: RunnerAccessibilityHealth,
    treeUnreadable: Bool = false
  ) {
    guard SnapshotGeometry.isPositiveFinite(geometry.windowOnScreen.rect) else { return nil }
    self.init(
      geometry: geometry,
      resolvedWindow: resolvedWindow,
      accessibilityHealth: accessibilityHealth,
      treeUnreadable: treeUnreadable
    )
  }
}
