saints-mile 1.0.2

A frontier JRPG for the adults who loved those games first
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Saint's Mile — A frontier JRPG for the adults who loved those games first.
//!
//! Terminal entry point: setup, app loop, teardown.

use std::io;
use std::time::Duration;

use anyhow::Result;
use crossterm::{
    event,
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::prelude::*;

use saints_mile::dev::quickstart::JumpPoint;
use saints_mile::state::store::StateStore;
use saints_mile::ui::{App, AppScreen, InputResult, QuitOption, PauseOption};
use saints_mile::ui::input::handle_event;
use saints_mile::ui::screens::{title, scene, standoff, combat, save_load, error, pause, status};
use saints_mile::ui::screens::save_load::{SaveLoadMode, SaveSlotInfo};

const VERSION: &str = env!("CARGO_PKG_VERSION");

type Term = Terminal<CrosstermBackend<io::Stdout>>;

fn main() -> Result<()> {
    let args: Vec<String> = std::env::args().collect();
    let mut quickstart_point: Option<JumpPoint> = None;

    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--version" | "-V" => {
                println!("saints-mile {}", VERSION);
                return Ok(());
            }
            "--help" | "-h" => {
                println!("saints-mile v{}\n", VERSION);
                println!("A frontier JRPG for the adults who loved those games first.\n");
                println!("USAGE:");
                println!("  saints-mile                          Start the game");
                println!("  saints-mile --quickstart <point>     Jump to a named point");
                println!("  saints-mile --version                Print version and exit");
                println!("  saints-mile --help                   Show this help and exit");
                println!();
                println!("QUICKSTART POINTS:");
                println!("  Prologue          Prologue start");
                println!("  BitterCutFight    Ch1 Bitter Cut fight");
                println!("  ConvoyStart       Ch2 convoy join");
                println!("  RelayRescue       Ch2 relay triage");
                return Ok(());
            }
            "--quickstart" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --quickstart requires a jump point name");
                    eprintln!("run saints-mile --help for available points");
                    std::process::exit(1);
                }
                quickstart_point = parse_jump_point(&args[i]);
                if quickstart_point.is_none() {
                    eprintln!("error: unknown quickstart point '{}'", args[i]);
                    eprintln!("run saints-mile --help for available points");
                    std::process::exit(1);
                }
            }
            _ => {}
        }
        i += 1;
    }

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let save_dir = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join("saves");

    let mut app = App::new(save_dir.clone());

    // If quickstart requested, inject the jump point state
    if let Some(jump) = quickstart_point {
        let state = jump.create_state();
        app.store = StateStore::from_state(state, &save_dir);
        let beat = app.store.state().beat.0.clone();
        app.load_scene(&beat);
    }

    let tick_rate = Duration::from_millis(50);
    let result = run_loop(&mut terminal, &mut app, tick_rate);

    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    result
}

/// Parse a quickstart jump point name (case-insensitive).
fn parse_jump_point(name: &str) -> Option<JumpPoint> {
    match name.to_lowercase().as_str() {
        "prologue" | "prologuestart" => Some(JumpPoint::PrologueStart),
        "prologuearroyo" => Some(JumpPoint::PrologueArroyo),
        "prologuecampfire" => Some(JumpPoint::PrologueCampfire),
        "cedarwakestart" => Some(JumpPoint::CedarWakeStart),
        "bittercutfight" => Some(JumpPoint::BitterCutFight),
        "bittercutdispatch" => Some(JumpPoint::BitterCutDispatch),
        "convoystart" => Some(JumpPoint::ConvoyStart),
        "redswitchwash" => Some(JumpPoint::RedSwitchWash),
        "hollowpump" => Some(JumpPoint::HollowPump),
        "relayrescue" | "relaytriage" => Some(JumpPoint::RelayTriage),
        "relayarrival" => Some(JumpPoint::RelayArrival),
        _ => None,
    }
}

fn run_loop(terminal: &mut Term, app: &mut App, tick_rate: Duration) -> Result<()> {
    loop {
        terminal.draw(|frame| render(frame, app))?;

        if event::poll(tick_rate)? {
            let ev = event::read()?;
            let result = handle_event(app, ev);
            process_result(app, result);
        }

        app.tick();

        if app.should_quit {
            break;
        }
    }
    Ok(())
}

