// highwind-duo-helper runs inside an iPhone Duo simulator (through `xcrun simctl spawn`) and posts
// the HID events that fold it and turn it. Highwind compiles this file on first use (DuoHelper.swift).
//
//   highwind-duo-helper hinge-angle                       prints the hinge angle in degrees
//   highwind-duo-helper hinge-sweep <from> <to> <seconds> moves the hinge between two angles
//   highwind-duo-helper orientation <value>               portrait | pud | landscape-left | landscape-right
//
// Hinge and orientation: Device Hub sends a vendor-defined event (usage page 0xFF61, usage 0x5B)
// carrying a binary-serialized dictionary, which locationd's CMDeviceStateRelayManager turns into a
// hinge angle or a device orientation. The hinge payload was first documented by
// https://github.com/artemnovichkov/hinge.
//
// Derived from duoctl-helper in duoctl (https://github.com/skarol/duoctl):
//
// MIT License
//
// Copyright (c) 2026 Karolina Samorek
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#import <Foundation/Foundation.h>
#import <mach/mach_time.h>

typedef struct __IOHIDEvent *IOHIDEventRef;
typedef struct __IOHIDEventSystemClient *IOHIDEventSystemClientRef;

extern IOHIDEventSystemClientRef IOHIDEventSystemClientCreateWithType(CFAllocatorRef, int, CFDictionaryRef);
extern void IOHIDEventSystemClientDispatchEvent(IOHIDEventSystemClientRef, IOHIDEventRef);
extern CFDataRef IOCFSerialize(CFTypeRef, CFOptionFlags);
extern IOHIDEventRef IOHIDEventCreateVendorDefinedEvent(CFAllocatorRef, uint64_t, uint32_t usagePage, uint32_t usage,
    uint32_t version, const uint8_t *data, CFIndex length, uint32_t options);

enum {
    kClientTypeSimple = 4,
    kSerializeBinary = 1,
    kVendorUsagePage = 0xFF61,
    kVendorUsage = 0x5B,
};

static const double kMoveRate = 60.0;

#pragma mark - Device state (hinge, orientation)

// Device Hub's provider name differs between CoreSimulator versions. Every event carries an
// absolute value, so sending it under both names is harmless and each version takes its own.
static NSArray<NSString *> *deviceStateProviders(void) {
    return @[ @"com.apple.Virtualization.VirtualMachines", @"com.apple.Virtualization" ];
}

static void dispatchDeviceState(IOHIDEventSystemClientRef client, NSString *source, NSString *type, id value) {
    for (NSString *provider in deviceStateProviders()) {
        NSDictionary *payload = @{
            @"provider": provider,
            @"source": source,
            @"type": type,
            @"value": value,
        };
        NSData *data = CFBridgingRelease(IOCFSerialize((__bridge CFTypeRef)payload, kSerializeBinary));
        IOHIDEventRef event = IOHIDEventCreateVendorDefinedEvent(NULL, mach_absolute_time(), kVendorUsagePage,
                                                                 kVendorUsage, 0, data.bytes, (CFIndex)data.length, 0);
        IOHIDEventSystemClientDispatchEvent(client, event);
        CFRelease(event);
    }
}

static IOHIDEventSystemClientRef deviceStateClient(void) {
    IOHIDEventSystemClientRef client = IOHIDEventSystemClientCreateWithType(NULL, kClientTypeSimple, NULL);
    if (!client) fprintf(stderr, "highwind-duo-helper: could not create a HID event system client\n");
    return client;
}

static void finishDeviceState(IOHIDEventSystemClientRef client) {
    // The event system delivers asynchronously; exiting at once can drop the last event.
    usleep(100000);
    CFRelease(client);
}

static int postDeviceState(NSString *source, NSString *type, id value) {
    IOHIDEventSystemClientRef client = deviceStateClient();
    if (!client) return 1;
    dispatchDeviceState(client, source, type, value);
    finishDeviceState(client);
    return 0;
}

/// Moves the hinge in small steps so the fold animates instead of jumping.
static int sweepHinge(double from, double to, double seconds) {
    IOHIDEventSystemClientRef client = deviceStateClient();
    if (!client) return 1;
    int steps = MAX(1, (int)(seconds * kMoveRate));
    for (int step = 1; step <= steps; step++) {
        double t = (double)step / steps;
        double eased = t * t * (3 - 2 * t);
        dispatchDeviceState(client, @"hinge-slider-control", @"range", @(from + (to - from) * eased));
        if (step < steps) usleep((useconds_t)(1e6 / kMoveRate));
    }
    finishDeviceState(client);
    return 0;
}

#pragma mark - Hinge angle

// CoreMotion's private angle manager, the source UIKit's UIHinge reads.
@interface CMAngle : NSObject
- (float)angleDegrees;
@end

@interface CMAngleManager : NSObject
+ (BOOL)isAvailable;
- (void)startAngleUpdatesToQueue:(NSOperationQueue *)queue handler:(void (^)(CMAngle *angle))handler;
- (void)stopAngleUpdates;
@end

static const CFTimeInterval kAngleTimeout = 2;

// Prints the current hinge angle in degrees. CoreMotion delivers the current value right away.
static int printHingeAngle(void) {
    Class managerClass = NSClassFromString(@"CMAngleManager");
    if (!managerClass || ![managerClass isAvailable]) {
        fprintf(stderr, "highwind-duo-helper: this simulator reports no hinge\n");
        return 1;
    }
    CMAngleManager *manager = [[managerClass alloc] init];
    __block BOOL printed = NO;
    [manager startAngleUpdatesToQueue:[NSOperationQueue new] handler:^(CMAngle *angle) {
        if (printed) return;
        printed = YES;
        printf("%.1f\n", [angle angleDegrees]);
        fflush(stdout);
        CFRunLoopStop(CFRunLoopGetMain());
    }];
    CFRunLoopRunInMode(kCFRunLoopDefaultMode, kAngleTimeout, false);
    [manager stopAngleUpdates];
    if (!printed) fprintf(stderr, "highwind-duo-helper: timed out reading the hinge angle\n");
    return printed ? 0 : 1;
}

#pragma mark - Entry point

static int usage(void) {
    fprintf(stderr,
            "usage: highwind-duo-helper hinge-angle\n"
            "       highwind-duo-helper hinge-sweep <from> <to> <seconds>\n"
            "       highwind-duo-helper orientation <portrait|pud|landscape-left|landscape-right>\n");
    return 64;
}

int main(int argc, char **argv) {
    @autoreleasepool {
        if (argc < 2) return usage();
        NSString *command = @(argv[1]);

        if ([command isEqualToString:@"hinge-angle"] && argc == 2) return printHingeAngle();
        if ([command isEqualToString:@"hinge-sweep"] && argc == 5) {
            double from = fmin(fmax(atof(argv[2]), 0), 180), to = fmin(fmax(atof(argv[3]), 0), 180);
            return sweepHinge(from, to, fmax(atof(argv[4]), 0));
        }
        if ([command isEqualToString:@"orientation"] && argc == 3) {
            NSSet *valid = [NSSet setWithArray:@[ @"portrait", @"pud", @"landscape-left", @"landscape-right" ]];
            NSString *value = @(argv[2]);
            if (![valid containsObject:value]) return usage();
            return postDeviceState(@"orientation-picker-control", @"enum", value);
        }
        return usage();
    }
}
