using Health.Application.Diets;
using Health.Infrastructure.AI;

namespace Health.Infrastructure.Diets;

public sealed class DietImageAnalyzer(VisionClient vision) : IDietImageAnalyzer
{
    private readonly VisionClient _vision = vision;

    public async Task<DietImageAnalysisResult> AnalyzeAsync(DietImageAnalysisJob job, CancellationToken ct)
    {
        var imageUrls = new List<string>();
        foreach (var filePath in job.FilePaths)
        {
            if (!File.Exists(filePath))
                return new DietImageAnalysisResult(false, 40004, null, "待识别图片不存在");

            var bytes = await File.ReadAllBytesAsync(filePath, ct);
            var base64 = Convert.ToBase64String(bytes);
            if (base64.Length > 7 * 1024 * 1024)
                return new DietImageAnalysisResult(false, 40001, null, "图片过大，请压缩后重新上传");

            var extension = Path.GetExtension(filePath).ToLowerInvariant();
            var mime = extension switch
            {
                ".png" => "image/png",
                ".heic" => "image/heic",
                _ => "image/jpeg"
            };
            imageUrls.Add($"data:{mime};base64,{base64}");
        }

        var prompt = """
            识别图片中的食物和饮品，返回JSON数组：
            [{"name":"名称","portion":"份量","calories":热量}]
            只返回JSON，不要其他内容。
            """;
        var response = await _vision.VisionAsync(prompt, imageUrls, userText: null, maxTokens: 8192, ct: ct);
        var result = response.Choices?.FirstOrDefault()?.Message?.Content ?? "[]";
        return new DietImageAnalysisResult(true, 0, result, null);
    }
}