fn render(frame: &mut Frame, app: &App) {
    let area = frame.area();

    match &app.screen {
        AppScreen::Title => {
            title::render_title(frame, area);
        }
        AppScreen::Scene { chapter_label, location_label } => {
            if let Some(prepared) = &app.current_prepared {
                if prepared.choices.is_empty() {
                    scene::render_end_scene(
                        frame, area, prepared, &app.reveal,
                        app.age_phase(), chapter_label, location_label,
                        app.memory_objects(),
                    );
                } else {
                    scene::render_scene(
                        frame, area, prepared, &app.reveal,
                        app.choice_cursor, app.age_phase(),
                        chapter_label, location_label, app.memory_objects(),
                    );
                }
            }
        }
        AppScreen::Standoff => {
            if let (Some(state), Some(ui)) = (&app.encounter_state, &app.standoff_ui) {
                let terrain = app.encounter_def.as_ref()
                    .map(|e| e.terrain.name.as_str())
                    .unwrap_or("Unknown");
                standoff::render_standoff(frame, area, state, ui, terrain);
            }
        }
        AppScreen::StandoffResult => {
            if let Some(state) = &app.encounter_state {
                let posture = app.combat_ui.standoff_posture
                    .unwrap_or(saints_mile::combat::types::StandoffPosture::SteadyHand);
                standoff::render_standoff_result(frame, area, state, posture);
            }
        }
        AppScreen::Combat => {
            if let Some(state) = &app.encounter_state {
                combat::render_combat(
                    frame, area, state, &app.combat_ui,
                    app.age_phase(), &app.combat_actions,
                );
            }
        }
        AppScreen::CombatOutcome => {
            render_combat_outcome(frame, area, app);
        }
        AppScreen::SaveLoad { mode } => {
            let slots = discover_save_slots();
            save_load::render_save_load(frame, area, *mode, &slots, app.save_cursor, app.delete_confirming);
        }
        AppScreen::ConfirmQuit { .. } => {
            render_confirm_quit(frame, area, app.quit_cursor);
        }
        AppScreen::Error { message, .. } => {
            error::render_error(frame, area, message);
        }
        AppScreen::Pause { .. } => {
            pause::render_pause(frame, area, app.pause_cursor);
        }
        AppScreen::Status { .. } => {
            status::render_status(frame, area, app.store.state());
        }
    }
}

fn render_combat_outcome(frame: &mut Frame, area: Rect, app: &App) {
    use ratatui::widgets::Paragraph;
    use saints_mile::combat::engine::EncounterResult;
    use saints_mile::ui::theme;

    let outcome = app.encounter_state.as_ref()
        .and_then(|s| s.outcome.as_ref());

    let mut lines = vec![
        Line::from(""),
        Line::from(""),
    ];

    if let Some(outcome) = outcome {
        let (label, color) = match outcome.result {
            EncounterResult::Victory => ("VICTORY", Color::Green),
            EncounterResult::Defeat => ("DEFEAT", Color::Red),
            EncounterResult::Fled => ("FLED", Color::Yellow),
            EncounterResult::ObjectiveComplete => ("OBJECTIVE COMPLETE", Color::Green),
        };

        lines.push(Line::from(Span::styled(
            format!("  {}", label),
            Style::default().fg(color).add_modifier(Modifier::BOLD),
        )));
        lines.push(Line::from(""));

        // Objective summary
        if let Some(state) = &app.encounter_state {
            for obj in &state.objectives {
                let (icon, obj_color) = match obj.status {
                    saints_mile::combat::engine::ObjectiveStatus::Active => ("[ ]", Color::White),
                    saints_mile::combat::engine::ObjectiveStatus::Succeeded => ("[x]", Color::Green),
                    saints_mile::combat::engine::ObjectiveStatus::Failed => ("[\u{2717}]", Color::Red),
                };
                lines.push(Line::from(vec![
                    Span::styled(format!("  {} ", icon), Style::default().fg(obj_color)),
                    Span::styled(&obj.label, Style::default().fg(obj_color)),
                ]));
            }
        }

        // Last combat log entries
        lines.push(Line::from(""));
        let log_start = app.combat_ui.log.len().saturating_sub(4);
        for entry in &app.combat_ui.log[log_start..] {
            lines.push(Line::from(Span::styled(entry.text.clone(), entry.style)));
        }
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  [Enter] Continue",
        theme::dim_style(),
    )));

    let para = Paragraph::new(lines);
    frame.render_widget(para, area);
}

