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
use crate::parse::{parse_uci, OptionType, UCI};
use anyhow::{bail, Result};
use async_trait::async_trait;
use std::{
    fmt::Display,
    process::Stdio,
    sync::{Arc, Mutex},
};
use tokio::{
    io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
    process::{Child, ChildStdin, ChildStdout, Command},
};

/// ChessEngine trait can be implemented for structures that implement the UCI Protocol
#[async_trait]
pub trait ChessEngine: Sized {
    /// Create new engine from executable
    async fn new(exe_path: &str) -> Result<Self>;

    /// Start the UCI Protocol
    async fn start_uci(&mut self) -> Result<()>;

    /// Notify engine of new game start
    async fn new_game(&mut self) -> Result<()>;

    /// Notify engine of new position to search
    async fn set_position(&mut self, position: &str) -> Result<()>;

    /// Notify engine to search for best move until explicitly stopped
    async fn go_infinite(&mut self) -> Result<()>;

    /// Notify engine to search for best move to a certain depth
    async fn go_depth(&mut self, plies: usize) -> Result<()>;

    /// Notify engine to search for best move for a set time
    async fn go_time(&mut self, ms: usize) -> Result<()>;

    /// Notify engine to search for a mate in a certain number of moves
    async fn go_mate(&mut self, mate_in: usize) -> Result<()>;

    /// Notify engine to stop current search
    async fn stop(&mut self) -> Result<()>;

    /// Retrieve the latest evaluation from the engine
    async fn get_evaluation(&mut self) -> Option<Evaluation>;

    /// Retrieve the list of available options from the engine
    async fn get_options(&mut self) -> Result<Vec<EngineOption>>;

    /// Set an option in the engine
    async fn set_option(&mut self, option: String, value: String) -> Result<()>;
}

/// Engine can be created to spawn any Chess Engine that implements the UCI Protocol
pub struct Engine {
    stdin: ChildStdin,
    state: EngineState,
    _proc: Child,
}

impl Engine {
    /// Send a command to the engine
    async fn send_command(&mut self, command: String) -> Result<()> {
        self.stdin.write_all(command.as_bytes()).await?;
        self.stdin.flush().await?;
        Ok(())
    }

    /// Check if the expected state is the current engine state
    async fn _expect_state(&mut self, exp_state: &EngineStateEnum) -> Result<()> {
        let state = self.state.state.lock().expect("couldn't aquire state lock");
        if *exp_state == *state {
            return Ok(());
        }
        bail!("engine didn't respond with {:?}", exp_state)
    }

    /// Check if the expected state is the current engine state, retries a couple of times
    /// waiting between attempts.
    async fn expect_state(&mut self, exp_state: EngineStateEnum) -> Result<()> {
        for _ in 0..10 {
            match self._expect_state(&exp_state).await {
                Ok(_) => return Ok(()),
                Err(_) => tokio::time::sleep(std::time::Duration::from_millis(100)).await,
            };
        }
        bail!("engine didn't respond with {:?}", exp_state)
    }

    /// Check if the engine initialized UCI
    async fn expect_uciok(&mut self) -> Result<()> {
        self.expect_state(EngineStateEnum::Initialized).await
    }

    /// Check if the engine is ready to receive commands
    async fn expect_readyok(&mut self) -> Result<()> {
        self.expect_state(EngineStateEnum::Ready).await
    }

    /// Change current engine state
    async fn set_state(&mut self, new_state: EngineStateEnum) -> Result<()> {
        // TODO: Return old state
        let mut state = self.state.state.lock().expect("couldn't acquire lock");
        *state = new_state;
        Ok(())
    }
}

/// Spawn a subprocess and return handles for stdin and stdout
fn spawn_process(exe_path: &str) -> Result<(Child, ChildStdin, ChildStdout)> {
    let mut cmd = Command::new(exe_path);
    cmd.stdin(Stdio::piped());
    cmd.stdout(Stdio::piped());
    let mut proc = cmd.spawn()?;
    let stdout = proc.stdout.take().expect("no stdout available");
    let stdin = proc.stdin.take().expect("no stdin available");
    Ok((proc, stdin, stdout))
}

