#import "RunnerSynthesizedGesture.h"
#import "RunnerXCTestEventBridge.h"

#import <CoreGraphics/CoreGraphics.h>
#import <objc/message.h>

static NSString *const RunnerGestureSynthesisSurface = @"event";

typedef id (*RunnerMsgSendInitRecord)(id, SEL, NSString *, NSUInteger, NSInteger);
typedef id (*RunnerMsgSendInitPath)(id, SEL, CGPoint, NSTimeInterval);
typedef void (*RunnerMsgSendPathMove)(id, SEL, CGPoint, NSTimeInterval);
typedef void (*RunnerMsgSendPathOffset)(id, SEL, NSTimeInterval);

// Gesture-specific extension of the shared bridge: the display-aware
// `initWithName:displayID:interfaceOrientation:` record initializer and the touch-path
// factory/mutator selectors, none of which text-entry synthesis needs.
typedef struct {
  RunnerXCTestEventBridge core;
  SEL initRecordSelector;
  SEL initPathSelector;
  SEL moveSelector;
  SEL liftSelector;
} RunnerGestureEventBridge;

typedef id (*RunnerDragPointerPathFactory)(
  const RunnerGestureEventBridge *,
  CGPoint,
  CGPoint,
  double
);

static NSString * _Nullable RunnerResolveGestureEventBridge(
  id application,
  RunnerGestureEventBridge *bridge
);
static NSString * _Nullable RunnerCreateEventRecord(
  id application,
  id _Nullable resolvedWindow,
  NSInteger interfaceOrientation,
  NSString *recordName,
  RunnerGestureEventBridge *bridge,
  id *record
);
static NSString * _Nullable RunnerSynthesizeEventRecord(
  const RunnerGestureEventBridge *bridge,
  id record
);
static id RunnerSwipePointerPath(
  const RunnerGestureEventBridge *bridge,
  CGPoint start,
  CGPoint end,
  double durationMs
);
static id RunnerControlledScrollPointerPath(
  const RunnerGestureEventBridge *bridge,
  CGPoint start,
  CGPoint end,
  double durationMs
);
static NSString * _Nullable RunnerTrySynthesizeDrag(
  id application,
  id _Nullable resolvedWindow,
  NSInteger interfaceOrientation,
  CGPoint start,
  CGPoint end,
  double durationMs,
  NSString *recordName,
  RunnerDragPointerPathFactory pathFactory,
  BOOL * _Nullable dispatched
);
static RunnerTapSynthesisStatus RunnerTrySynthesizeTap(
  id application,
  id _Nullable resolvedWindow,
  NSInteger interfaceOrientation,
  CGPoint point,
  NSDate * _Nullable deadline,
  NSString * _Nullable * _Nullable errorMessage
);
// XCTest's proven swipe profile reaches the endpoint in 100 ms, then holds for the planned
// fling duration. Fast movement is what lets UIKit distinguish a fling from a timed pan.
static const NSTimeInterval RunnerSwipeMovementDurationSeconds = 0.1;
static const double RunnerDragSampleIntervalMs = 16.0;
static const NSInteger RunnerControlledScrollMaxFrameCount = 30;
static id RunnerTapPointerPath(
  const RunnerGestureEventBridge *bridge,
  CGPoint point
);

@implementation RunnerSynthesizedGesture

+ (NSString * _Nullable)synthesizeDragWithApplication:(id)application
                                      resolvedWindow:(id _Nullable)resolvedWindow
                                interfaceOrientation:(NSInteger)interfaceOrientation
                                                drag:(RunnerSynthesizedDrag)drag
                                          dispatched:(BOOL * _Nullable)dispatched {
  if (dispatched != NULL) *dispatched = NO;
  @try {
    return RunnerTrySynthesizeDrag(
      application, resolvedWindow, interfaceOrientation, drag.start, drag.end, drag.durationMs,
      drag.controlledScroll ? @"agent-device-controlled-scroll" : @"agent-device-swipe",
      drag.controlledScroll ? RunnerControlledScrollPointerPath : RunnerSwipePointerPath,
      dispatched
    );
  } @catch (NSException *exception) {
    return RunnerFormatXCTestException(exception, @"private XCTest event synthesis failed");
  }
}

