1use std::env;
2use std::path::{Path, PathBuf};
3
4use manabot::agent::AgentKind;
5use manabrew_agent_interface::protocol::GameFormat;
6use manabrew_protocol::deck_dto::{Deck, DeckCard, DeckCardIdentity};
7use serde::Deserialize;
8use tracing::warn;
9
10use crate::engine_backend::EngineBackendKind;
11
12#[derive(Debug, Clone)]
13pub struct Config {
14 pub backend: EngineBackendKind,
15 pub relay_url: String,
16 pub username: String,
17 pub password: String,
18 pub room_id: Option<String>,
19 pub room_name: String,
20 pub max_players: u8,
21 pub max_games: usize,
22 pub state_delta: bool,
25 pub format: GameFormat,
26 pub auto_start: bool,
27 pub engine_enabled: bool,
28 pub host_plays: bool,
29 pub official_key: Option<String>,
30 pub room_password: Option<String>,
31 pub bot_enabled: bool,
32 pub bot_username: String,
33 pub forge_ai: bool,
34 pub bot_agent: AgentKind,
38 pub bot_local_answers: bool,
41 pub reconnect_timeout_s: Option<u32>,
42 pub table_style: Option<String>,
43 pub host_deck: DeckSelection,
44 pub bot_deck: DeckSelection,
45}
46
47#[derive(Debug, Clone)]
48pub struct DeckSelection {
49 pub name: String,
50 pub deck: Deck,
51 pub commander_name: Option<String>,
52}
53
54#[derive(Debug, Deserialize)]
55struct PresetDeckFile {
56 label: String,
57 #[serde(default)]
58 commander: Option<String>,
59 cards: Vec<PresetDeckCard>,
60}
61
62#[derive(Debug, Deserialize)]
63struct PresetDeckCard {
64 name: String,
65 count: usize,
66 #[serde(default)]
67 set: String,
68}
69
70impl Config {
71 pub fn from_env() -> Self {
72 let username = format!("self-hosted-node-{}", uuid::Uuid::new_v4());
73 let bot_username = env_first("SELF_HOSTED_NODE_BOT_USERNAME", "FORGE_ROOM_BOT_USERNAME")
74 .unwrap_or_else(|| "Bot".into());
75 let host_deck_id = env_first("SELF_HOSTED_NODE_DECK", "FORGE_ROOM_NODE_DECK")
76 .unwrap_or_else(|| "ashling_limitless_commander".into());
77 let bot_deck_id = env_first("SELF_HOSTED_NODE_BOT_DECK", "FORGE_ROOM_BOT_DECK")
78 .unwrap_or_else(|| "neheb_minotaur_commander".into());
79 let host_commander = env_first("SELF_HOSTED_NODE_COMMANDER", "FORGE_ROOM_NODE_COMMANDER")
80 .filter(|value| !value.is_empty())
81 .or_else(|| infer_commander_name(&host_deck_id).map(str::to_string));
82 let bot_commander = env_first("SELF_HOSTED_NODE_BOT_COMMANDER", "FORGE_ROOM_BOT_COMMANDER")
83 .filter(|value| !value.is_empty())
84 .or_else(|| infer_commander_name(&bot_deck_id).map(str::to_string));
85
86 let room_id = env_first("SELF_HOSTED_NODE_ROOM_ID", "FORGE_ROOM_ID")
87 .filter(|value| !value.is_empty());
88 let engine_enabled_default = room_id.is_none();
89
90 let format = env_first("SELF_HOSTED_NODE_FORMAT", "FORGE_ROOM_FORMAT")
91 .and_then(|value| parse_format(&value))
92 .unwrap_or(GameFormat::Any);
93 Self {
94 backend: EngineBackendKind::from_env(),
95 relay_url: env_first("SELF_HOSTED_NODE_RELAY_URL", "FORGE_RELAY_URL")
96 .unwrap_or_else(|| "ws://127.0.0.1:9443".to_string()),
97 username,
98 password: env_first("SELF_HOSTED_NODE_SERVER_KEY", "MANABREW_SERVER_KEY")
99 .unwrap_or_else(|| "forge".to_string()),
100 room_id,
101 room_name: env_first("SELF_HOSTED_NODE_ROOM_NAME", "FORGE_ROOM_NAME")
102 .unwrap_or_else(|| "Self-Hosted Node".into()),
103 max_players: env_first("SELF_HOSTED_NODE_MAX_PLAYERS", "FORGE_ROOM_MAX_PLAYERS")
104 .and_then(|value| value.parse().ok())
105 .unwrap_or(4),
106 state_delta: env_bool(
110 "SELF_HOSTED_NODE_STATE_DELTA",
111 "FORGE_ROOM_STATE_DELTA",
112 true,
113 ),
114 max_games: env_first("SELF_HOSTED_NODE_MAX_GAMES", "FORGE_ROOM_MAX_GAMES")
115 .and_then(|value| value.parse().ok())
116 .filter(|games| *games >= 1)
117 .unwrap_or(1),
118 format,
119 auto_start: env_bool(
120 "SELF_HOSTED_NODE_AUTO_START",
121 "FORGE_ROOM_AUTO_START",
122 false,
123 ),
124 engine_enabled: env_bool(
125 "SELF_HOSTED_NODE_ENGINE_ENABLED",
126 "FORGE_ROOM_ENGINE_ENABLED",
127 engine_enabled_default,
128 ),
129 host_plays: env_bool(
130 "SELF_HOSTED_NODE_HOST_PLAYS",
131 "FORGE_ROOM_NODE_HOST_PLAYS",
132 false,
133 ),
134 official_key: arg_value("--official")
135 .or_else(|| env_first("SELF_HOSTED_NODE_OFFICIAL_KEY", "SECRET_MANABREW_KEY"))
136 .filter(|value| !value.is_empty()),
137 room_password: arg_value("--password")
138 .or_else(|| env_first("SELF_HOSTED_NODE_ROOM_PASSWORD", "FORGE_ROOM_PASSWORD"))
139 .filter(|value| !value.is_empty()),
140 bot_enabled: env_bool(
141 "SELF_HOSTED_NODE_BOT_ENABLED",
142 "FORGE_ROOM_BOT_ENABLED",
143 false,
144 ),
145 bot_username,
146 forge_ai: env_bool("SELF_HOSTED_NODE_FORGE_AI", "FORGE_ROOM_FORGE_AI", true),
147 bot_agent: AgentKind::default(),
148 bot_local_answers: env_bool("SELF_HOSTED_NODE_BOT_LOCAL_ANSWERS", "", true),
149 reconnect_timeout_s: env_first("SELF_HOSTED_NODE_RECONNECT_TIMEOUT_S", "")
150 .and_then(|value| value.parse().ok()),
151 table_style: None,
152 host_deck: load_deck_selection(&host_deck_id, host_commander),
153 bot_deck: load_deck_selection(&bot_deck_id, bot_commander),
154 }
155 }
156
157 #[allow(clippy::too_many_arguments)]
162 pub fn for_hosted_room(
163 relay_url: String,
164 password: String,
165 room_name: String,
166 format: GameFormat,
167 max_players: u8,
168 room_password: Option<String>,
169 reconnect_timeout_s: Option<u32>,
170 table_style: Option<String>,
171 ) -> Self {
172 let username = format!("forge-host-{}", uuid::Uuid::new_v4());
173 Self {
174 backend: EngineBackendKind::Forge,
175 relay_url,
176 username,
177 password,
178 room_id: None,
179 room_name,
180 max_players,
181 max_games: 1,
182 state_delta: true,
183 format,
184 auto_start: false,
185 engine_enabled: true,
186 host_plays: false,
187 official_key: None,
188 room_password,
189 bot_enabled: false,
190 bot_username: "Bot".into(),
191 forge_ai: true,
192 bot_agent: AgentKind::default(),
193 bot_local_answers: true,
194 reconnect_timeout_s,
195 table_style,
196 host_deck: synthetic_deck("forge-host", None),
197 bot_deck: synthetic_deck("forge-bot", None),
198 }
199 }
200}
201
202#[derive(Debug, Clone)]
203pub struct SelfPlayConfig {
204 pub seats: Vec<DeckSelection>,
205 pub starting_life: i32,
206 pub seed: u64,
207}
208
209impl SelfPlayConfig {
210 pub fn from_env() -> Self {
211 let seed = env::var("SELF_HOSTED_NODE_SELF_PLAY_SEED")
212 .ok()
213 .and_then(|value| value.parse().ok())
214 .unwrap_or(42);
215 let starting_life = match env::var("SELF_HOSTED_NODE_SELF_PLAY_FORMAT")
216 .ok()
217 .and_then(|value| parse_format(&value))
218 {
219 Some(GameFormat::Commander) => 40,
220 _ => 20,
221 };
222
223 let base: Vec<DeckSelection> = match env::var("SELF_HOSTED_NODE_SELF_PLAY_DECKS") {
224 Ok(ids) if !ids.trim().is_empty() => ids
225 .split(',')
226 .map(str::trim)
227 .filter(|id| !id.is_empty())
228 .map(|id| load_deck_selection(id, infer_commander_name(id).map(str::to_string)))
229 .collect(),
230 _ => default_self_play_seats(),
231 };
232
233 let players = env::var("SELF_HOSTED_NODE_SELF_PLAY_PLAYERS")
234 .ok()
235 .and_then(|value| value.parse().ok())
236 .unwrap_or(base.len())
237 .max(2);
238 let seats = (0..players).map(|i| base[i % base.len()].clone()).collect();
239 Self {
240 seats,
241 starting_life,
242 seed,
243 }
244 }
245}
246
247fn default_self_play_seats() -> Vec<DeckSelection> {
248 vec![
249 mono_seat("Mountain", "Lightning Bolt"),
250 mono_seat("Forest", "Grizzly Bears"),
251 ]
252}
253
254fn mono_seat(land: &str, spell: &str) -> DeckSelection {
255 let card = |name: &str| DeckCard {
256 identity: DeckCardIdentity {
257 name: name.to_string(),
258 ..Default::default()
259 },
260 ..Default::default()
261 };
262 let name = format!("{land} / {spell}");
263 DeckSelection {
264 deck: Deck {
265 name: name.clone(),
266 cards: (0..24)
267 .map(|_| card(land))
268 .chain((0..36).map(|_| card(spell)))
269 .collect(),
270 ..Default::default()
271 },
272 name,
273 commander_name: None,
274 }
275}
276
277pub fn workspace_root() -> PathBuf {
278 Path::new(env!("CARGO_MANIFEST_DIR"))
279 .ancestors()
280 .nth(3)
281 .unwrap_or_else(|| Path::new("."))
282 .to_path_buf()
283}
284
285fn load_deck_selection(deck_id: &str, commander_name: Option<String>) -> DeckSelection {
286 match load_preset_deck(deck_id, commander_name.clone()) {
287 Ok(deck) => deck,
288 Err(error) => {
289 warn!(deck_id, %error, "falling back to synthetic self-hosted-node deck");
290 synthetic_deck(deck_id, commander_name)
291 }
292 }
293}
294
295fn load_preset_deck(
296 deck_id: &str,
297 commander_name: Option<String>,
298) -> Result<DeckSelection, Box<dyn std::error::Error + Send + Sync>> {
299 let path = preset_decks_dir().join(format!("{deck_id}.json"));
300 let contents = std::fs::read_to_string(&path)?;
301 let preset: PresetDeckFile = serde_json::from_str(&contents)?;
302 let mut cards = Vec::new();
303 for entry in preset.cards {
304 for _ in 0..entry.count {
305 cards.push(DeckCard {
306 identity: DeckCardIdentity {
307 name: entry.name.clone(),
308 set_code: entry.set.clone(),
309 ..Default::default()
310 },
311 ..Default::default()
312 });
313 }
314 }
315 let label = preset.label;
316 Ok(DeckSelection {
317 deck: Deck {
318 name: label.clone(),
319 cards,
320 ..Default::default()
321 },
322 name: label,
323 commander_name: commander_name.or(preset.commander),
324 })
325}
326
327fn preset_decks_dir() -> PathBuf {
328 env::var("PRESET_DECKS_DIR")
329 .map(PathBuf::from)
330 .unwrap_or_else(|_| workspace_root().join("public/preset_decks"))
331}
332
333fn synthetic_deck(name: &str, commander_name: Option<String>) -> DeckSelection {
334 let cards: Vec<DeckCard> = (0..60)
335 .map(|_| DeckCard {
336 identity: DeckCardIdentity {
337 name: "Mountain".to_string(),
338 set_code: "M20".to_string(),
339 ..Default::default()
340 },
341 ..Default::default()
342 })
343 .collect();
344 DeckSelection {
345 name: name.to_string(),
346 deck: Deck {
347 name: name.to_string(),
348 cards,
349 ..Default::default()
350 },
351 commander_name,
352 }
353}
354
355fn infer_commander_name(deck_id: &str) -> Option<&'static str> {
356 match deck_id {
357 "ashling_limitless_commander" => Some("Ashling, the Limitless"),
358 "hearthhull_world_shaper_commander" => Some("Hearthhull, the Worldseed"),
359 "kaalia_regression_commander" => Some("Kaalia of the Vast"),
360 "neheb_minotaur_commander" => Some("Neheb, the Worthy"),
361 "ramses_regression_commander" => Some("Ramses, Assassin Lord"),
362 "real_teval_commander" => None,
363 _ => None,
364 }
365}
366
367fn env_first(primary: &str, fallback: &str) -> Option<String> {
368 env::var(primary).ok().or_else(|| env::var(fallback).ok())
369}
370
371fn arg_value(flag: &str) -> Option<String> {
372 let prefix = format!("{flag}=");
373 let mut args = env::args();
374 while let Some(arg) = args.next() {
375 if let Some(value) = arg.strip_prefix(&prefix) {
376 return Some(value.to_string());
377 }
378 if arg == flag {
379 return args.next();
380 }
381 }
382 None
383}
384
385fn env_bool(primary: &str, fallback: &str, default: bool) -> bool {
386 env_first(primary, fallback)
387 .and_then(|value| match value.to_ascii_lowercase().as_str() {
388 "1" | "true" | "yes" | "on" => Some(true),
389 "0" | "false" | "no" | "off" => Some(false),
390 _ => None,
391 })
392 .unwrap_or(default)
393}
394
395fn parse_format(value: &str) -> Option<GameFormat> {
396 let mut chars = value.trim().chars();
397 let first = chars.next()?;
398 let mut canonical = first.to_ascii_uppercase().to_string();
399 canonical.extend(chars.map(|c| c.to_ascii_lowercase()));
400 serde_json::from_value(serde_json::Value::String(canonical)).ok()
401}