aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/api_colors.go
blob: 882a0960711fd5f28efd7eb191d996dcbb6809cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package admin

import (
	"net/http"
	"os"
	"sort"
	"strings"

	"gopkg.in/yaml.v3"

	"thehouseoficarus/internal/color"
	"thehouseoficarus/internal/config"
)

// colorCategory describes one editable color category: its config key, a
// human-friendly label, and a UI grouping.
type colorCategory struct {
	Name  string `json:"name"`
	Label string `json:"label"`
	Group string `json:"group"`
}

// colorSegment is one piece of preview text tagged with the category whose
// color spec should paint it. A nil/empty category means plain (uncolored).
type colorSegment struct {
	T string `json:"t"` // text
	C string `json:"c"` // category name, "" = plain
}

// colorLine groups segments into one rendered line.
type colorLine struct {
	Segments []colorSegment `json:"segments"`
}

// colorSection is a titled block of example output.
type colorSection struct {
	Title string      `json:"title"`
	Lines []colorLine `json:"lines"`
}

// colorCategories is the curated, grouped, ordered master list mirroring the
// keys produced by config.DefaultColors(). Editing here is the single source
// of truth for the admin color themer's left-side list.
var colorCategories = []colorCategory{
	// Room / look
	{Name: "room_name", Label: "Room Name", Group: "Room"},
	{Name: "room_number", Label: "Room Number", Group: "Room"},
	{Name: "room_desc", Label: "Room Description", Group: "Room"},
	{Name: "exit_direction", Label: "Exit Direction", Group: "Room"},
	{Name: "exit_name", Label: "Exit Name", Group: "Room"},
	{Name: "mob", Label: "Mob", Group: "Room"},
	{Name: "protected_mob", Label: "Protected Mob", Group: "Room"},
	{Name: "player_name", Label: "Player Name", Group: "Room"},
	{Name: "item", Label: "Item", Group: "Room"},
	{Name: "dim", Label: "Dim / Brackets", Group: "Room"},

	// Movement
	{Name: "direction", Label: "Move Direction", Group: "Movement"},

	// Combat
	{Name: "damage_dealt", Label: "Damage Dealt", Group: "Combat"},
	{Name: "damage_taken", Label: "Damage Taken", Group: "Combat"},
	{Name: "miss", Label: "Miss", Group: "Combat"},
	{Name: "death", Label: "Death", Group: "Combat"},
	{Name: "victory", Label: "Victory", Group: "Combat"},
	{Name: "warning", Label: "Warning", Group: "Combat"},
	{Name: "error", Label: "Error", Group: "Combat"},
	{Name: "science_mod", Label: "Science Mod", Group: "Combat"},

	// XP / level
	{Name: "xp", Label: "XP Drop", Group: "XP / Level"},
	{Name: "level_up", Label: "Level Up", Group: "XP / Level"},

	// Pickups / economy
	{Name: "currency_pickup", Label: "Currency Pickup", Group: "Pickups / Economy"},

	// Chat / dialog
	{Name: "say", Label: "Say", Group: "Chat / Dialog"},
	{Name: "global", Label: "Global", Group: "Chat / Dialog"},
	{Name: "broadcast", Label: "Broadcast", Group: "Chat / Dialog"},
	{Name: "dialog", Label: "Dialog", Group: "Chat / Dialog"},
	{Name: "dialog_options", Label: "Dialog Options", Group: "Chat / Dialog"},

	// Drops / consume / fire
	{Name: "drop_message", Label: "Drop Message", Group: "Drops / Consume / Fire"},
	{Name: "eat_food", Label: "Eat Food", Group: "Drops / Consume / Fire"},
	{Name: "fire", Label: "Fire", Group: "Drops / Consume / Fire"},

	// Tick / status
	{Name: "visual_tick", Label: "Visual Tick", Group: "Tick / Status"},
	{Name: "visual_first_tick", Label: "Visual First Tick", Group: "Tick / Status"},

	// Tech / farm
	{Name: "battery", Label: "Battery", Group: "Tech / Farm"},
	{Name: "tech_depleted", Label: "Tech Depleted", Group: "Tech / Farm"},
	{Name: "farm_grow", Label: "Farm Grow", Group: "Tech / Farm"},
	{Name: "farm_disease", Label: "Farm Disease", Group: "Tech / Farm"},

	// Assassin / map / safespot
	{Name: "assassin_task", Label: "Assassin Task", Group: "Assassin / Map / Safespot"},
	{Name: "map_at", Label: "Map At (you)", Group: "Assassin / Map / Safespot"},
	{Name: "map_blocked", Label: "Map Blocked", Group: "Assassin / Map / Safespot"},
	{Name: "map_agility", Label: "Map Agility", Group: "Assassin / Map / Safespot"},
	{Name: "safespot_alert", Label: "Safespot Alert", Group: "Assassin / Map / Safespot"},

	// System
	{Name: "sequence", Label: "Sequence (trigger)", Group: "System"},
}

