package server

import (
	"errors"
	"hash/fnv"
	"slices"

	"tinyadventure/internal/model"
	"tinyadventure/internal/rng"
	"tinyadventure/internal/sim"
)

const (
	SupplyPrice   = 25
	startSupplies = 2
	stockSize     = 5
)

type site struct {
	id, name string
	x, y     int
	level    int
}

func (g *game) shops() []site {
	var out []site
	for _, s := range g.state.Map.Spawns {
		out = append(out, site{s.ID, s.Kind, s.X, s.Y, 1})
	}
	for _, p := range g.state.Map.POIs {
		if p.Cleared {
			out = append(out, site{p.ID, p.Name, p.X, p.Y, p.Level})
		}
	}
	return out
}

func (g *game) shopAt(x, y int) *site {
	for _, s := range g.shops() {
		if s.x == x && s.y == y {
			return &s
		}
	}
	return nil
}

func (g *game) stockAt(s *site) []model.Item {
	if g.stock == nil {
		g.stock = map[string][]model.Item{}
	}
	if items, ok := g.stock[s.id]; ok {
		return items
	}
	h := fnv.New64a()
	h.Write([]byte(s.id))
	r := rng.New(g.state.Seed ^ model.Seed(h.Sum64()))
	items := make([]model.Item, stockSize)
	for i := range items {
		items[i] = sim.RollItem(r, s.level+1)
	}
	g.stock[s.id] = items
	return items
}

func (g *game) shopView() *model.Shop {
	s := g.shopAt(g.state.Party.X, g.state.Party.Y)
	if s == nil {
		return nil
	}
	return &model.Shop{ID: s.id, Name: s.name, Stock: slices.Clone(g.stockAt(s)), SupplyPrice: SupplyPrice}
}

func (g *game) atShop() (*site, error) {
	s := g.shopAt(g.state.Party.X, g.state.Party.Y)
	if s == nil {
		return nil, errors.New("nobody trades here: find a spawn or a place you have cleared")
	}
	g.begin()
	return s, nil
}

func (g *game) buy(id string) error {
	s, err := g.atShop()
	if err != nil {
		return err
	}
	p := &g.state.Party
	if id == "supplies" {
		if p.Gold < SupplyPrice {
			return errors.New("not enough gold for camp supplies")
		}
		p.Gold -= SupplyPrice
		p.Supplies++
		return nil
	}
	stock := g.stockAt(s)
	i := slices.IndexFunc(stock, func(it model.Item) bool { return it.ID == id })
	if i < 0 {
		return errors.New("item is not for sale here")
	}
	if p.Gold < stock[i].Value {
		return errors.New("not enough gold for " + stock[i].Name)
	}
	p.Gold -= stock[i].Value
	p.Inventory = append(p.Inventory, stock[i])
	g.stock[s.id] = slices.Delete(stock, i, i+1)
	return nil
}

func (g *game) sell(id string) error {
	if _, err := g.atShop(); err != nil {
		return err
	}
	p := &g.state.Party
	i := slices.IndexFunc(p.Inventory, func(it model.Item) bool { return it.ID == id })
	if i < 0 {
		return errors.New("item not in inventory")
	}
	p.Gold += SellPrice(p.Inventory[i])
	p.Inventory = slices.Delete(p.Inventory, i, i+1)
	return nil
}

func SellPrice(it model.Item) int { return max(1, it.Value/2) }

func (g *game) pickup(x, y int) {
	if p := g.poiAt(x, y); (p != nil && !p.Cleared) || g.bandAt(x, y) != nil {
		return
	}
	for i := range g.state.Map.Loot {
		l := &g.state.Map.Loot[i]
		if l.X == x && l.Y == y && !l.Collected {
			if l.Trap {
				g.spring()
			}
			l.Collected = true
			g.take(l.Item)
			g.state.Found = append(g.state.Found, l.Item)
		}
	}
}
