#import "PanelColorizerBridge.h"
#import <ImageIO/ImageIO.h>
#import <UIKit/UIKit.h>
#import <onnxruntime.h>

NSData *YokanDecodePanel(NSData *data, int maxSide, int *width, int *height) {
    @autoreleasepool {
        CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, nullptr);
        if (!source) return nil;
        NSDictionary *options = @{
            (NSString *)kCGImageSourceCreateThumbnailFromImageAlways: @YES,
            (NSString *)kCGImageSourceThumbnailMaxPixelSize: @(maxSide),
            (NSString *)kCGImageSourceCreateThumbnailWithTransform: @YES,
            (NSString *)kCGImageSourceShouldCacheImmediately: @YES,
        };
        CGImageRef image = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef)options);
        CFRelease(source);
        if (!image) return nil;
        *width = (int)CGImageGetWidth(image); *height = (int)CGImageGetHeight(image);
        if (*width <= 0 || *height <= 0 || *width > maxSide || *height > maxSide) { CGImageRelease(image); return nil; }
        NSMutableData *pixels = [NSMutableData dataWithLength:(NSUInteger)(*width) * (*height) * 4];
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(pixels.mutableBytes, *width, *height, 8, *width * 4, colorSpace,
                                                    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
        CGColorSpaceRelease(colorSpace);
        if (!context) { CGImageRelease(image); return nil; }
        CGContextSetRGBFillColor(context, 1, 1, 1, 1);
        CGContextFillRect(context, CGRectMake(0, 0, *width, *height));
        CGContextDrawImage(context, CGRectMake(0, 0, *width, *height), image);
        CGContextRelease(context); CGImageRelease(image);
        return pixels;
    }
}

NSData *YokanDecodePanelFullPage(NSData *data, int *width, int *height, int *failureCode) {
    @autoreleasepool {
        *failureCode = 1;
        CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, nullptr);
        if (!source) return nil;
        if (CGImageSourceGetStatus(source) != kCGImageStatusComplete ||
            CGImageSourceGetStatusAtIndex(source, 0) != kCGImageStatusComplete) {
            CFRelease(source);
            return nil;
        }
        NSDictionary *properties = CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(source, 0, nullptr));
        NSNumber *sourceWidth = properties[(NSString *)kCGImagePropertyPixelWidth];
        NSNumber *sourceHeight = properties[(NSString *)kCGImagePropertyPixelHeight];
        NSDictionary *tiffProperties = properties[(NSString *)kCGImagePropertyTIFFDictionary];
        NSNumber *orientationValue = properties[(NSString *)kCGImagePropertyOrientation] ?:
            tiffProperties[(NSString *)kCGImagePropertyTIFFOrientation];
        uint64_t rawWidth = sourceWidth.unsignedLongLongValue;
        uint64_t rawHeight = sourceHeight.unsignedLongLongValue;
        if (!sourceWidth || !sourceHeight || rawWidth == 0 || rawHeight == 0 || rawWidth > 4096 || rawHeight > 4096 ||
            rawWidth * rawHeight > 8000000ULL) {
            if (sourceWidth && sourceHeight && rawWidth > 0 && rawHeight > 0) *failureCode = 2;
            CFRelease(source);
            return nil;
        }
        NSUInteger orientation = orientationValue ? orientationValue.unsignedIntegerValue : 1;
        if (orientation < 1 || orientation > 8) {
            CFRelease(source);
            return nil;
        }
        // ImageIO's transformed thumbnail preserves full resolution here: the validated source is
        // already within maxPixelSize. Its transform applies EXIF orientation before rasterization.
        NSDictionary *options = @{
            (NSString *)kCGImageSourceCreateThumbnailFromImageAlways: @YES,
            (NSString *)kCGImageSourceThumbnailMaxPixelSize: @4096,
            (NSString *)kCGImageSourceCreateThumbnailWithTransform: @YES,
            (NSString *)kCGImageSourceShouldCacheImmediately: @YES,
        };
        CGImageRef image = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef)options);
        CFRelease(source);
        if (!image) return nil;
        size_t decodedWidth = CGImageGetWidth(image);
        size_t decodedHeight = CGImageGetHeight(image);
        if (decodedWidth == 0 || decodedHeight == 0 || decodedWidth > 4096 || decodedHeight > 4096 ||
            (uint64_t)decodedWidth * (uint64_t)decodedHeight > 8000000ULL) {
            *failureCode = 2;
            CGImageRelease(image);
            return nil;
        }
        *width = (int)decodedWidth;
        *height = (int)decodedHeight;
        NSMutableData *pixels = [NSMutableData dataWithLength:(NSUInteger)decodedWidth * decodedHeight * 4];
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(pixels.mutableBytes, *width, *height, 8, *width * 4, colorSpace,
                                                    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
        CGColorSpaceRelease(colorSpace);
        if (!context) { CGImageRelease(image); return nil; }
        CGContextDrawImage(context, CGRectMake(0, 0, *width, *height), image);
        // CGBitmapContext stores premultiplied RGBA; expose straight RGBA to Kotlin/ARGB.
        uint8_t *rgba = (uint8_t *)pixels.mutableBytes;
        NSUInteger pixelCount = (NSUInteger)decodedWidth * decodedHeight;
        for (NSUInteger i = 0; i < pixelCount; i++) {
            uint8_t alpha = rgba[i * 4 + 3];
            if (alpha == 0) {
                rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = 0;
            } else if (alpha < 255) {
                for (NSUInteger channel = 0; channel < 3; channel++) {
                    rgba[i * 4 + channel] = (uint8_t)MIN(255, (rgba[i * 4 + channel] * 255 + alpha / 2) / alpha);
                }
            }
        }
        CGContextRelease(context);
        CGImageRelease(image);
        *failureCode = 0;
        return pixels;
    }
}

