namespace Health.Infrastructure.AI.AgentHandlers;

/// <summary>
/// 记数据 Agent 工具处理器——录入健康指标
/// </summary>
public static class HealthDataAgentHandler
{
    public static readonly ToolDefinition RecordHealthDataTool = new()
    {
        Function = new()
        {
            Name = "record_health_data", Description = "记录健康数据（血压/心率/血糖/血氧/体重）",
            Parameters = new { type = "object", properties = new { type = new { type = "string" }, systolic = new { type = "integer" }, diastolic = new { type = "integer" }, heart_rate = new { type = "number" }, glucose = new { type = "number" }, spo2 = new { type = "number" }, weight = new { type = "number" } }, required = new[] { "type" } }
        }
    };

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

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

    private static async Task<object> ExecuteRecordHealthData(AppDbContext db, Guid userId, JsonElement args)
    {
        var type = args.TryGetProperty("type", out var t) ? t.GetString()! : "";
        var record = new HealthRecord
        {
            Id = Guid.NewGuid(), UserId = userId, Source = HealthRecordSource.AiEntry,
            RecordedAt = args.TryGetProperty("recorded_at", out var ra) && ra.TryGetDateTime(out var dt) ? dt : DateTime.UtcNow,
            CreatedAt = DateTime.UtcNow,
        };

        switch (type)
        {
            case "blood_pressure":
                record.MetricType = HealthMetricType.BloodPressure;
                record.Systolic = args.TryGetProperty("systolic", out var s) ? s.GetInt32() : null;
                record.Diastolic = args.TryGetProperty("diastolic", out var d) ? d.GetInt32() : null;
                record.Unit = "mmHg";
                record.IsAbnormal = record.Systolic >= 140 || record.Diastolic >= 90 || record.Systolic <= 89 || record.Diastolic <= 59;
                break;
            case "heart_rate":
                record.MetricType = HealthMetricType.HeartRate;
                record.Value = args.TryGetProperty("heart_rate", out var hr) ? hr.GetDecimal() : null;
                record.Unit = "次/分";
                record.IsAbnormal = record.Value > 100 || record.Value < 60;
                break;
            case "glucose":
                record.MetricType = HealthMetricType.Glucose;
                record.Value = args.TryGetProperty("glucose", out var g) ? g.GetDecimal() : null;
                record.Unit = "mmol/L";
                record.IsAbnormal = record.Value >= 7.0m || record.Value <= 3.8m;
                break;
            case "spo2":
                record.MetricType = HealthMetricType.SpO2;
                record.Value = args.TryGetProperty("spo2", out var o) ? o.GetDecimal() : null;
                record.Unit = "%";
                record.IsAbnormal = record.Value <= 94;
                break;
            case "weight":
                record.MetricType = HealthMetricType.Weight;
                record.Value = args.TryGetProperty("weight", out var w) ? w.GetDecimal() : null;
                record.Unit = "kg";
                break;
            default:
                return new { success = false, message = $"未知指标类型: {type}" };
        }

        db.HealthRecords.Add(record);
        await db.SaveChangesAsync();
        return new { success = true, record_id = record.Id, type = record.MetricType.ToString() };
    }
}