fn render_confirm_quit(frame: &mut Frame, area: Rect, cursor: usize) {
    use ratatui::widgets::Paragraph;
    use saints_mile::ui::theme;

    let options = QuitOption::all();
    let mut lines = vec![
        Line::from(""),
        Line::from(""),
        Line::from(Span::styled(
            "  QUIT GAME",
            Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "  You have unsaved progress. What would you like to do?",
            Style::default().fg(Color::Rgb(160, 150, 130)),
        )),
        Line::from(""),
    ];

    for (i, option) in options.iter().enumerate() {
        let marker = if i == cursor { "> " } else { "  " };
        let color = if i == cursor { Color::White } else { Color::DarkGray };
        lines.push(Line::from(Span::styled(
            format!("  {} {}", marker, option.label()),
            Style::default().fg(color),
        )));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  [Esc] Cancel",
        theme::dim_style(),
    )));

    let para = Paragraph::new(lines);
    frame.render_widget(para, area);
}

fn process_result(app: &mut App, result: InputResult) {
    match result {
        InputResult::None | InputResult::Redraw => {}
        InputResult::Quit => app.should_quit = true,
        InputResult::NewGame => app.new_game(),
        InputResult::LoadScreen => {
            app.save_cursor = 0;
            app.screen = AppScreen::SaveLoad { mode: SaveLoadMode::Load };
        }
        InputResult::BackToTitle => app.screen = AppScreen::Title,
        InputResult::QuickSave => app.quick_save(),
        InputResult::AdvanceScene => app.advance_no_choice_scene(),
        InputResult::ConfirmChoice(idx) => app.execute_choice(idx),
        InputResult::ConfirmSaveLoad(idx) => handle_save_load(app, idx),

        // Standoff input
        InputResult::StandoffCyclePosture(dir) => {
            if let Some(ui) = &mut app.standoff_ui {
                let max = ui.postures.len();
                if dir > 0 && ui.posture_cursor < max - 1 {
                    ui.posture_cursor += 1;
                } else if dir < 0 && ui.posture_cursor > 0 {
                    ui.posture_cursor -= 1;
                }
            }
        }
        InputResult::StandoffCycleFocus(dir) => {
            if let Some(ui) = &mut app.standoff_ui {
                let max = ui.enemy_count;
                if dir > 0 {
                    ui.focus_cursor = (ui.focus_cursor + 1) % max;
                } else if ui.focus_cursor > 0 {
                    ui.focus_cursor -= 1;
                } else {
                    ui.focus_cursor = max.saturating_sub(1);
                }
            }
        }
        InputResult::StandoffConfirm => app.resolve_standoff(),

        // Combat input
        InputResult::CombatCycleAction(dir) => {
            let max = app.combat_actions.len().saturating_sub(1);
            if dir > 0 && app.combat_ui.action_cursor < max {
                app.combat_ui.action_cursor += 1;
            } else if dir < 0 && app.combat_ui.action_cursor > 0 {
                app.combat_ui.action_cursor -= 1;
            }
        }
        InputResult::CombatCycleTarget(dir) => {
            let max = app.living_enemy_count().saturating_sub(1);
            if dir > 0 && app.combat_ui.target_cursor < max {
                app.combat_ui.target_cursor += 1;
            } else if dir < 0 && app.combat_ui.target_cursor > 0 {
                app.combat_ui.target_cursor -= 1;
            }
        }
        InputResult::CombatConfirmAction => app.execute_combat_action(),

        // Post-standoff / post-combat
        InputResult::AdvanceCombat => {
            match &app.screen {
                AppScreen::StandoffResult => app.begin_combat(),
                AppScreen::CombatOutcome => app.exit_combat(),
                _ => {}
            }
        }

        // Quit confirmation flow
        InputResult::RequestQuit => {
            // Swap the current screen into the return_screen box
            let current = std::mem::replace(&mut app.screen, AppScreen::Title);
            app.quit_cursor = 0;
            app.screen = AppScreen::ConfirmQuit {
                return_screen: Box::new(current),
            };
        }
        InputResult::ConfirmQuitOption(option) => {
            match option {
                QuitOption::SaveAndQuit => {
                    app.quick_save();
                    app.should_quit = true;
                }
                QuitOption::QuitWithoutSaving => {
                    app.should_quit = true;
                }
                QuitOption::Cancel => {
                    // Restore the screen we came from
                    let screen = std::mem::replace(&mut app.screen, AppScreen::Title);
                    if let AppScreen::ConfirmQuit { return_screen } = screen {
                        app.screen = *return_screen;
                    }
                }
            }
        }
        InputResult::CancelQuit => {
            let screen = std::mem::replace(&mut app.screen, AppScreen::Title);
            if let AppScreen::ConfirmQuit { return_screen } = screen {
                app.screen = *return_screen;
            }
        }

        // Error screen
        InputResult::DismissError => {
            let screen = std::mem::replace(&mut app.screen, AppScreen::Title);
            if let AppScreen::Error { return_screen, .. } = screen {
                app.screen = *return_screen;
            }
        }

        // Pause screen
        InputResult::OpenPause => {
            let current = std::mem::replace(&mut app.screen, AppScreen::Title);
            app.pause_cursor = 0;
            app.screen = AppScreen::Pause {
                return_screen: Box::new(current),
            };
        }
        InputResult::ConfirmPauseOption(option) => {
            match option {
                PauseOption::Resume => {
                    let screen = std::mem::replace(&mut app.screen, AppScreen::Title);
                    if let AppScreen::Pause { return_screen } = screen {
                        app.screen = *return_screen;
                    }
                }
                PauseOption::Save => {
                    // Save to quicksave then stay paused
                    match app.store.save("quicksave") {
                        Ok(_) => {} // silently succeed
                        Err(e) => {
                            app.show_error(format!("Save failed: {}", e));
                        }
                    }
                }
                PauseOption::ReturnToTitle => {
                    app.screen = AppScreen::Title;
                }
            }
        }
        InputResult::CancelPause => {
            let screen = std::mem::replace(&mut app.screen, AppScreen::Title);
            if let AppScreen::Pause { return_screen } = screen {
                app.screen = *return_screen;
            }
        }

        // Status screen
        InputResult::OpenStatus => {
            let current = std::mem::replace(&mut app.screen, AppScreen::Title);
            app.screen = AppScreen::Status {
                return_screen: Box::new(current),
            };
        }
        InputResult::CloseStatus => {
            let screen = std::mem::replace(&mut app.screen, AppScreen::Title);
            if let AppScreen::Status { return_screen } = screen {
                app.screen = *return_screen;
            }
        }

        // Save deletion
        InputResult::RequestDeleteSave(idx) => {
            app.delete_confirming = Some(idx);
        }
        InputResult::ConfirmDeleteSave(idx) => {
            let slots = discover_save_slots();
            if let Some(slot) = slots.get(idx) {
                if slot.exists {
                    let save_dir = app.save_dir();
                    if let Err(e) = saints_mile::state::store::StateStore::delete_save(&slot.name, &save_dir) {
                        app.show_error(e);
                    }
                }
            }
        }
        InputResult::CancelDeleteSave => {
            // delete_confirming already cleared by input handler
        }
    }
}