#[async_trait]
impl ChessEngine for Engine {
    async fn new(exe_path: &str) -> Result<Self> {
        let (proc, stdin, stdout) = spawn_process(exe_path)?;
        let state = EngineState::new(stdout).await;
        Ok(Engine {
            state: state,
            stdin: stdin,
            _proc: proc,
        })
    }

    async fn start_uci(&mut self) -> Result<()> {
        self.send_command("uci\n".to_string()).await?;
        self.expect_uciok().await?;
        self.send_command("isready\n".to_string()).await?;
        self.expect_readyok().await?;
        Ok(())
    }

    async fn new_game(&mut self) -> Result<()> {
        self.send_command("ucinewgame\n".to_string()).await?;
        self.set_state(EngineStateEnum::Initialized).await?;
        self.send_command("isready\n".to_string()).await?;
        self.expect_readyok().await?;
        Ok(())
    }

    async fn set_position(&mut self, fen: &str) -> Result<()> {
        let cmd = format!("position fen {}\n", fen);
        self.send_command(cmd.to_string()).await
    }

    async fn go_infinite(&mut self) -> Result<()> {
        self.send_command("go infinite\n".to_string()).await?;
        self.set_state(EngineStateEnum::Thinking).await?;
        Ok(())
    }

    async fn go_depth(&mut self, depth: usize) -> Result<()> {
        self.send_command(format!("go depth {}\n", depth).to_string())
            .await?;
        self.set_state(EngineStateEnum::Thinking).await?;
        Ok(())
    }

    async fn go_time(&mut self, ms: usize) -> Result<()> {
        self.send_command(format!("go movetime {}\n", ms).to_string())
            .await?;
        self.set_state(EngineStateEnum::Thinking).await?;
        Ok(())
    }

    async fn go_mate(&mut self, mate_in: usize) -> Result<()> {
        self.send_command(format!("go mate {}\n", mate_in).to_string())
            .await?;
        self.set_state(EngineStateEnum::Thinking).await?;
        Ok(())
    }

    async fn stop(&mut self) -> Result<()> {
        self.send_command("stop\n".to_string()).await?;
        self.set_state(EngineStateEnum::Initialized).await?;
        Ok(())
    }

    async fn get_evaluation(&mut self) -> Option<Evaluation> {
        let ev = self.state.evaluation.lock().expect("couldn't acquire lock");
        return match &*ev {
            Some(e) => Some(e.clone()),
            None => None,
        };
    }

    async fn get_options(&mut self) -> Result<Vec<EngineOption>> {
        let options = self.state.options.lock().expect("couldn't acquire lock");
        Ok(options.clone())
    }

    async fn set_option(&mut self, option: String, value: String) -> Result<()> {
        let cmd = format!("setoption name {} value {}\n", option, value);
        self.send_command(cmd).await
    }
}

/// Engine evaluation info
#[derive(Debug, Clone, PartialEq)]
pub struct Evaluation {
    score: isize,
    mate: isize,
    depth: isize,
    nodes: isize,
    seldepth: isize,
    multipv: isize,
    pv: Vec<String>,
    time: isize,
}

impl Default for Evaluation {
    /// Create evaluation with empty values
    fn default() -> Self {
        Evaluation {
            score: 0,
            mate: 0,
            depth: 0,
            nodes: 0,
            seldepth: 0,
            multipv: 0,
            pv: vec![],
            time: 0,
        }
    }
}

