namespace Health.Infrastructure.AI.AgentHandlers;

/// <summary>
/// 运动计划 Agent 工具处理器
/// </summary>
public static class ExerciseAgentHandler
{
    public static readonly ToolDefinition ManageExerciseTool = new()
    {
        Function = new()
        {
            Name = "manage_exercise", Description = "运动计划管理",
            Parameters = new { type = "object", properties = new { action = new { type = "string" } }, required = new[] { "action" } }
        }
    };

    public static List<ToolDefinition> Tools => [ManageExerciseTool];

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

    private static async Task<object> ExecuteManageExercise(AppDbContext db, Guid userId, JsonElement args)
    {
        var action = args.TryGetProperty("action", out var a) ? a.GetString()! : "query";
        switch (action)
        {
            case "create":
                var weekStart = args.TryGetProperty("week_start_date", out var wsd) ? DateOnly.Parse(wsd.GetString()!) : DateOnly.FromDateTime(DateTime.Now);
                var plan = new ExercisePlan { Id = Guid.NewGuid(), UserId = userId, WeekStartDate = weekStart };
                if (args.TryGetProperty("items", out var items))
                {
                    foreach (var item in items.EnumerateArray())
                    {
                        plan.Items.Add(new ExercisePlanItem
                        {
                            Id = Guid.NewGuid(), DayOfWeek = item.GetProperty("day_of_week").GetInt32(),
                            ExerciseType = item.GetProperty("exercise_type").GetString() ?? "散步",
                            DurationMinutes = item.GetProperty("duration_minutes").GetInt32(),
                            IsRestDay = item.TryGetProperty("is_rest_day", out var rd) && rd.GetBoolean(),
                        });
                    }
                }
                db.ExercisePlans.Add(plan);
                await db.SaveChangesAsync();
                return new { success = true, plan_id = plan.Id };

            case "checkin":
                var itemId = args.TryGetProperty("item_id", out var iid) ? iid.GetGuid() : Guid.Empty;
                var exerciseItem = await db.ExercisePlanItems.FindAsync([itemId]);
                if (exerciseItem == null) return new { success = false, message = "条目不存在" };
                exerciseItem.IsCompleted = true;
                exerciseItem.CompletedAt = DateTime.UtcNow;
                await db.SaveChangesAsync();
                return new { success = true };

            default:
                var existingPlan = await db.ExercisePlans.Where(p => p.UserId == userId)
                    .OrderByDescending(p => p.WeekStartDate).FirstOrDefaultAsync();
                if (existingPlan == null) return new { found = false };
                var exerciseItems = await db.ExercisePlanItems.Where(i => i.PlanId == existingPlan.Id).OrderBy(i => i.DayOfWeek).ToListAsync();
                return new { found = true, plan_id = existingPlan.Id, items = exerciseItems.Select(i => new { i.Id, i.DayOfWeek, i.ExerciseType, i.DurationMinutes, i.IsCompleted }) };
        }
    }
}
