package priority

import (
	
	
	
	
	
	

	
)

const (
	// UserKey is a key to use with a Context that stores a user ID.
	UserKey key = 2

	// The max level value for a priority class
	maxLevel = 99.0
)

// ContextWithUser returns a context with the userID stored with the UserKey.
func ( context.Context,  string) context.Context {
	return context.WithValue(, UserKey, )
}

// UserFromContext returns the userID from the context, else "".
func ( context.Context) string {
	if  := .Value(UserKey);  != nil {
		if ,  := .(string);  {
			return 
		}
	}
	return ""
}

// UsageTracker tracks resource usage per user as execution usages for fair execution prioritization.
type UsageTracker interface {
	// RecordUsage calculates and records usage for the user.
	RecordUsage(userID string, usage int64)

	// GetUsage returns the total recorded usage for a user, returning the usage and true if the user exists in the tracker,
	// else 0 and false.
	GetUsage(userID string) (int64, bool)

	// GetLevel returns the priority level for a user based on their recent usage.
	GetLevel(userID string, priority Priority) int

	// Calibrate calibrates levels based on the distribution of usage across all users.
	Calibrate()
}

type usageTracker struct {
	clock              util.Clock
	newWindowFn        func() *usageWindow
	maxUsers           int
	expirationDuration time.Duration

	mu sync.RWMutex
	// Guarded by mu
	users map[string]*userEntry
	lru   *list.List
}

type userEntry struct {
	window     *usageWindow
	quantile   float64 // Negative value represents being uncalibrated
	lastActive time.Time
	lruElement *list.Element
}

// NewUsageTracker creates a new UsageTracker with the specified configuration. The UsageTracker will track up to the
// maxUsers, and track any recent usage within the usageWindow. If a user hasn't had activity in 2x the usageWindow,
// they're removed from the tracker.
func ( time.Duration,  int) UsageTracker {
	return &usageTracker{
		clock: util.WallClock,
		newWindowFn: func() *usageWindow {
			return newUsageWindow(30, , util.WallClock)
		},
		maxUsers:           ,
		expirationDuration: 2 * ,
		users:              make(map[string]*userEntry),
		lru:                list.New(),
	}
}

func ( *usageTracker) ( string,  int64) {
	.mu.Lock()
	defer .mu.Unlock()

	 := .users[]
	if  == nil {
		if len(.users) >= .maxUsers {
			.evictOldest()
		}
		 = &userEntry{
			window:   .newWindowFn(),
			quantile: -1,
		}
		.users[] = 
		.lruElement = .lru.PushFront()
	} else {
		.lru.MoveToFront(.lruElement)
	}

	.lastActive = .clock.Now()
	.window.RecordUsage()
}

func ( *usageTracker) ( string,  Priority) int {
	.mu.RLock()
	 := .users[]
	.mu.RUnlock()

	 := .levelRange()
	// Handle users that have no recorded usages
	if  == nil {
		return .upper
	}

	// Handle new entries with no recently recorded usages
	 := .window.TotalUsage()
	if  == 0 {
		return .upper
	}

	// Handle uncalibrated user
	if .quantile < 0 {
		return .upper
	}

	 := 1.0 - .quantile
	return .lower + int(maxLevel*)
}

func ( *usageTracker) ( string) (int64, bool) {
	.mu.RLock()
	defer .mu.RUnlock()

	 := .users[]
	if  == nil {
		return 0, false
	}
	return .window.TotalUsage(), true
}

// Calibrate has an O(n log n) time complexity, where n is the number of users.
func ( *usageTracker) () {
	.mu.Lock()
	defer .mu.Unlock()

	 := .clock.Now()
	 := .Add(-.expirationDuration)
	 := make([]int64, 0, len(.users))

	for ,  := range .users {
		.window.ExpireBuckets()
		if  := .window.TotalUsage();  > 0 {
			 = append(, )
		} else if .lastActive.Before() {
			delete(.users, )
			.lru.Remove(.lruElement)
		}
	}

	slices.Sort()

	// Update percentiles for all active users
	for ,  := range .users {
		if  := .window.TotalUsage();  > 0 {
			.quantile = .computeQuantile(, )
		} else {
			.quantile = -1
		}
	}
}

// computeQuantile returns the quantile for a usage, among the sortedUsages.
func ( *usageTracker) ( int64,  []int64) float64 {
	if len() == 0 {
		return 0
	}

	 := sort.Search(len(), func( int) bool {
		return [] >= 
	})

	return util.Round(float64() / float64(len()))
}

func ( *usageTracker) () {
	if  := .lru.Back();  != nil {
		 := .Value.(string)
		delete(.users, )
		.lru.Remove()
	}
}

type usageStat struct {
	totalUsage int64
	samples    uint32
}

type usageWindow struct {
	util.BucketedWindow[usageStat]
}

func newUsageWindow( int,  time.Duration,  util.Clock) *usageWindow {
	 := make([]usageStat, )

	return &usageWindow{
		util.BucketedWindow[usageStat]{
			Clock:       ,
			BucketCount: int64(),
			BucketNanos: ( / time.Duration()).Nanoseconds(),
			Buckets:     ,
			Summary:     usageStat{},
			AddFn: func( *usageStat,  *usageStat) {
				.totalUsage += .totalUsage
				.samples += .samples
			},
			RemoveFn: func( *usageStat,  *usageStat) {
				.totalUsage -= .totalUsage
				.samples -= .samples
			},
			ResetFn: func( *usageStat) {
				.totalUsage = 0
				.samples = 0
			},
		},
	}
}

func ( *usageWindow) ( int64) {
	 := .ExpireBuckets()
	.totalUsage += 
	.samples++
	.Summary.totalUsage += 
	.Summary.samples++
}

func ( *usageWindow) () int64 {
	return .Summary.totalUsage
}

func ( *usageWindow) () uint32 {
	return .Summary.samples
}