package model

import (
	"fmt"
	"time"
)

// FreeBuffActivationsPerPeriod is the legacy shared limit. Kept for backward compatibility.
const FreeBuffActivationsPerPeriod = 2

// BuffFreeChargesPerType defines the per-buff free charge limits per 24h window.
var BuffFreeChargesPerType = map[BuffType]int{
	BuffRush:         3,
	BuffRage:         2,
	BuffShield:       2,
	BuffLuck:         1,
	BuffResurrection: 1,
	BuffHeal:         3,
	BuffPowerPotion:  1,
	BuffWarCry:       2,
}

// ApplyBuffQuotaRollover refills free buff charges when the 24h window has passed.
// Returns true if the hero was mutated (caller may persist).
// Deprecated: kept for backward compat with the shared counter. New code should
// use GetBuffCharges / ConsumeBuffCharge which handle rollover inline.
func (h *Hero) ApplyBuffQuotaRollover(now time.Time) bool {
	if h.SubscriptionActive {
		return false
	}
	if h.BuffQuotaPeriodEnd == nil {
		return false
	}
	changed := false
	for now.After(*h.BuffQuotaPeriodEnd) {
		h.BuffFreeChargesRemaining = FreeBuffActivationsPerPeriod
		next := h.BuffQuotaPeriodEnd.Add(24 * time.Hour)
		h.BuffQuotaPeriodEnd = &next
		changed = true
	}
	return changed
}

// GetBuffCharges returns the current charge state for a specific buff type,
// rolling over the 24h window if expired.
func (h *Hero) GetBuffCharges(bt BuffType, now time.Time) BuffChargeState {
	if h.BuffCharges == nil {
		h.BuffCharges = make(map[string]BuffChargeState)
	}

	maxCharges := BuffFreeChargesPerType[bt]
	if maxCharges == 0 {
		maxCharges = FreeBuffActivationsPerPeriod // fallback
	}

	state, exists := h.BuffCharges[string(bt)]
	if !exists {
		// First access for this buff type — initialize with full charges.
		pe := now.Add(24 * time.Hour)
		state = BuffChargeState{
			Remaining: maxCharges,
			PeriodEnd: &pe,
		}
		h.BuffCharges[string(bt)] = state
		return state
	}

	// Roll over if the period has expired.
	if state.PeriodEnd != nil && now.After(*state.PeriodEnd) {
		for state.PeriodEnd != nil && now.After(*state.PeriodEnd) {
			next := state.PeriodEnd.Add(24 * time.Hour)
			state.PeriodEnd = &next
		}
		state.Remaining = maxCharges
		h.BuffCharges[string(bt)] = state
	}

	return state
}

// ConsumeBuffCharge decrements one free charge for the specific buff type.
// Returns an error if no charges remain.
func (h *Hero) ConsumeBuffCharge(bt BuffType, now time.Time) error {
	state := h.GetBuffCharges(bt, now)

	if state.Remaining <= 0 {
		periodStr := "unknown"
		if state.PeriodEnd != nil {
			periodStr = state.PeriodEnd.Format(time.RFC3339)
		}
		return fmt.Errorf(
			"no free %s charges left; next refresh at %s",
			string(bt), periodStr,
		)
	}

	state.Remaining--
	h.BuffCharges[string(bt)] = state

	// Keep legacy counter roughly in sync.
	h.BuffFreeChargesRemaining--
	if h.BuffFreeChargesRemaining < 0 {
		h.BuffFreeChargesRemaining = 0
	}

	return nil
}

// RefundBuffCharge increments one charge back for the specific buff type.
func (h *Hero) RefundBuffCharge(bt BuffType) {
	if h.BuffCharges == nil {
		return
	}
	state, exists := h.BuffCharges[string(bt)]
	if !exists {
		return
	}
	maxCharges := BuffFreeChargesPerType[bt]
	if maxCharges == 0 {
		maxCharges = FreeBuffActivationsPerPeriod
	}
	state.Remaining++
	if state.Remaining > maxCharges {
		state.Remaining = maxCharges
	}
	h.BuffCharges[string(bt)] = state

	// Keep legacy counter roughly in sync.
	h.BuffFreeChargesRemaining++
}

// ResetBuffCharges resets charges to max. If bt is nil, resets ALL buff types.
// If bt is non-nil, resets only that buff type.
func (h *Hero) ResetBuffCharges(bt *BuffType, now time.Time) {
	if h.BuffCharges == nil {
		h.BuffCharges = make(map[string]BuffChargeState)
	}

	pe := now.Add(24 * time.Hour)

	if bt != nil {
		maxCharges := BuffFreeChargesPerType[*bt]
		if maxCharges == 0 {
			maxCharges = FreeBuffActivationsPerPeriod
		}
		h.BuffCharges[string(*bt)] = BuffChargeState{
			Remaining: maxCharges,
			PeriodEnd: &pe,
		}
		return
	}

	// Reset ALL buff types.
	for buffType, maxCharges := range BuffFreeChargesPerType {
		h.BuffCharges[string(buffType)] = BuffChargeState{
			Remaining: maxCharges,
			PeriodEnd: &pe,
		}
	}

	// Also reset legacy counter.
	h.BuffFreeChargesRemaining = FreeBuffActivationsPerPeriod
	h.BuffQuotaPeriodEnd = &pe
}

// EnsureBuffChargesPopulated initializes BuffCharges for all buff types if the map
// is empty. Returns true if the map was freshly populated (caller should persist).
func (h *Hero) EnsureBuffChargesPopulated(now time.Time) bool {
	if h.BuffCharges == nil {
		h.BuffCharges = make(map[string]BuffChargeState)
	}
	if len(h.BuffCharges) == 0 {
		pe := now.Add(24 * time.Hour)
		if h.BuffQuotaPeriodEnd != nil {
			pe = *h.BuffQuotaPeriodEnd
		}
		for bt, maxCharges := range BuffFreeChargesPerType {
			h.BuffCharges[string(bt)] = BuffChargeState{
				Remaining: maxCharges,
				PeriodEnd: &pe,
			}
		}
		return true
	}
	return false
}
