using System.Security.Cryptography;
using System.Text;
using Kbx.Shared.Experiments.Generated;
namespace Kbx.Shared.Experiments;
public static class KbxExperimentAssignmentPolicy
{
    public static bool IsEnrolled(Guid tenantId,Guid userId,string experimentId,int rolloutPercent) =>
        rolloutPercent>0 && Bucket(tenantId,userId,experimentId,"enroll") < rolloutPercent*100;
    public static string ChooseVariant(Guid tenantId,Guid userId,KbxExperimentDefinition definition)
    {
        var point=Bucket(tenantId,userId,definition.Id,"variant")%100,cumulative=0;
        foreach(var item in definition.Variants){cumulative+=item.Weight;if(point<cumulative)return item.Key;}
        return "control";
    }
    private static int Bucket(Guid tenantId,Guid userId,string experimentId,string purpose)
    {
        var bytes=SHA256.HashData(Encoding.UTF8.GetBytes($"{tenantId:N}|{userId:N}|{experimentId}|{purpose}|kbx-v1"));
        return (int)(BitConverter.ToUInt32(bytes,0)%10000);
    }
}
