#include "ThorRenderer.hpp"

#include <thorvg.h>

#include <thread>

using namespace tvg;

namespace {

// ThorVG's engine is process-global; initialize it exactly once. Worker threads
// let ThorVG rasterize a frame in parallel (see thor::recommendedThreadCount).
bool ensureThorVGInitialized() {
  static const bool initialized =
      (Initializer::init(thor::recommendedThreadCount()) == Result::Success);
  return initialized;
}

struct Rgba {
  uint8_t r, g, b, a;
};

Rgba unpackArgb(uint32_t argb) {
  return Rgba{static_cast<uint8_t>((argb >> 16) & 0xFF),
              static_cast<uint8_t>((argb >> 8) & 0xFF),
              static_cast<uint8_t>(argb & 0xFF),
              static_cast<uint8_t>((argb >> 24) & 0xFF)};
}

// Build geometry + paint for one shape. The shape may be reused across frames
// (see the pool below), so every paint property that could have been set on a
// previous frame is written unconditionally — otherwise stale fill/stroke would
// bleed through. Assumes the caller has already reset() the shape's path.
void applyShape(Shape* shape, const thor::ThorShapeDesc& d) {
  switch (d.type) {
  case thor::ThorShapeType::Rect:
    shape->appendRect(d.x, d.y, d.w, d.h, d.rx, d.ry);
    break;
  case thor::ThorShapeType::Circle:
    shape->appendCircle(d.cx, d.cy, d.radius, d.radius);
    break;
  case thor::ThorShapeType::Line:
    shape->moveTo(d.x1, d.y1);
    shape->lineTo(d.x2, d.y2);
    break;
  case thor::ThorShapeType::Polygon:
    if (d.points.size() >= 4) {
      shape->moveTo(d.points[0], d.points[1]);
      for (size_t i = 2; i + 1 < d.points.size(); i += 2) {
        shape->lineTo(d.points[i], d.points[i + 1]);
      }
      if (d.closed) {
        shape->close();
      }
    }
    break;
  }

  if (d.hasFill) {
    const Rgba c = unpackArgb(d.fillColor);
    shape->fill(c.r, c.g, c.b, c.a);
  } else {
    shape->fill(0, 0, 0, 0); // explicit transparent fill (borders-only)
  }

  if (d.hasStroke && d.strokeWidth > 0.0f) {
    const Rgba c = unpackArgb(d.strokeColor);
    shape->strokeWidth(d.strokeWidth);
    shape->strokeFill(c.r, c.g, c.b, c.a);
    shape->strokeJoin(StrokeJoin::Round);
    shape->strokeCap(StrokeCap::Round);
  } else {
    shape->strokeWidth(0.0f); // clear any stroke retained from a previous frame
  }
}

} // namespace

namespace thor {

unsigned recommendedThreadCount() {
  // ThorVG spreads a frame's rasterization across this many worker threads.
  // Cap at 4: measured throughput on ThorVG's banded SW rasterizer peaks around
  // 4 threads and *regresses* beyond it (per-band sync overhead outweighs the
  // gain) — e.g. for a 1080x1920 / 400-shape frame, 4 threads ran ~3.1x faster
  // than single-threaded while 8 threads were ~40% slower than 4. On mobile
  // big.LITTLE SoCs a higher count also spills onto slow efficiency cores.
  // Fall back to a sane default when the hardware count is unknown.
  unsigned hw = std::thread::hardware_concurrency();
  if (hw == 0) return 4;
  return hw < 4 ? hw : 4;
}

ThorRenderer::ThorRenderer() : _initialized(ensureThorVGInitialized()) {}

ThorRenderer::~ThorRenderer() {
  if (_canvas) delete static_cast<SwCanvas*>(_canvas);
}

bool ThorRenderer::renderScene(uint32_t* buffer, uint32_t width, uint32_t height,
                               const std::vector<ThorShapeDesc>& shapes,
                               PixelFormat format) {
  if (!_initialized || buffer == nullptr || width == 0 || height == 0) {
    return false;
  }

  // ARGB8888 == BGRA-in-memory (iOS CGImage); ABGR8888 == RGBA-in-memory
  // (Android Bitmap ARGB_8888).
  const ColorSpace cs =
      (format == PixelFormat::RGBA) ? ColorSpace::ABGR8888 : ColorSpace::ARGB8888;

  // Reuse one SwCanvas across frames; only (re)create + (re)target when the
  // destination buffer/size/format actually changes (avoids per-frame engine churn).
  auto* canvas = static_cast<SwCanvas*>(_canvas);
  if (canvas == nullptr) {
    canvas = SwCanvas::gen();
    _canvas = canvas;
    if (canvas == nullptr) return false;
  }
  if (buffer != _lastBuffer || width != _lastWidth || height != _lastHeight ||
      static_cast<int>(format) != _lastFormat) {
    if (canvas->target(buffer, width, width, height, cs) != Result::Success) {
      return false;
    }
    _lastBuffer = buffer;
    _lastWidth = width;
    _lastHeight = height;
    _lastFormat = static_cast<int>(format);
  }

  // Retained-scene update: reuse pooled shapes instead of freeing/allocating a
  // fresh Shape per shape per frame. Grow the pool with new paints (added once),
  // shrink it by removing the surplus, then reset()+refill the live ones.
  const size_t need = shapes.size();
  while (_pool.size() < need) {
    auto* s = Shape::gen();
    canvas->add(s); // ownership transfers to the canvas
    _pool.push_back(s);
  }
  while (_pool.size() > need) {
    canvas->remove(static_cast<Shape*>(_pool.back()));
    _pool.pop_back();
  }
  for (size_t i = 0; i < need; ++i) {
    auto* shape = static_cast<Shape*>(_pool[i]);
    shape->reset(); // clears the path (keeps buffers cached); paint re-set below
    applyShape(shape, shapes[i]);
  }

  const bool ok = (canvas->draw(true) == Result::Success);
  canvas->sync();
  return ok;
}

} // namespace thor
