using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XPrintServer.TestConsole
{

    // StarVectorInference.cs
    using Microsoft.ML.OnnxRuntime;
    using Microsoft.ML.OnnxRuntime.Tensors;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;

    public class StarVectorRunner
    {
        private InferenceSession session;
        private int[] inputShape;

        public StarVectorRunner(string onnxPath)
        {
            session = new InferenceSession(onnxPath);
            inputShape = session.InputMetadata["pixel_values"].Dimensions.ToArray();
        }

        public string GenerateSvg(string imagePath)
        {
            // 1. 加载并处理图像
            using var bitmap = new Bitmap(imagePath);
            var resizedBitmap = ResizeImage(bitmap, inputShape[2], inputShape[3]);
            float[] imageData = ImageToFloatArray(resizedBitmap);

            // 2. 创建输入张量
            var inputTensor = new DenseTensor<float>(imageData, inputShape);
            var inputs = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor("pixel_values", inputTensor) };

            // 3. 运行推理
            using var results = session.Run(inputs);
            var outputData = results.First().AsEnumerable<byte>().ToArray();

            // 4. 解析输出为 SVG 字符串
            return System.Text.Encoding.UTF8.GetString(outputData);
        }

        private Bitmap ResizeImage(Image image, int width, int height)
        {
            var resized = new Bitmap(width, height);
            using var graphics = Graphics.FromImage(resized);
            graphics.DrawImage(image, 0, 0, width, height);
            return resized;
        }

        private float[] ImageToFloatArray(Image image)
        {
            using var ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);
            var bytes = ms.ToArray();
            return bytes.Select(b => (float)b / 255f).ToArray();
        }
    }
}
