#import "ThorRenderBridge.h"

#import "ThorRenderer.hpp"

#import <QuartzCore/QuartzCore.h>
#import <vector>

// Builds the C++ scene from the parallel primitive arrays (mirrors the Android
// JNI marshaller). params is stride-8 per shape: [strokeWidth, g1..g6, closed].
static void buildScene(int count, const int32_t *types, const uint32_t *fills,
                       const uint32_t *strokes, const float *params,
                       const float *pointsFlat, const int32_t *pointCounts,
                       std::vector<thor::ThorShapeDesc> &scene) {
  scene.clear();
  scene.reserve(static_cast<size_t>(count));
  int pointsOffset = 0;
  for (int i = 0; i < count; ++i) {
    thor::ThorShapeDesc d;
    d.type = static_cast<thor::ThorShapeType>(types[i]);

    const uint32_t fill = fills[i];
    if ((fill >> 24) != 0u) {
      d.hasFill = true;
      d.fillColor = fill;
    }
    const uint32_t stroke = strokes[i];
    const float *p = &params[i * 8];
    const float sw = p[0];
    if ((stroke >> 24) != 0u && sw > 0.0f) {
      d.hasStroke = true;
      d.strokeColor = stroke;
      d.strokeWidth = sw;
    }
    d.closed = (p[7] != 0.0f);

    switch (d.type) {
    case thor::ThorShapeType::Rect:
      d.x = p[1]; d.y = p[2]; d.w = p[3]; d.h = p[4]; d.rx = p[5]; d.ry = p[6];
      break;
    case thor::ThorShapeType::Circle:
      d.cx = p[1]; d.cy = p[2]; d.radius = p[3];
      break;
    case thor::ThorShapeType::Line:
      d.x1 = p[1]; d.y1 = p[2]; d.x2 = p[3]; d.y2 = p[4];
      break;
    case thor::ThorShapeType::Polygon: {
      const int n = pointCounts[i];
      if (n > 0) {
        d.points.assign(pointsFlat + pointsOffset, pointsFlat + pointsOffset + n);
      }
      break;
    }
    }
    pointsOffset += pointCounts[i];
    scene.push_back(std::move(d));
  }
}

@implementation ThorRenderBridge

+ (nullable UIImage *)imageWithWidth:(int)width
                              height:(int)height
                               count:(int)count
                               types:(const int32_t *)types
                               fills:(const uint32_t *)fills
                             strokes:(const uint32_t *)strokes
                              params:(const float *)params
                          pointsFlat:(const float *)pointsFlat
                         pointCounts:(const int32_t *)pointCounts {
  if (width <= 0 || height <= 0) {
    return nil;
  }

  // Called on the main thread only — these statics are reused across frames to
  // avoid per-frame allocation (renderer + engine, scratch scene vector, pixel
  // buffer, and the device color space).
  static thor::ThorRenderer renderer;
  static std::vector<thor::ThorShapeDesc> scene;
  static std::vector<uint32_t> buffer;
  static CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

  // PERF: windowed per-frame timing (marshal + ThorVG rasterize), logged under
  // the "ThorPerf" tag every 120 frames — the iOS analogue of the Android log.
  static uint64_t sFrame = 0;
  static double sMarshalMs = 0, sRasterMs = 0, sMaxMs = 0;
  const CFTimeInterval t0 = CACurrentMediaTime();

  buildScene(count, types, fills, strokes, params, pointsFlat, pointCounts, scene);
  const CFTimeInterval t1 = CACurrentMediaTime();

  const size_t pixelCount = static_cast<size_t>(width) * static_cast<size_t>(height);
  if (buffer.size() < pixelCount) buffer.assign(pixelCount, 0); // grow only

  const bool ok = renderer.renderScene(buffer.data(), static_cast<uint32_t>(width),
                                       static_cast<uint32_t>(height), scene);
  const CFTimeInterval t2 = CACurrentMediaTime();
  sMarshalMs += (t1 - t0) * 1000.0;
  sRasterMs += (t2 - t1) * 1000.0;
  const double total = (t2 - t0) * 1000.0;
  if (total > sMaxMs) sMaxMs = total;
  if (++sFrame % 120 == 0) {
    NSLog(@"ThorPerf CPU %dx%d shapes=%d  marshal=%.3fms  raster=%.3fms  total=%.3fms  max=%.3fms",
          width, height, count, sMarshalMs / 120.0, sRasterMs / 120.0,
          (sMarshalMs + sRasterMs) / 120.0, sMaxMs);
    sMarshalMs = 0; sRasterMs = 0; sMaxMs = 0;
  }
  if (!ok) {
    return nil;
  }

  const CGBitmapInfo bitmapInfo =
      static_cast<CGBitmapInfo>(kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
  CGContextRef context =
      CGBitmapContextCreate(buffer.data(), static_cast<size_t>(width),
                            static_cast<size_t>(height), 8,
                            static_cast<size_t>(width) * 4, colorSpace, bitmapInfo);

  UIImage *image = nil;
  if (context != NULL) {
    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    if (cgImage != NULL) {
      image = [UIImage imageWithCGImage:cgImage scale:1.0
                           orientation:UIImageOrientationUp];
      CGImageRelease(cgImage);
    }
    CGContextRelease(context);
  }
  return image;
}

@end
