package gen

import (
	"fmt"
	"math/rand/v2"

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

var mainNames = []string{"The Fall of the %s", "Ashes Under the %s", "Bane of the %s"}
var mainTemplates = []string{"hunt", "relic", "siege"}
var sideNames = []string{"A Favor for the Hamlet", "Lost and Found", "Bounty Posted", "The Quiet Errand"}

func kindsFor(sys Systems) []string {
	if sys.Factions {
		return []string{"reach", "defeat"}
	}
	return []string{"reach"}
}

type questBuilder struct {
	r        *rand.Rand
	sys      Systems
	factions map[string]model.Faction
	names    []string
	keys     []model.Item
	n        int
}

func (q *questBuilder) step(id string, kind string, poi model.POI) model.MissionStep {
	f := q.factions[poi.Faction]
	s := model.MissionStep{ID: id, Kind: kind, POI: poi.ID, Slots: model.Slots{POIKind: poi.Kind, Faction: f.ID}}
	switch kind {
	case "defeat":
		s.Text = fmt.Sprintf("Drive the %s out of %s", f.Name, poi.Name)
	case "retrieve":
		q.n++
		it := makeKeyItem(q.n, q.names[q.n%len(q.names)])
		q.keys = append(q.keys, it)
		s.Slots.Item = it.ID
		s.Text = fmt.Sprintf("Recover the %s from %s", it.Name, poi.Name)
	default:
		s.Text = fmt.Sprintf("Travel to %s", poi.Name)
	}
	return s
}

func (q *questBuilder) main(pois []model.POI, boss string) model.Mission {
	last := pois[len(pois)-1]
	steps := make([]model.MissionStep, 0, len(pois))
	for i, p := range pois[:len(pois)-1] {
		kind := "reach"
		if i > 0 {
			kind = "retrieve"
		}
		steps = append(steps, q.step(fmt.Sprintf("m%d", i+1), kind, p))
	}
	bs := q.step(fmt.Sprintf("m%d", len(pois)), "boss", last)
	bs.Text = fmt.Sprintf("Slay %s in %s", boss, last.Name)
	steps = append(steps, bs)
	ti := q.r.IntN(len(mainTemplates))
	return model.Mission{
		Template: mainTemplates[ti],
		Name:     fmt.Sprintf(mainNames[ti], q.factions[last.Faction].Name),
		Steps:    steps,
	}
}

func (q *questBuilder) side(i int, pois []model.POI) model.Mission {
	kinds := kindsFor(q.sys)
	steps := make([]model.MissionStep, len(pois))
	for j, p := range pois {
		steps[j] = q.step(fmt.Sprintf("s%d_%d", i+1, j+1), rng.Pick(q.r, kinds), p)
	}
	return model.Mission{Template: "side", Name: sideNames[i%len(sideNames)], Steps: steps}
}

var keyNames = []string{"Sunken Crown", "Bone Key", "Moonstone Sigil", "Ember Seal", "Gilded Chalice", "Black Lantern", "Serpent Idol", "Iron Reliquary", "Glass Eye", "Thorn Circlet"}

func makeKeyItem(n int, name string) model.Item {
	return model.Item{ID: fmt.Sprintf("key%d", n), Name: name, Rarity: "rare", Key: true}
}

func rollKeyNames(r *rand.Rand) []string {
	return rng.Shuffled(r, keyNames)
}