+ (RunnerTapSynthesisStatus)synthesizeTapWithApplication:(id)application
                                      resolvedWindow:(id _Nullable)resolvedWindow
                                interfaceOrientation:(NSInteger)interfaceOrientation
                                               point:(CGPoint)point
                                            deadline:(NSDate * _Nullable)deadline
                                        errorMessage:(NSString * _Nullable * _Nullable)errorMessage {
  if (errorMessage != NULL) *errorMessage = nil;
  @try {
    return RunnerTrySynthesizeTap(application, resolvedWindow, interfaceOrientation, point, deadline, errorMessage);
  } @catch (NSException *exception) {
    if (errorMessage != NULL) {
      *errorMessage = RunnerFormatXCTestException(exception, @"private XCTest event synthesis failed");
    }
    return RunnerTapSynthesisStatusFailed;
  }
}

+ (NSString * _Nullable)synthesizeGestureWithApplication:(id)application
                                          resolvedWindow:(id _Nullable)resolvedWindow
                                    interfaceOrientation:(NSInteger)interfaceOrientation
                                          pointerSamples:(NSArray<NSArray<NSDictionary<NSString *, NSNumber *> *> *> *)pointerSamples
                                              dispatched:(BOOL * _Nullable)dispatched {
  if (dispatched != NULL) *dispatched = NO;
  @try {
    RunnerGestureEventBridge bridge;
    id record = nil;
    NSString *error = RunnerCreateEventRecord(
      application,
      resolvedWindow,
      interfaceOrientation,
      @"agent-device-gesture-plan",
      &bridge,
      &record
    );
    if (error != nil) return error;

    for (NSArray<NSDictionary<NSString *, NSNumber *> *> *samples in pointerSamples) {
      NSDictionary<NSString *, NSNumber *> *first = samples.firstObject;
      if (first == nil) return @"private XCTest event synthesis failed: empty pointer path";
      CGPoint start = CGPointMake(first[@"x"].doubleValue, first[@"y"].doubleValue);
      id path = ((RunnerMsgSendInitPath)objc_msgSend)(
        [bridge.core.pathClass alloc],
        bridge.initPathSelector,
        start,
        first[@"offsetMs"].doubleValue / 1000.0
      );
      if (path == nil) {
        return @"private XCTest event synthesis failed: could not create pointer path";
      }
      for (NSUInteger index = 1; index < samples.count; index += 1) {
        NSDictionary<NSString *, NSNumber *> *sample = samples[index];
        CGPoint point = CGPointMake(sample[@"x"].doubleValue, sample[@"y"].doubleValue);
        ((RunnerMsgSendPathMove)objc_msgSend)(
          path,
          bridge.moveSelector,
          point,
          sample[@"offsetMs"].doubleValue / 1000.0
        );
      }
      NSDictionary<NSString *, NSNumber *> *last = samples.lastObject;
      ((RunnerMsgSendPathOffset)objc_msgSend)(
        path,
        bridge.liftSelector,
        last[@"offsetMs"].doubleValue / 1000.0
      );
      ((RunnerMsgSendAddPath)objc_msgSend)(record, bridge.core.addPathSelector, path);
    }

    if (dispatched != NULL) *dispatched = YES;
    return RunnerSynthesizeEventRecord(&bridge, record);
  } @catch (NSException *exception) {
    return RunnerFormatXCTestException(exception, @"private XCTest event synthesis failed");
  }
}

+ (NSInteger)interfaceOrientationForApplication:(id)application {
  SEL selector = NSSelectorFromString(@"interfaceOrientation");
  if (![application respondsToSelector:selector]) {
    return 0;  // UIInterfaceOrientationUnknown
  }
  return ((RunnerMsgSendInteger)objc_msgSend)(application, selector);
}

static NSString * _Nullable RunnerTrySynthesizeDrag(
  id application,
  id _Nullable resolvedWindow,
  NSInteger interfaceOrientation,
  CGPoint start,
  CGPoint end,
  double durationMs,
  NSString *recordName,
  RunnerDragPointerPathFactory pathFactory,
  BOOL * _Nullable dispatched
) {
  RunnerGestureEventBridge bridge;
  id record = nil;
  NSString *error = RunnerCreateEventRecord(application, resolvedWindow, interfaceOrientation, recordName, &bridge, &record);
  if (error != nil) return error;

  id path = pathFactory(&bridge, start, end, durationMs);
  if (path == nil) {
    return @"private XCTest event synthesis failed: could not create pointer path";
  }
  ((RunnerMsgSendAddPath)objc_msgSend)(record, bridge.core.addPathSelector, path);

  if (dispatched != NULL) *dispatched = YES;
  return RunnerSynthesizeEventRecord(&bridge, record);
}