// knownColor returns true if name is one of the editable categories.
func knownColor(name string) bool {
	for _, c := range colorCategories {
		if c.Name == name {
			return true
		}
	}
	return false
}

// seg is a small constructor helper for the inline preview builder.
func seg(t, cat string) colorSegment {
	return colorSegment{T: t, C: cat}
}

// ln builds a line from a sequence of segments.
func ln(segs ...colorSegment) colorLine {
	return colorLine{Segments: segs}
}

// txt builds a plain (uncolored) line.
func txt(s string) colorLine {
	return colorLine{Segments: []colorSegment{{T: s}}}
}

// buildPreview constructs the example output covering every color category.
// Text patterns match real in-game output (room looks, combat, pickups, chat,
// etc.) so admins see exactly what each color key paints.
func buildPreview() []colorSection {
	var sections []colorSection

	// --- A full room "look" ----------------------------------------------
	sections = append(sections, colorSection{
		Title: "Room Look",
		Lines: []colorLine{
			ln(seg("Test Room", "room_name"),
				seg(" (intro, #2001)", "room_number")),
			txt(""),
			// Description + minimap, right-aligned at column 80.
			// Text padded to 71 chars visible + "  " + 7-char map = 80.
			ln(seg("Golstaff, you have entered the door to the north. You are now by         ", "room_desc"),
				seg("╔═════╗", "dim")),
			ln(seg("yourself, standing in a dark room. The pungent stench of mildew          ", "room_desc"),
				seg("║", "dim"), seg("     ", ""), seg("║", "dim")),
			ln(seg("emanates from the wet dungeon walls.                                     ", "room_desc"),
				seg("║", "dim"), seg("     ", ""), seg("║", "dim")),
			ln(seg("                                                                         ", ""),
				seg("║", "dim"), seg("■", ""), seg("-", ""), seg("@", "map_at"), seg("-", ""), seg("■", ""), seg("║", "dim")),
			ln(seg("Crassius Rex", "protected_mob"), seg(" watches the gate.                                           ", ""),
				seg("║", "dim"), seg("  ", ""), seg("│", "map_agility"), seg("  ", ""), seg("║", "dim")),
			ln(seg("A man ", "mob"), seg("(level 5)", "victory"), seg(" scribbles something in a small notebook.                 ", ""),
				seg("║", "dim"), seg("  ", ""), seg("■", ""), seg("  ", ""), seg("║", "dim")),
			ln(seg("                                                                         ", ""),
				seg("╚═════╝", "dim")),
			txt(""),
			ln(seg("Dalinar", "player_name"), seg(" (level 123)", "error"), seg(" is here.", "")),
			txt(""),
			txt("On the ground:"),
			ln(seg("  bones            ", "item"), seg("(reserved for Dalinar 65t)", "dim")),
			ln(seg("  bronze axe", "item")),
			ln(seg("  bucket of water", "item")),
			ln(seg("  10 x ", ""), seg("chips       ", "item"), seg("(reserved for Dalinar 65t)", "dim")),
			ln(seg("  pot of flour", "item")),
			txt(""),
			txt("Exits:"),
			ln(seg("  ", ""), seg("south", "exit_direction"), seg(" - ", ""), seg("Test Room", "exit_name")),
			ln(seg("  ", ""), seg("east", "exit_direction"), seg("  - ", ""), seg("Processing Station", "exit_name")),
			ln(seg("  ", ""), seg("west", "exit_direction"), seg("  - ", ""), seg("Inside Transport Shuttle", "exit_name")),
			txt(""),
			ln(seg("> s", "")),
			ln(seg("You walk ", ""), seg("south", "direction"), seg(".", "")),
		},
	})

	// --- Combat rounds (matches real output) ------------------------------
	sections = append(sections, colorSection{
		Title: "Combat (two encounters)",
		Lines: []colorLine{
			txt(""),
			ln(seg("> attack man", "")),
			txt(""),
			ln(seg("You attack ", ""), seg("the man", "mob"), seg("! Style: accurate (+3 atk)", "")),
			ln(seg("You hit ", ""), seg("the man", "mob"), seg(" for  ", ""),
				seg("\U0001FB38 1 \U0001FB34 damage.   ", "damage_dealt"),
				seg("[█████████░]", "victory"), seg(" [ 6/7]", ""),
				seg(" (+18xp acc, +6xp hp)", "xp")),
			ln(seg("The man misses you.", "miss")),
			ln(seg("You hit ", ""), seg("the man", "mob"), seg(" for  ", ""),
				seg("\U0001FB38 6 \U0001FB34 damage.   ", "damage_dealt"),
				seg("[░░░░░░░░░░]", "error"), seg(" [ 0/7]", ""),
				seg(" (+18xp acc, +6xp hp)", "xp")),
			ln(seg("You have defeated ", ""), seg("the man", "mob"), seg("!", "victory")),
			ln(seg("*** You are now level 12 accuracy! ***", "level_up")),
			txt(""),
			ln(seg("The man", "mob"), seg(" hits you for ", ""),
				seg("\U0001FB38 5 \U0001FB34 damage.   ", "damage_taken"),
				seg("[██████░░░░]", "warning"), seg(" [22/40]", "")),
			ln(seg("Oh dear, you are dead!", "death")),
			txt(""),
			txt(""),

		},
	})

	// --- Chat / dialog ----------------------------------------------------
	sections = append(sections, colorSection{
		Title: "Chat & Dialog",
		Lines: []colorLine{
			ln(seg("You say: ", ""), seg("hello there", "say")),
			ln(seg("[Global] ", "global"), seg("Dalinar: ", "player_name"), seg("I just won big in baccarat!", "global")),
			ln(seg("Dalinar", "player_name"), seg(" has slain ", ""),
				seg("a scout", "broadcast"), seg(" (level 5)!", "broadcast")),
			txt(""),
			ln(seg("Guard says: ", ""), seg("\u201cHalt. State your business.\u201d", "dialog")),
			ln(seg("  1. ", "dialog_options"), seg("I'm looking for work.", "dialog")),
			ln(seg("  2. ", "dialog_options"), seg("Just passing through.", "dialog")),
			ln(seg("[enter to continue]", "dialog_options")),
		},
	})

	// --- Drops / consume / fire ------------------------------------------
	sections = append(sections, colorSection{
		Title: "Drops, Consume & Fire",
		Lines: []colorLine{
			txt(""),
			ln(seg("The man drops: ", "drop_message"), seg("bones", "item")),
			ln(seg("The man drops: ", "drop_message"),
				seg("10", ""), seg(" x ", ""), seg("chips", "item")),
			ln(seg("You eat the bread. It restores some energy.", "eat_food")),
			ln(seg("You manage to get a fire going!", "fire")),
		},
	})

	// --- Tick / tech / farm ----------------------------------------------
	sections = append(sections, colorSection{
		Title: "Tick, Tech & Farm",
		Lines: []colorLine{
			ln(seg("tick 1", "visual_first_tick")),
			ln(seg("tick 2", "visual_tick")),
			ln(seg("tick 3", "visual_tick")),
			ln(seg("Your battery is depleted! All tech has been disabled.", "tech_depleted")),
			ln(seg("You connect to the charging station. Your battery is fully recharged.", "battery")),
			ln(seg("Your marigold has grown to stage 2/4.", "farm_grow")),
			ln(seg("Your marigold has become diseased!", "farm_disease")),
		},
	})

	// --- Assassin / safespot ---------------------------------------------
	sections = append(sections, colorSection{
		Title: "Assassin & Safespot",
		Lines: []colorLine{
			txt(""),
			ln(seg("Your target: 15 slugs. Get to work.", "assassin_task")),
			ln(seg("*** Assassin task complete! ***", "assassin_task"),
				seg(" (+50xp asm)", "xp")),
			ln(seg("  Assassin task: 12 of 15 slugs remaining.", "assassin_task")),
			ln(seg("Your safespot has been compromised!", "safespot_alert")),
			txt(""),
		},
	})

	return sections
}

