namespace Health.Infrastructure.AI.AgentHandlers;

/// <summary>
/// 药管家 Agent 工具处理器——用药管理
/// </summary>
public static class MedicationAgentHandler
{
    public static readonly ToolDefinition ManageMedicationTool = new()
    {
        Function = new()
        {
            Name = "manage_medication", Description = "用药管理",
            Parameters = new { type = "object", properties = new { action = new { type = "string" }, name = new { type = "string" }, dosage = new { type = "string" } }, required = new[] { "action" } }
        }
    };

    public static List<ToolDefinition> Tools => [ManageMedicationTool, CommonAgentHandler.CheckArchiveTool];

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

    private static async Task<object> ExecuteManageMedication(AppDbContext db, Guid userId, JsonElement args)
    {
        var action = args.TryGetProperty("action", out var a) ? a.GetString()! : "query";
        return action switch
        {
            "create" => await CreateMedication(db, userId, args),
            "query" => await QueryMedications(db, userId),
            "confirm" => await ConfirmMedication(db, userId, args),
            _ => new { success = false, message = $"未知操作: {action}" }
        };
    }

    private static async Task<object> CreateMedication(AppDbContext db, Guid userId, JsonElement args)
    {
        var med = new Medication
        {
            Id = Guid.NewGuid(), UserId = userId,
            Name = args.TryGetProperty("name", out var n) ? n.GetString()! : "",
            Dosage = args.TryGetProperty("dosage", out var dg) ? dg.GetString() : null,
            Source = MedicationSource.AiEntry, IsActive = true,
        };
        db.Medications.Add(med);
        await db.SaveChangesAsync();
        return new { success = true, medication_id = med.Id, med.Name };
    }

    private static async Task<object> QueryMedications(AppDbContext db, Guid userId)
    {
        var meds = await db.Medications.Where(m => m.UserId == userId && m.IsActive)
            .Select(m => new { m.Id, m.Name, m.Dosage, m.TimeOfDay }).ToListAsync();
        return new { count = meds.Count, medications = meds };
    }

    private static async Task<object> ConfirmMedication(AppDbContext db, Guid userId, JsonElement args)
    {
        var medId = args.TryGetProperty("medication_id", out var mid) ? mid.GetGuid() : Guid.Empty;
        db.MedicationLogs.Add(new MedicationLog
        {
            Id = Guid.NewGuid(), MedicationId = medId, UserId = userId,
            Status = MedicationLogStatus.Taken, ScheduledTime = TimeOnly.FromDateTime(DateTime.Now), ConfirmedAt = DateTime.UtcNow,
        });
        await db.SaveChangesAsync();
        return new { success = true };
    }
}