static RunnerTapSynthesisStatus RunnerTrySynthesizeTap(
  id application,
  id _Nullable resolvedWindow,
  NSInteger interfaceOrientation,
  CGPoint point,
  NSDate * _Nullable deadline,
  NSString * _Nullable * _Nullable errorMessage
) {
  RunnerGestureEventBridge bridge;
  id record = nil;
  NSString *error = RunnerCreateEventRecord(
    application,
    resolvedWindow,
    interfaceOrientation,
    @"agent-device-tap",
    &bridge,
    &record
  );
  if (error != nil) {
    if (errorMessage != NULL) *errorMessage = error;
    return RunnerTapSynthesisStatusFailed;
  }

  id path = RunnerTapPointerPath(&bridge, point);
  if (path == nil) {
    if (errorMessage != NULL) *errorMessage = @"private XCTest event synthesis failed: could not create pointer path";
    return RunnerTapSynthesisStatusFailed;
  }
  ((RunnerMsgSendAddPath)objc_msgSend)(record, bridge.core.addPathSelector, path);
  if (deadline != nil && deadline.timeIntervalSinceNow <= 0) {
    return RunnerTapSynthesisStatusDeadlineExceeded;
  }
  error = RunnerSynthesizeEventRecord(&bridge, record);
  if (errorMessage != NULL) *errorMessage = error;
  return error == nil ? RunnerTapSynthesisStatusSucceeded : RunnerTapSynthesisStatusFailed;
}

static NSString * _Nullable RunnerResolveGestureEventBridge(
  id application,
  RunnerGestureEventBridge *bridge
) {
  RunnerXCTestEventBridge core;
  NSString *missing = RunnerResolveXCTestEventBridge(application, RunnerGestureSynthesisSurface, &core);
  if (missing != nil) return missing;

  SEL initRecordSelector = NSSelectorFromString(@"initWithName:displayID:interfaceOrientation:");
  SEL initPathSelector = NSSelectorFromString(@"initForTouchAtPoint:offset:");
  SEL moveSelector = NSSelectorFromString(@"moveToPoint:atOffset:");
  SEL liftSelector = NSSelectorFromString(@"liftUpAtOffset:");

  missing = RunnerRequireSelector(
    core.recordClass, initRecordSelector, @"initWithName:displayID:interfaceOrientation:", RunnerGestureSynthesisSurface
  );
  if (missing != nil) return missing;
  missing = RunnerRequireSelector(
    core.pathClass, initPathSelector, @"initForTouchAtPoint:offset:", RunnerGestureSynthesisSurface
  );
  if (missing != nil) return missing;
  missing = RunnerRequireSelector(
    core.pathClass, moveSelector, @"moveToPoint:atOffset:", RunnerGestureSynthesisSurface
  );
  if (missing != nil) return missing;
  missing = RunnerRequireSelector(
    core.pathClass, liftSelector, @"liftUpAtOffset:", RunnerGestureSynthesisSurface
  );
  if (missing != nil) return missing;

  *bridge = (RunnerGestureEventBridge){
    .core = core,
    .initRecordSelector = initRecordSelector,
    .initPathSelector = initPathSelector,
    .moveSelector = moveSelector,
    .liftSelector = liftSelector,
  };
  return nil;
}

static NSString * _Nullable RunnerCreateEventRecord(
  id application,
  id _Nullable resolvedWindow,
  NSInteger interfaceOrientation,
  NSString *recordName,
  RunnerGestureEventBridge *bridge,
  id *record
) {
  NSString *missing = RunnerResolveGestureEventBridge(application, bridge);
  if (missing != nil) return missing;

  NSUInteger displayID = 0;
  // A nil window is the caller's sole-screen route: the app tree could not name its window.
  // Re-asking here, at dispatch, is what keeps the record's display the one the app fills now.
  id soleScreen = nil;
  NSString *displayError = resolvedWindow == nil
    ? RunnerResolveSoleScreen(application, &soleScreen, &displayID)
    : RunnerResolveWindowDisplayID(resolvedWindow, &displayID);
  if (displayError != nil) return displayError;
  NSInteger targetProcessID =
    ((RunnerMsgSendInteger)objc_msgSend)(application, bridge->core.processIDSelector);
  if (targetProcessID <= 0) {
    return @"private XCTest event synthesis unavailable: could not resolve target process ID";
  }

  id eventRecord = ((RunnerMsgSendInitRecord)objc_msgSend)(
    [bridge->core.recordClass alloc],
    bridge->initRecordSelector,
    recordName,
    displayID,
    interfaceOrientation
  );
  if (eventRecord == nil) {
    return @"private XCTest event synthesis failed: could not create event record";
  }
  NSLog(
    @"AGENT_DEVICE_RUNNER_SYNTHESIZED_RECORD name=%@ displayID=%lu interfaceOrientation=%ld",
    recordName,
    (unsigned long)displayID,
    (long)interfaceOrientation
  );
  ((RunnerMsgSendSetInteger)objc_msgSend)(
    eventRecord,
    bridge->core.setTargetProcessIDSelector,
    targetProcessID
  );
  *record = eventRecord;
  return nil;
}

