rumenx-chess 0.2.0

A high-performance chess engine and REST API server written in Rust
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::engine::game::Game;
use crate::engine::san::move_to_san;
use crate::engine::types::{Color, Move, PieceType, Square};

// ---------------------------------------------------------------------------
// Request models
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateGameRequest {
    pub fen: Option<String>,
    pub ai_enabled: Option<bool>,
    pub ai_difficulty: Option<String>,
    pub ai_color: Option<String>,
    pub white_player: Option<String>,
    pub black_player: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MoveRequest {
    pub from: String,
    pub to: String,
    pub promotion: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AiMoveRequest {
    pub difficulty: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FenRequest {
    pub fen: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListGamesQuery {
    pub limit: Option<usize>,
    pub offset: Option<usize>,
    pub status: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LegalMovesQuery {
    pub from: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnalysisQuery {
    pub difficulty: Option<String>,
}

// ---------------------------------------------------------------------------
// Chat request / response models (API layer)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatRequest {
    pub message: String,
    pub provider: Option<String>,
    pub api_key: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatResponse {
    pub response: String,
    pub provider: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub game_context: Option<HashMap<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suggestions: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReactionRequest {
    #[serde(rename = "move")]
    pub chess_move: String,
    pub provider: Option<String>,
    pub api_key: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReactionResponse {
    pub reaction: String,
    pub provider: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub game_context: Option<HashMap<String, serde_json::Value>>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatStatusResponse {
    pub enabled: bool,
    pub provider: Option<String>,
}

// ---------------------------------------------------------------------------
// Response models
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HealthResponse {
    pub status: String,
    pub version: String,
    pub language: String,
    pub engine: String,
    pub uptime: u64,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteResponse {
    pub success: bool,
    pub message: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GameResponse {
    pub id: String,
    pub board: Vec<Vec<Option<String>>>,
    pub fen: String,
    pub status: String,
    pub current_player: String,
    pub move_history: Vec<MoveHistoryEntry>,
    pub captured_pieces: CapturedPieces,
    pub check: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_move: Option<LastMove>,
    pub players: Players,
    pub created_at: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MoveHistoryEntry {
    pub from: String,
    pub to: String,
    pub piece: PieceInfo,
    pub captured: Option<PieceInfo>,
    pub promotion: Option<String>,
    pub san: String,
    pub fen: String,
}

#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PieceInfo {
    #[serde(rename = "type")]
    pub piece_type: String,
    pub color: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CapturedPieces {
    pub white: Vec<String>,
    pub black: Vec<String>,
}

#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct LastMove {
    pub from: String,
    pub to: String,
    pub san: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Players {
    pub white: String,
    pub black: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ListGamesResponse {
    pub games: Vec<GameResponse>,
    pub total: usize,
    pub limit: usize,
    pub offset: usize,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MoveListResponse {
    pub moves: Vec<MoveHistoryEntry>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LegalMoveEntry {
    pub from: String,
    pub to: String,
    pub san: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub promotion: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LegalMovesResponse {
    pub moves: Vec<LegalMoveEntry>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AiMoveResponse {
    #[serde(rename = "move")]
    pub ai_move: LastMove,
    #[serde(flatten)]
    pub game: GameResponse,
    pub evaluation: Option<i32>,
    pub thinking_time: u64,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HintResponse {
    pub hint: LastMove,
    pub evaluation: Option<i32>,
    pub thinking_time: u64,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AnalysisResponse {
    pub evaluation: i32,
    pub best_move: Option<LastMove>,
    pub depth: u32,
    pub nodes_searched: u64,
    pub thinking_time: u64,
}

// ---------------------------------------------------------------------------
// Conversion helpers
// ---------------------------------------------------------------------------

fn piece_type_name(pt: PieceType) -> &'static str {
    match pt {
        PieceType::Pawn => "pawn",
        PieceType::Knight => "knight",
        PieceType::Bishop => "bishop",
        PieceType::Rook => "rook",
        PieceType::Queen => "queen",
        PieceType::King => "king",
    }
}

pub(crate) fn color_name(c: Color) -> &'static str {
    match c {
        Color::White => "white",
        Color::Black => "black",
    }
}

/// Promotion piece type character from string like "queen", "rook", etc.
pub fn parse_promotion(s: &str) -> Option<PieceType> {
    match s.to_lowercase().as_str() {
        "queen" | "q" => Some(PieceType::Queen),
        "rook" | "r" => Some(PieceType::Rook),
        "bishop" | "b" => Some(PieceType::Bishop),
        "knight" | "n" => Some(PieceType::Knight),
        _ => None,
    }
}

fn promotion_name(pt: PieceType) -> &'static str {
    match pt {
        PieceType::Queen => "queen",
        PieceType::Rook => "rook",
        PieceType::Bishop => "bishop",
        PieceType::Knight => "knight",
        _ => "queen",
    }
}

/// Build the 8×8 board array for the API response.
/// Row 0 = rank 8 (top), row 7 = rank 1 (bottom).
/// Pieces: uppercase for White ("R"), lowercase for Black ("r").
/// Empty = None.
pub fn board_to_api(game: &Game) -> Vec<Vec<Option<String>>> {
    let pos = game.position();
    let mut rows = Vec::with_capacity(8);
    for rank in (0..8u8).rev() {
        let mut row = Vec::with_capacity(8);
        for file in 0..8u8 {
            let sq = Square::from_file_rank(file, rank);
            match pos.piece_at(sq) {
                Some((color, pt)) => {
                    let ch = pt.to_char(color);
                    row.push(Some(ch.to_string()));
                }
                None => row.push(None),
            }
        }
        rows.push(row);
    }
    rows
}

/// Build captured pieces from move history by replaying captures.
pub fn captured_pieces(game: &Game) -> CapturedPieces {
    let mut white_captured: Vec<String> = Vec::new(); // pieces captured BY white (black pieces)
    let mut black_captured: Vec<String> = Vec::new(); // pieces captured BY black (white pieces)

    // We need to track captures. The MoveRecord has the move with CAPTURE flag.
    // We need to know what was captured. We'll replay from starting position.
    // Simpler: read captured info from moves. But MoveRecord only stores mv and san.
    // We'll need to reconstruct. For now, track from the position difference.

    // Alternative: compare piece counts from starting position vs current.
    // This is simpler and always correct.
    let starting_counts = if game.started_from_fen() {
        // Re-parse the starting FEN to get original piece counts.
        if let Ok(start) = crate::engine::board::Position::from_fen(game.starting_fen()) {
            count_pieces(&start)
        } else {
            starting_piece_counts()
        }
    } else {
        starting_piece_counts()
    };

    let current = count_pieces(game.position());

    // White pieces captured (by Black) = starting white - current white
    for pt_idx in 0..6 {
        let diff = starting_counts[0][pt_idx] as i32 - current[0][pt_idx] as i32;
        let pt = PieceType::ALL[pt_idx];
        for _ in 0..diff.max(0) {
            white_captured.push(pt.to_char(Color::White).to_string());
        }
    }

    // Black pieces captured (by White) = starting black - current black
    for pt_idx in 0..6 {
        let diff = starting_counts[1][pt_idx] as i32 - current[1][pt_idx] as i32;
        let pt = PieceType::ALL[pt_idx];
        for _ in 0..diff.max(0) {
            black_captured.push(pt.to_char(Color::Black).to_string());
        }
    }

    CapturedPieces {
        white: black_captured, // pieces lost by white (captured by black)
        black: white_captured, // pieces lost by black (captured by white)
    }
}

fn count_pieces(pos: &crate::engine::board::Position) -> [[u32; 6]; 2] {
    let mut counts = [[0u32; 6]; 2];
    for (color, row) in counts.iter_mut().enumerate() {
        for (pt, cell) in row.iter_mut().enumerate() {
            *cell = pos.pieces[color][pt].pop_count();
        }
    }
    counts
}

fn starting_piece_counts() -> [[u32; 6]; 2] {
    // Standard starting position: P=8, N=2, B=2, R=2, Q=1, K=1
    [[8, 2, 2, 2, 1, 1], [8, 2, 2, 2, 1, 1]]
}

/// Convert internal Game to full API GameResponse.
pub fn game_to_response(game: &Game) -> GameResponse {
    let status = game.status();
    let is_check = matches!(status, crate::engine::types::GameStatus::Check);

    let last_move = game.move_history().last().map(|rec| LastMove {
        from: rec.mv.from.to_algebraic(),
        to: rec.mv.to.to_algebraic(),
        san: rec.san.clone(),
    });

    GameResponse {
        id: game.id.clone(),
        board: board_to_api(game),
        fen: game.to_fen(),
        status: status.as_str().to_string(),
        current_player: color_name(game.side_to_move()).to_string(),
        move_history: build_move_history(game),
        captured_pieces: captured_pieces(game),
        check: is_check,
        last_move,
        players: Players {
            white: game.white_player.clone(),
            black: game.black_player.clone(),
        },
        created_at: game.created_at.to_rfc3339(),
    }
}

/// Build the move history entries by replaying the game from the starting
/// position to reconstruct per-move FEN and captured piece info.
fn build_move_history(game: &Game) -> Vec<MoveHistoryEntry> {
    let history = game.move_history();
    if history.is_empty() {
        return Vec::new();
    }

    // Replay from starting FEN.
    let mut replay = if game.started_from_fen() {
        match Game::from_fen(game.starting_fen()) {
            Ok(g) => g,
            Err(_) => return Vec::new(),
        }
    } else {
        Game::new()
    };

    let mut entries = Vec::with_capacity(history.len());

    for rec in history {
        let mv = rec.mv;
        let pos = replay.position();
        let side = pos.side_to_move;

        // Determine piece being moved.
        let piece_info = pos
            .piece_at(mv.from)
            .map(|(c, pt)| PieceInfo {
                piece_type: piece_type_name(pt).to_string(),
                color: color_name(c).to_string(),
            })
            .unwrap_or(PieceInfo {
                piece_type: "pawn".to_string(),
                color: color_name(side).to_string(),
            });

        // Determine captured piece (if any).
        let captured = if mv.flags.is_capture() {
            if mv.flags.is_en_passant() {
                Some(PieceInfo {
                    piece_type: "pawn".to_string(),
                    color: color_name(!side).to_string(),
                })
            } else {
                pos.piece_at(mv.to).map(|(c, pt)| PieceInfo {
                    piece_type: piece_type_name(pt).to_string(),
                    color: color_name(c).to_string(),
                })
            }
        } else {
            None
        };

        let promotion = mv.promotion.map(|pt| promotion_name(pt).to_string());

        // Make the move to get the resulting FEN.
        let _ = replay.make_move(mv);
        let fen_after = replay.to_fen();

        entries.push(MoveHistoryEntry {
            from: mv.from.to_algebraic(),
            to: mv.to.to_algebraic(),
            piece: piece_info,
            captured,
            promotion,
            san: rec.san.clone(),
            fen: fen_after,
        });
    }

    entries
}

/// Build a legal move entry with SAN.
pub fn legal_move_entry(game: &Game, mv: Move, legal: &[Move]) -> LegalMoveEntry {
    let san = move_to_san(game.position(), mv, legal);
    LegalMoveEntry {
        from: mv.from.to_algebraic(),
        to: mv.to.to_algebraic(),
        san,
        promotion: mv.promotion.map(|pt| promotion_name(pt).to_string()),
    }
}