func (s *AdminServer) handleColors(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		s.getColors(w, r)
	case http.MethodPost:
		s.saveColors(w, r)
	default:
		writeJSONError(w, "method not allowed", http.StatusMethodNotAllowed)
	}
}

func (s *AdminServer) getColors(w http.ResponseWriter, _ *http.Request) {
	live := make(map[string]string, len(colorCategories))
	for _, c := range colorCategories {
		if v, ok := s.cfg.DefaultColors[c.Name]; ok {
			live[c.Name] = v
		} else {
			live[c.Name] = ""
		}
	}
	defaults := config.DefaultColors()
	def := make(map[string]string, len(colorCategories))
	for _, c := range colorCategories {
		if v, ok := defaults[c.Name]; ok {
			def[c.Name] = v
		} else {
			def[c.Name] = ""
		}
	}
	writeJSON(w, map[string]any{
		"colors":         live,
		"default_colors": def,
		"categories":     colorCategories,
		"preview":        buildPreview(),
	})
}

func (s *AdminServer) saveColors(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Colors map[string]string `json:"colors"`
	}
	if err := readJSON(r, &body); err != nil {
		writeJSONError(w, "invalid request body", http.StatusBadRequest)
		return
	}

	// Validate every supplied key/spec against the known config grammar.
	for name, val := range body.Colors {
		if !knownColor(name) {
			writeJSONError(w, "unknown color category: "+name, http.StatusBadRequest)
			return
		}
		// "off" or empty is explicitly allowed (NoColor). Anything else must
		// parse to a non-empty ColorSpec whose only unknown we tolerate is none.
		spec := color.Parse(val)
		if strings.TrimSpace(val) != "" && val != "off" && spec.Empty() {
			writeJSONError(w, "invalid color spec for "+name+": "+val, http.StatusBadRequest)
			return
		}
	}

	cur := s.cfg.DefaultColors
	next := make(map[string]string, len(cur)+len(body.Colors))
	for k, v := range cur {
		next[k] = v
	}
	for k, v := range body.Colors {
		next[k] = v
	}
	s.cfg.DefaultColors = next

	if err := s.writeConfigFile(); err != nil {
		writeJSONError(w, "save failed: "+err.Error(), http.StatusInternalServerError)
		return
	}
	writeJSON(w, map[string]any{"ok": true})
}

func (s *AdminServer) handleColorsReset(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		writeJSONError(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	s.cfg.DefaultColors = config.DefaultColors()
	if err := s.writeConfigFile(); err != nil {
		writeJSONError(w, "save failed: "+err.Error(), http.StatusInternalServerError)
		return
	}
	// Return the freshly reset live values for the client to reload.
	live := make(map[string]string, len(colorCategories))
	for _, c := range colorCategories {
		if v, ok := s.cfg.DefaultColors[c.Name]; ok {
			live[c.Name] = v
		} else {
			live[c.Name] = ""
		}
	}
	writeJSON(w, map[string]any{"ok": true, "colors": live})
}

// writeConfigFile marshals the entire live *config.Config back to config.yaml,
// overwriting whatever was on disk. A full re-marshal drops the file's manual
// comments but produces a valid, reloadable file with the edited colors.
func (s *AdminServer) writeConfigFile() error {
	_ = backupFile(s.configPath) // best-effort snapshot for safety
	out, err := yaml.Marshal(s.cfg)
	if err != nil {
		return err
	}
	return os.WriteFile(s.configPath, out, 0644)
}

// sortedKeys is a small helper retained in case future code wants a stable
// iteration order over the category names.
func sortedKeys(m map[string]string) []string {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys
}