static NSString * _Nullable RunnerSynthesizeEventRecord(
  const RunnerGestureEventBridge *bridge,
  id record
) {
  NSError *error = nil;
  BOOL ok = ((RunnerMsgSendSynthesize)objc_msgSend)(record, bridge->core.synthesizeSelector, &error);
  if (!ok) {
    NSString *detail = error.localizedDescription ?: @"synthesizeWithError returned false";
    return [NSString stringWithFormat:@"private XCTest event synthesis failed: %@", detail];
  }
  return nil;
}

static id RunnerSwipePointerPath(
  const RunnerGestureEventBridge *bridge,
  CGPoint start,
  CGPoint end,
  double durationMs
) {
  id path =
    ((RunnerMsgSendInitPath)objc_msgSend)([bridge->core.pathClass alloc], bridge->initPathSelector, start, 0.0);
  if (path == nil) {
    return nil;
  }

  NSTimeInterval durationSeconds = durationMs / 1000.0;
  ((RunnerMsgSendPathMove)objc_msgSend)(
    path,
    bridge->moveSelector,
    end,
    RunnerSwipeMovementDurationSeconds
  );
  ((RunnerMsgSendPathOffset)objc_msgSend)(
    path,
    bridge->liftSelector,
    RunnerSwipeMovementDurationSeconds + durationSeconds
  );
  return path;
}

static id RunnerControlledScrollPointerPath(
  const RunnerGestureEventBridge *bridge,
  CGPoint start,
  CGPoint end,
  double durationMs
) {
  // A stationary hold is not a reliable zero-velocity release in XCTest. Cubic ease-out decreases
  // velocity from the first movement and reaches near zero before lift. Profiles that accelerate
  // after pan recognition can still be classified as flings despite a slow final sample.
  id path =
    ((RunnerMsgSendInitPath)objc_msgSend)([bridge->core.pathClass alloc], bridge->initPathSelector, start, 0.0);
  if (path == nil) {
    return nil;
  }

  NSInteger frameCount = RunnerControlledScrollFrameCount(durationMs);
  NSTimeInterval durationSeconds = durationMs / 1000.0;
  for (NSInteger index = 1; index <= frameCount; index += 1) {
    double t = (double)index / (double)frameCount;
    double easedT = RunnerControlledScrollProgress(t);
    CGPoint point = CGPointMake(
      start.x + (end.x - start.x) * easedT,
      start.y + (end.y - start.y) * easedT
    );
    ((RunnerMsgSendPathMove)objc_msgSend)(path, bridge->moveSelector, point, durationSeconds * t);
  }

  ((RunnerMsgSendPathOffset)objc_msgSend)(path, bridge->liftSelector, durationSeconds);
  return path;
}

NSInteger RunnerControlledScrollFrameCount(double durationMs) {
  return MIN(
    RunnerControlledScrollMaxFrameCount,
    MAX(3, (NSInteger)ceil(durationMs / RunnerDragSampleIntervalMs) - 1)
  );
}

double RunnerControlledScrollProgress(double t) {
  double remaining = 1.0 - t;
  return 1.0 - remaining * remaining * remaining;
}

static id RunnerTapPointerPath(
  const RunnerGestureEventBridge *bridge,
  CGPoint point
) {
  id path =
    ((RunnerMsgSendInitPath)objc_msgSend)([bridge->core.pathClass alloc], bridge->initPathSelector, point, 0.0);
  if (path == nil) {
    return nil;
  }
  ((RunnerMsgSendPathOffset)objc_msgSend)(path, bridge->liftSelector, 0.05);
  return path;
}

@end
