package server

import (
	"net"
	"net/http"
	"strings"
	"sync"
	"time"
)

type rate struct{ per, burst float64 }

var rates = map[string]rate{
	"read":     {20, 80},
	"act":      {8, 60},
	"new":      {1.0 / 30, 10},
	"feedback": {1.0 / 600, 3},
}

type bucket struct {
	tokens float64
	last   time.Time
}

type limiter struct {
	mu      sync.Mutex
	buckets map[string]*bucket
}

func (l *limiter) allow(ip, kind string) bool {
	if ip == "" {
		return true
	}
	r := rates[kind]
	now := time.Now()
	l.mu.Lock()
	defer l.mu.Unlock()
	if l.buckets == nil || len(l.buckets) > 20000 {
		l.buckets = map[string]*bucket{}
	}
	b := l.buckets[kind+" "+ip]
	if b == nil {
		b = &bucket{tokens: r.burst, last: now}
		l.buckets[kind+" "+ip] = b
	}
	b.tokens = min(r.burst, b.tokens+now.Sub(b.last).Seconds()*r.per)
	b.last = now
	if b.tokens < 1 {
		return false
	}
	b.tokens--
	return true
}

func clientIP(r *http.Request) string {
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		host = r.RemoteAddr
	}
	if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
		return host
	}
	xff := r.Header.Get("X-Forwarded-For")
	if xff == "" {
		return ""
	}
	parts := strings.Split(xff, ",")
	return strings.TrimSpace(parts[len(parts)-1])
}
