using ClaudeDo.Data.Models;

namespace ClaudeDo.Worker.Runner;

/// <summary>Single source of truth for the permission mode actually started, shared by
/// <see cref="ClaudeArgsBuilder"/>'s real dispatch and <see cref="EffectiveRunConfigResolver"/>'s
/// read-only report — so the two can never drift apart.</summary>
public static class PermissionModeResolver
{
    public static string Resolve(string? model, string? requestedPermissionMode)
    {
        var mode = string.IsNullOrWhiteSpace(requestedPermissionMode)
            || requestedPermissionMode.Equals("bypassPermissions", StringComparison.OrdinalIgnoreCase)
            ? "auto"
            : requestedPermissionMode;

        // claude-cli 2.1.220 silently downgrades "--permission-mode auto" to the interactive
        // "default" mode when --model resolves to a haiku model (confirmed by capturing the
        // stream-json `init` event for both models side by side; acceptEdits/bypassPermissions
        // pass through unaffected). An unattended run then blocks forever on an edit confirmation
        // that never arrives, so substitute the closest unattended-safe mode instead.
        if (string.Equals(mode, "auto", StringComparison.OrdinalIgnoreCase)
            && ModelRegistry.TryNormalizeAlias(model) == "haiku")
            return "acceptEdits";

        return mode;
    }
}