fn handle_save_load(app: &mut App, slot_index: usize) {
    let slots = discover_save_slots();
    if let Some(slot) = slots.get(slot_index) {
        match &app.screen {
            AppScreen::SaveLoad { mode: SaveLoadMode::Save } => {
                match app.store.save(&slot.name) {
                    Ok(_) => {
                        app.screen = AppScreen::Title;
                    }
                    Err(e) => {
                        app.show_error(format!("Save failed: {}", e));
                    }
                }
            }
            AppScreen::SaveLoad { mode: SaveLoadMode::Load } => {
                let path = app.save_dir().join(format!("{}.ron", slot.name));
                if !path.exists() {
                    app.show_error("Save slot is empty.".to_string());
                    return;
                }
                match saints_mile::state::store::StateStore::load(&path) {
                    Ok(loaded) => {
                        app.store = loaded;
                        let beat = app.store.state().beat.0.clone();
                        app.load_scene(&beat);
                    }
                    Err(e) => {
                        app.show_error(format!("Load failed: {}", e));
                    }
                }
            }
            _ => {}
        }
    }
}

fn discover_save_slots() -> Vec<SaveSlotInfo> {
    let save_dir = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join("saves");

    (1..=3)
        .map(|i| {
            let name = format!("slot{}", i);
            // Validate slot name contains only safe characters
            if !name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-') {
                return SaveSlotInfo { name, label: String::new(), exists: false };
            }
            let path = save_dir.join(format!("{}.ron", name));
            // Validate resolved path is within the save directory
            if let (Ok(canonical_dir), Ok(canonical_path)) = (
                std::fs::canonicalize(&save_dir),
                std::fs::canonicalize(&path),
            ) {
                if !canonical_path.starts_with(&canonical_dir) {
                    return SaveSlotInfo { name, label: String::new(), exists: false };
                }
            }
            let (exists, label) = if path.exists() {
                match std::fs::read_to_string(&path) {
                    Ok(contents) => {
                        if let Ok(envelope) = ron::from_str::<saints_mile::state::store::SaveEnvelope>(&contents) {
                            (true, envelope.label)
                        } else {
                            (true, "corrupted save".to_string())
                        }
                    }
                    Err(_) => (false, String::new()),
                }
            } else {
                (false, String::new())
            };
            SaveSlotInfo { name, label, exists }
        })
        .collect()
}