namespace Health.Infrastructure.AI.AgentHandlers;

/// <summary>
/// 看报告 Agent 工具处理器——报告分析
/// </summary>
public static class ReportAgentHandler
{
    public static readonly ToolDefinition AnalyzeReportTool = new()
    {
        Function = new() { Name = "analyze_report", Description = "分析报告图片", Parameters = new { type = "object", properties = new { image_url = new { type = "string" } }, required = new[] { "image_url" } } }
    };

    public static List<ToolDefinition> Tools => [AnalyzeReportTool, CommonAgentHandler.QueryHealthRecordsTool];

    public static Task<object> Execute(string toolName, JsonElement args, AppDbContext db, Guid userId)
    {
        return toolName switch
        {
            "query_health_records" => CommonAgentHandler.Execute(toolName, args, db, userId),
            _ => Task.FromResult<object>(new { success = false, message = $"未知工具: {toolName}" })
        };
    }

    public static async Task<object> AnalyzeReport(AppDbContext db, Guid userId, JsonElement args, VisionClient visionClient)
    {
        var imageUrl = args.TryGetProperty("image_url", out var u) ? u.GetString()! : "";
        if (string.IsNullOrEmpty(imageUrl))
            return new { success = false, message = "缺少报告图片" };

        var prompt = """
            你是一个医学报告解读专家。请分析以下检查报告图片，以JSON格式返回：
            {
              "reportType": "报告类型（血常规/生化全项/心电图/彩超/出院小结/其他）",
              "indicators": [
                {"name":"指标名","value":"数值","unit":"单位","range":"参考范围","status":"normal/high/low"}
              ],
              "summary": "初步分析摘要",
              "needsDoctorReview": true/false
            }
            只返回JSON，不要其他内容。
            """;

        var response = await visionClient.VisionAsync(prompt, [imageUrl], userText: "请分析这份检查报告");
        var content = response.Choices?.FirstOrDefault()?.Message?.Content ?? "{}";

        // 保存到报告记录
        var report = await db.Reports
            .OrderByDescending(r => r.CreatedAt)
            .FirstOrDefaultAsync(r => r.UserId == userId && r.Status == ReportStatus.PendingDoctor);
        if (report != null)
        {
            report.AiSummary = content;
            report.AiIndicators = content;
        }

        return new { success = true, analysis = content };
    }
}