impl Display for Evaluation {
    /// The alternate ("{:#}") operator will add the moves in pv to the output
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "score: {} mate: {} depth: {} nodes: {} seldepth: {} multipv: {} time: {}",
            self.score, self.mate, self.depth, self.nodes, self.seldepth, self.multipv, self.time
        ))?;
        if f.alternate() {
            f.write_fmt(format_args!("\npv: {}", self.pv.join(", ")))?;
        }
        Ok(())
    }
}

/// Posible engine states
#[derive(PartialEq, Debug)]
enum EngineStateEnum {
    Uninitialized,
    Initialized,
    Ready,
    Thinking,
}

#[derive(PartialEq, Debug, Clone)]
pub struct EngineOption {
    name: String,
    opt_type: OptionType,
}

/// Engine state handler with async stdout parsing
struct EngineState {
    state: Arc<Mutex<EngineStateEnum>>,
    evaluation: Arc<Mutex<Option<Evaluation>>>,
    options: Arc<Mutex<Vec<EngineOption>>>,
}

impl EngineState {
    async fn new(stdout: ChildStdout) -> Self {
        let ev = Arc::new(Mutex::new(None));
        let state = Arc::new(Mutex::new(EngineStateEnum::Uninitialized));
        let options = Arc::new(Mutex::new(Vec::new()));
        let stdout = BufReader::new(stdout);
        let engstate = EngineState {
            state: state.clone(),
            evaluation: ev.clone(),
            options: options.clone(),
        };
        tokio::spawn(async move {
            Self::process_stdout(stdout, state.clone(), ev.clone(), options.clone()).await
        });
        return engstate;
    }

    async fn process_stdout(
        mut stdout: BufReader<ChildStdout>,
        state: Arc<Mutex<EngineStateEnum>>,
        ev: Arc<Mutex<Option<Evaluation>>>,
        options: Arc<Mutex<Vec<EngineOption>>>,
    ) {
        loop {
            let mut str = String::new();
            stdout.read_line(&mut str).await.unwrap();
            match parse_uci(str) {
                Ok(UCI::UciOk) => {
                    let mut state = state.lock().expect("couldn't aquire state lock");
                    *state = EngineStateEnum::Initialized;
                }
                Ok(UCI::ReadyOk) => {
                    let mut state = state.lock().expect("couldn't aquire state lock");
                    *state = EngineStateEnum::Ready;
                }
                Ok(UCI::Info {
                    cp,
                    mate,
                    depth,
                    nodes,
                    seldepth,
                    time,
                    multipv,
                    pv,
                }) => {
                    let mut ev = ev.lock().expect("couldn't aquire ev lock");
                    let def_ev = Evaluation::default();
                    let prev_ev = match ev.as_ref() {
                        Some(ev) => ev,
                        None => &def_ev,
                    };
                    *ev = Some(Evaluation {
                        score: cp.unwrap_or(prev_ev.score),
                        mate: mate.unwrap_or(prev_ev.mate),
                        depth: depth.unwrap_or(prev_ev.depth),
                        nodes: nodes.unwrap_or(prev_ev.nodes),
                        seldepth: seldepth.unwrap_or(prev_ev.seldepth),
                        multipv: multipv.unwrap_or(prev_ev.multipv),
                        pv: pv.unwrap_or(prev_ev.pv.clone()),
                        time: time.unwrap_or(prev_ev.time),
                    });
                }
                Ok(UCI::Option { name, opt_type }) => {
                    let mut options = options.lock().expect("couldn't aquire options lock");
                    options.push(EngineOption { name, opt_type });
                }
                _ => continue,
            }
        }
    }
}

#[cfg(test)]
mod test {
    use anyhow::Result;

    use crate::engine::{ChessEngine, Engine};

    macro_rules! test_file {
        ($fname:expr) => {
            concat!(env!("CARGO_MANIFEST_DIR"), "/res/test/", $fname)
        };
    }

    #[tokio::test]
    async fn test_sf() -> Result<()> {
        let mut sf = Engine::new(test_file!("fakefish.sh")).await?;
        sf.start_uci().await?;
        Ok(())
    }
}