using System.Text.Json.Nodes;

namespace Nalu.Web.PostProcessors;

/// Reads the handoff JSON and sets SuggestionKeyOverride based on wants_human + urgency.
public class SelectHandoffSuggestion : IPostProcessor
{
    public string Name => "select_handoff_suggestion";

    public ProcessorResult Process(string? value)
    {
        if (string.IsNullOrWhiteSpace(value)) return ProcessorResult.Ok(value);

        try
        {
            var obj = JsonNode.Parse(value)?.AsObject();
            if (obj is null) return ProcessorResult.Ok(value);

            var wantsHuman = obj["wants_human"]?.GetValue<bool>() ?? false;
            if (!wantsHuman)
                return ProcessorResult.WithOverride(value, "when_not_handoff");

            var urgency = obj["urgency"]?.GetValue<string>() ?? "medium";
            var key = urgency switch
            {
                "high"   => "when_handoff_high",
                "low"    => "when_handoff_low",
                _        => "when_handoff_medium"
            };

            return ProcessorResult.WithOverride(value, key);
        }
        catch
        {
            return ProcessorResult.Ok(value);
        }
    }
}