NSData *YokanEncodePanel(const uint32_t *argb, int width, int height) {
    @autoreleasepool {
        if (width <= 0 || height <= 0 || width > 4096 || height > 4096 ||
            (uint64_t)width * (uint64_t)height > 8000000ULL) return nil;
        NSMutableData *data = [NSMutableData dataWithLength:(NSUInteger)width * height * 4];
        uint8_t *pixels = (uint8_t *)data.mutableBytes;
        for (int i = 0; i < width * height; i++) {
            uint8_t alpha = (argb[i] >> 24) & 255;
            pixels[i * 4 + 2] = ((argb[i] & 255) * alpha + 127) / 255;
            pixels[i * 4 + 3] = alpha;
            pixels[i * 4] = (((argb[i] >> 16) & 255) * alpha + 127) / 255;
            pixels[i * 4 + 1] = (((argb[i] >> 8) & 255) * alpha + 127) / 255;
        }
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * 4, colorSpace,
                                                    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
        CGColorSpaceRelease(colorSpace);
        if (!context) return nil;
        CGImageRef image = CGBitmapContextCreateImage(context);
        NSData *png = image ? UIImagePNGRepresentation([UIImage imageWithCGImage:image]) : nil;
        if (image) CGImageRelease(image);
        CGContextRelease(context);
        return png;
    }
}

BOOL YokanInferPanel(NSString *modelPath, const float *input, float *output, int width, int height) {
    @autoreleasepool {
        if (width <= 0 || height <= 0 || width % 32 != 0 || height % 32 != 0) return NO;
        NSError *error = nil;
        ORTEnv *env = [[ORTEnv alloc] initWithLoggingLevel:ORTLoggingLevelWarning error:&error];
        ORTSessionOptions *options = [[ORTSessionOptions alloc] initWithError:&error];
        if (!env || !options || ![options setIntraOpNumThreads:1 error:&error] ||
            ![options setGraphOptimizationLevel:ORTGraphOptimizationLevelNone error:&error] ||
            ![options addConfigEntryWithKey:@"session.disable_prepacking" value:@"1" error:&error]) return NO;
        ORTSession *session = [[ORTSession alloc] initWithEnv:env modelPath:modelPath sessionOptions:options error:&error];
        if (!session) return NO;
        NSMutableData *inputData = [NSMutableData dataWithBytes:input length:5 * width * height * sizeof(float)];
        NSMutableData *outputData = [NSMutableData dataWithLength:3 * width * height * sizeof(float)];
        ORTValue *inputTensor = [[ORTValue alloc] initWithTensorData:inputData elementType:ORTTensorElementDataTypeFloat
                                                          shape:@[@1, @5, @(height), @(width)] error:&error];
        ORTValue *outputTensor = [[ORTValue alloc] initWithTensorData:outputData elementType:ORTTensorElementDataTypeFloat
                                                           shape:@[@1, @3, @(height), @(width)] error:&error];
        if (!inputTensor || !outputTensor) return NO;
        BOOL success = [session runWithInputs:@{@"input":inputTensor} outputs:@{@"rgb":outputTensor} runOptions:nil error:&error];
        if (success) memcpy(output, outputData.bytes, outputData.length);
        return success;
        // ARC + the autorelease pool release tensors, session, weights, and temporary buffers each job.
    }
}
