dealbreaker 1.4.0

A data-driven solver for patience / solitaire card games: describe a game's rules as data, get solutions or proofs of unsolvability.
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
//! Deal difficulty grading and game-level difficulty calibration.
//!
//! Grading operates at two complementary levels:
//!
//! * **Per-deal difficulty** (`Easy` / `Medium` / `Hard`): only solvable deals receive a
//!   difficulty. Unsolvable deals return [`DealGrade::Unsolvable`] and budget-exhausted deals
//!   return [`DealGrade::Unknown`] — neither carries a [`Difficulty`].
//!   When grading a batch with [`grade_batch`], solved deals are bucketed into Easy / Medium /
//!   Hard **relative to that game** using empirical tercile cutoffs, and those cutoffs are
//!   returned in [`GameDifficultySummary::cutoffs`] so future single deals can be graded
//!   consistently with [`grade`].
//! * **Overall game difficulty**: [`grade_batch`] also computes an **absolute** game-level
//!   difficulty across the full batch from both solvability rate and simulated-player win rate.
//!
//! Each solved deal's continuous difficulty score (`0.0..=1.0`, higher is harder) combines:
//! 1. **Simulated-player forgivingness** (primary): `1.0 - playout_win_rate` over fast,
//!    non-backtracking, noisy-greedy playouts that do not peek at face-down cards.
//! 2. **Solver effort** (secondary tie-breaker): log-scaled `states` visited by [`crate::solve`].

use std::sync::atomic::{AtomicBool, Ordering};

use crate::game::{Game, State};
use crate::solver::{run_playouts, solve, solve_with_cancel, Outcome, SolveOptions};

/// Difficulty tier for a solvable deal or an overall game.
#[derive(
    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Difficulty {
    Easy,
    Medium,
    Hard,
}

impl Difficulty {
    pub fn label(self) -> &'static str {
        match self {
            Difficulty::Easy => "easy",
            Difficulty::Medium => "medium",
            Difficulty::Hard => "hard",
        }
    }
}

impl std::fmt::Display for Difficulty {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.label())
    }
}

/// Thresholds mapping a continuous difficulty score (`0.0..=1.0`) to [`Difficulty`].
///
/// Scores `<= easy_max` map to [`Difficulty::Easy`]; scores `<= medium_max` map to
/// [`Difficulty::Medium`]; higher scores map to [`Difficulty::Hard`].
#[derive(Copy, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DifficultyCutoffs {
    pub easy_max: f32,
    pub medium_max: f32,
}

impl Default for DifficultyCutoffs {
    fn default() -> Self {
        DifficultyCutoffs {
            easy_max: 0.35,
            medium_max: 0.65,
        }
    }
}

impl DifficultyCutoffs {
    /// Construct cutoffs, clamping `medium_max >= easy_max` within `0.0..=1.0`.
    pub fn new(easy_max: f32, medium_max: f32) -> Self {
        let easy_max = easy_max.clamp(0.0, 1.0);
        let medium_max = medium_max.clamp(easy_max, 1.0);
        DifficultyCutoffs {
            easy_max,
            medium_max,
        }
    }

    /// Classify a continuous difficulty score into [`Difficulty`].
    pub fn classify(self, score: f32) -> Difficulty {
        if score <= self.easy_max {
            Difficulty::Easy
        } else if score <= self.medium_max {
            Difficulty::Medium
        } else {
            Difficulty::Hard
        }
    }
}

/// Grading settings for [`grade`] and [`grade_batch`].
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(default)]
#[non_exhaustive]
pub struct GradeOptions {
    /// Search options for the initial solvability solve.
    pub solve: SolveOptions,
    /// Number of fast non-peeking heuristic playouts per solved deal (default 24).
    /// Set to `0` to grade purely from solver effort.
    pub playouts: u32,
    /// RNG seed for deterministic playouts (default 0).
    pub seed: u64,
    /// Optional cutoffs for single-deal [`grade`]. Ignored by [`grade_batch`], which derives
    /// empirical per-game cutoffs from the batch itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cutoffs: Option<DifficultyCutoffs>,
}

impl Default for GradeOptions {
    fn default() -> Self {
        GradeOptions {
            solve: SolveOptions {
                shorten: false,
                ..SolveOptions::default()
            },
            playouts: 24,
            seed: 0,
            cutoffs: None,
        }
    }
}

impl GradeOptions {
    pub fn solve(mut self, opts: SolveOptions) -> Self {
        self.solve = opts;
        self
    }

    pub fn playouts(mut self, n: u32) -> Self {
        self.playouts = n;
        self
    }

    pub fn seed(mut self, seed: u64) -> Self {
        self.seed = seed;
        self
    }

    pub fn cutoffs(mut self, cutoffs: DifficultyCutoffs) -> Self {
        self.cutoffs = Some(cutoffs);
        self
    }
}

/// Diagnostic metrics for a solved deal.
#[derive(Copy, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DealMetrics {
    /// Continuous difficulty score in `0.0..=1.0` (higher is harder).
    pub score: f32,
    /// Fraction of simulated non-peeking playouts that won (`0.0..=1.0`), or `None` when
    /// `playouts == 0`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub playout_win_rate: Option<f32>,
    /// Number of simulated playouts that won.
    pub playout_wins: u32,
    /// Number of simulated playouts run.
    pub playouts: u32,
    /// Distinct positions visited by [`crate::solve`].
    pub states: u64,
    /// Length of the winning line in steps.
    pub steps: usize,
}

/// Outcome of grading a single deal.
///
/// Unsolvable and budget-exhausted deals never carry a [`Difficulty`].
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "status", rename_all = "snake_case")]
#[non_exhaustive]
pub enum DealGrade {
    /// The deal is solvable and has been graded.
    Solvable {
        difficulty: Difficulty,
        #[serde(flatten)]
        metrics: DealMetrics,
    },
    /// Every reachable position was searched: there is no win.
    Unsolvable { states: u64 },
    /// The solver hit its budget/timeout, or the game has no win condition.
    Unknown { states: u64 },
}

impl DealGrade {
    /// Returns the deal's difficulty if and only if it was proven solvable.
    pub fn difficulty(&self) -> Option<Difficulty> {
        match self {
            DealGrade::Solvable { difficulty, .. } => Some(*difficulty),
            DealGrade::Unsolvable { .. } | DealGrade::Unknown { .. } => None,
        }
    }

    /// Returns the metrics if and only if the deal was proven solvable.
    pub fn metrics(&self) -> Option<&DealMetrics> {
        match self {
            DealGrade::Solvable { metrics, .. } => Some(metrics),
            DealGrade::Unsolvable { .. } | DealGrade::Unknown { .. } => None,
        }
    }

    pub fn is_solvable(&self) -> bool {
        matches!(self, DealGrade::Solvable { .. })
    }

    pub fn is_unsolvable(&self) -> bool {
        matches!(self, DealGrade::Unsolvable { .. })
    }

    pub fn label(&self) -> &'static str {
        match self {
            DealGrade::Solvable { difficulty, .. } => difficulty.label(),
            DealGrade::Unsolvable { .. } => "unsolvable",
            DealGrade::Unknown { .. } => "unknown",
        }
    }
}

/// Overall absolute difficulty summary for a game, derived from a batch of deals.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct GameDifficultySummary {
    /// Total deals evaluated.
    pub deals: usize,
    /// Deals proven solvable.
    pub solved: usize,
    /// Deals proven unsolvable.
    pub unsolvable: usize,
    /// Deals where the solver hit its budget/timeout (or game has no win condition).
    pub unknown: usize,
    /// Lower bound on solvability rate: `solved / deals`.
    pub solvability_rate: f32,
    /// Upper bound on solvability rate: `(solved + unknown) / deals`.
    pub solvability_rate_max: f32,
    /// Mean simulated-player win rate across solved deals (`None` if no solved deals or
    /// `playouts == 0`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mean_playout_win_rate: Option<f32>,
    /// Expected simulated-player win rate on a random deal
    /// (`solvability_rate * mean_playout_win_rate`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub overall_win_rate: Option<f32>,
    /// Median solver states across solved deals.
    pub median_states: u64,
    /// Interquartile range (`p75 - p25`) of deal scores across solved deals.
    pub score_iqr: f32,
    /// Empirical cutoffs used to bucket solved deals into Easy / Medium / Hard.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cutoffs: Option<DifficultyCutoffs>,
    /// Overall absolute difficulty score for the game (`0.0..=1.0`, higher is harder).
    pub game_score: f32,
    /// Overall absolute difficulty tier for the game (`None` if `deals == 0`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub game_difficulty: Option<Difficulty>,
    /// Solved deals classified as Easy (relative to this game).
    pub easy: usize,
    /// Solved deals classified as Medium (relative to this game).
    pub medium: usize,
    /// Solved deals classified as Hard (relative to this game).
    pub hard: usize,
}

/// Result of [`grade_batch`]: per-deal grades (relative to this game) and overall game summary.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct BatchGrade {
    pub summary: GameDifficultySummary,
    pub deals: Vec<DealGrade>,
}

/// Effort score in `0.0..=1.0` from visited solver states (log10 scale: 1 -> 0.0, 1M -> 1.0).
fn effort_score(states: u64) -> f32 {
    ((states.max(1) as f64).log10() / 6.0).clamp(0.0, 1.0) as f32
}

/// Continuous difficulty score in `0.0..=1.0` for a solved deal.
fn deal_score(states: u64, playout_wins: u32, playouts: u32) -> f32 {
    let effort = effort_score(states);
    if playouts == 0 {
        effort
    } else {
        let fail_rate = 1.0 - (playout_wins as f32 / playouts as f32);
        (0.75 * fail_rate + 0.25 * effort).clamp(0.0, 1.0)
    }
}

/// Grade a single deal.
///
/// Unsolvable deals return [`DealGrade::Unsolvable`] without a [`Difficulty`].
/// Budget-exhausted deals (or scored games with no win target) return [`DealGrade::Unknown`].
pub fn grade(game: &Game, state: &State, opts: &GradeOptions) -> DealGrade {
    grade_inner(game, state, opts, None)
}

/// Like [`grade`], stopping early with [`DealGrade::Unknown`] if `cancel` becomes `true`.
pub fn grade_with_cancel(
    game: &Game,
    state: &State,
    opts: &GradeOptions,
    cancel: &AtomicBool,
) -> DealGrade {
    grade_inner(game, state, opts, Some(cancel))
}

fn grade_inner(
    game: &Game,
    state: &State,
    opts: &GradeOptions,
    cancel: Option<&AtomicBool>,
) -> DealGrade {
    if game.is_scored() && game.target_score().is_none() {
        return DealGrade::Unknown { states: 0 };
    }
    if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
        return DealGrade::Unknown { states: 0 };
    }
    let res = match cancel {
        Some(c) => solve_with_cancel(game, state, &opts.solve, c),
        None => solve(game, state, &opts.solve),
    };
    match res.outcome {
        Outcome::Unsolvable => DealGrade::Unsolvable { states: res.states },
        Outcome::GaveUp => DealGrade::Unknown { states: res.states },
        Outcome::Solved(moves) => {
            if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                return DealGrade::Unknown { states: res.states };
            }
            let steps = game.steps(state, &moves).len();
            let playout_wins = run_playouts(game, state, opts.playouts, opts.seed, cancel);
            if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                return DealGrade::Unknown { states: res.states };
            }
            let score = deal_score(res.states, playout_wins, opts.playouts);
            let playout_win_rate =
                (opts.playouts > 0).then(|| playout_wins as f32 / opts.playouts as f32);
            let cutoffs = opts.cutoffs.unwrap_or_default();
            DealGrade::Solvable {
                difficulty: cutoffs.classify(score),
                metrics: DealMetrics {
                    score,
                    playout_win_rate,
                    playout_wins,
                    playouts: opts.playouts,
                    states: res.states,
                    steps,
                },
            }
        }
    }
}

/// Absolute thresholds mapping a game's overall `game_score` (`0.0..=1.0`) to
/// [`Difficulty`]: `<= 0.55` is Easy (e.g. FreeCell, Spider 1-suit), `<= 0.78` is Medium
/// (e.g. Klondike Draw-1, Baker's Dozen), and `> 0.78` is Hard (e.g. Klondike Draw-3,
/// Forty Thieves, Spider 4-suit).
const GAME_DIFFICULTY_CUTOFFS: DifficultyCutoffs = DifficultyCutoffs {
    easy_max: 0.55,
    medium_max: 0.78,
};

/// Linear-interpolated quantile over a non-empty sorted slice (`p` in `0.0..=1.0`).
fn quantile(sorted: &[f32], p: f32) -> f32 {
    debug_assert!(!sorted.is_empty());
    if sorted.len() == 1 {
        return sorted[0];
    }
    let pos = p.clamp(0.0, 1.0) * (sorted.len() - 1) as f32;
    let lo = pos.floor() as usize;
    let hi = pos.ceil() as usize;
    let frac = pos - lo as f32;
    sorted[lo] * (1.0 - frac) + sorted[hi] * frac
}

/// Grade a batch of deals for a game, bucketing solvable deals into Easy / Medium / Hard
/// **relative to this game** (empirical terciles) and computing an **absolute** game-level
/// difficulty summary.
///
/// Unsolvable and unknown deals are excluded from the quantile buckets and never carry a
/// [`Difficulty`].
pub fn grade_batch(game: &Game, states: &[State], opts: &GradeOptions) -> BatchGrade {
    grade_batch_inner(game, states, opts, None)
}

/// Like [`grade_batch`], stopping early if `cancel` becomes `true`.
pub fn grade_batch_with_cancel(
    game: &Game,
    states: &[State],
    opts: &GradeOptions,
    cancel: &AtomicBool,
) -> BatchGrade {
    grade_batch_inner(game, states, opts, Some(cancel))
}

fn grade_batch_inner(
    game: &Game,
    states: &[State],
    opts: &GradeOptions,
    cancel: Option<&AtomicBool>,
) -> BatchGrade {
    let raw: Vec<DealGrade> = {
        #[cfg(feature = "parallel")]
        {
            use rayon::prelude::*;
            states
                .par_iter()
                .enumerate()
                .map(|(i, st)| {
                    let mut per = opts.clone();
                    per.seed = opts.seed.wrapping_add(i as u64);
                    grade_inner(game, st, &per, cancel)
                })
                .collect()
        }
        #[cfg(not(feature = "parallel"))]
        {
            states
                .iter()
                .enumerate()
                .map(|(i, st)| {
                    let mut per = opts.clone();
                    per.seed = opts.seed.wrapping_add(i as u64);
                    grade_inner(game, st, &per, cancel)
                })
                .collect()
        }
    };
    finalize_batch(raw)
}

/// Re-bucket a collection of raw [`DealGrade`]s using empirical per-game terciles and compute
/// the overall [`GameDifficultySummary`].
pub fn finalize_batch(mut deals: Vec<DealGrade>) -> BatchGrade {
    let total = deals.len();
    let mut solved = 0usize;
    let mut unsolvable = 0usize;
    let mut unknown = 0usize;
    let mut scores: Vec<f32> = Vec::new();
    let mut solve_states: Vec<u64> = Vec::new();
    let mut playout_rate_sum = 0.0f64;
    let mut playout_rate_count = 0usize;

    for g in &deals {
        match g {
            DealGrade::Solvable { metrics, .. } => {
                solved += 1;
                scores.push(metrics.score);
                solve_states.push(metrics.states);
                if let Some(wr) = metrics.playout_win_rate {
                    playout_rate_sum += wr as f64;
                    playout_rate_count += 1;
                }
            }
            DealGrade::Unsolvable { .. } => unsolvable += 1,
            DealGrade::Unknown { .. } => unknown += 1,
        }
    }

    scores.sort_by(|a, b| a.total_cmp(b));
    solve_states.sort_unstable();

    let median_states = if solve_states.is_empty() {
        0
    } else {
        let mid = solve_states.len() / 2;
        if solve_states.len() % 2 == 1 {
            solve_states[mid]
        } else {
            solve_states[mid - 1].saturating_add(solve_states[mid]) / 2
        }
    };

    let (cutoffs, score_iqr) = if scores.is_empty() {
        (None, 0.0)
    } else {
        let q25 = quantile(&scores, 0.25);
        let q75 = quantile(&scores, 0.75);
        let iqr = (q75 - q25).max(0.0);
        let spread = scores[scores.len() - 1] - scores[0];
        let cut = if spread < 1e-4 {
            // Flat game with virtually identical deal scores: fall back to absolute cutoffs
            // instead of inventing arbitrary Easy/Medium/Hard splits.
            DifficultyCutoffs::default()
        } else {
            DifficultyCutoffs::new(quantile(&scores, 1.0 / 3.0), quantile(&scores, 2.0 / 3.0))
        };
        (Some(cut), iqr)
    };

    let (mut easy, mut medium, mut hard) = (0usize, 0usize, 0usize);
    if let Some(cut) = cutoffs {
        for g in &mut deals {
            if let DealGrade::Solvable {
                difficulty,
                metrics,
            } = g
            {
                let d = cut.classify(metrics.score);
                *difficulty = d;
                match d {
                    Difficulty::Easy => easy += 1,
                    Difficulty::Medium => medium += 1,
                    Difficulty::Hard => hard += 1,
                }
            }
        }
    }

    let solvability_rate = if total == 0 {
        0.0
    } else {
        solved as f32 / total as f32
    };
    let solvability_rate_max = if total == 0 {
        0.0
    } else {
        (solved + unknown) as f32 / total as f32
    };
    let mean_playout_win_rate =
        (playout_rate_count > 0).then(|| (playout_rate_sum / playout_rate_count as f64) as f32);
    let overall_win_rate = mean_playout_win_rate.map(|wr| solvability_rate * wr);

    let median_effort = effort_score(median_states);
    let game_score = if total == 0 {
        0.0
    } else if let Some(owr) = overall_win_rate {
        (0.80 * (1.0 - owr) + 0.20 * median_effort).clamp(0.0, 1.0)
    } else {
        (0.70 * (1.0 - solvability_rate) + 0.30 * median_effort).clamp(0.0, 1.0)
    };
    let game_difficulty = (total > 0).then(|| GAME_DIFFICULTY_CUTOFFS.classify(game_score));

    BatchGrade {
        summary: GameDifficultySummary {
            deals: total,
            solved,
            unsolvable,
            unknown,
            solvability_rate,
            solvability_rate_max,
            mean_playout_win_rate,
            overall_win_rate,
            median_states,
            score_iqr,
            cutoffs,
            game_score,
            game_difficulty,
            easy,
            medium,
            hard,
        },
        deals,
    }
}

/// Options for [`find_deal`] and [`find_deal_with_cancel`].
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(default)]
#[non_exhaustive]
pub struct FindDealOptions {
    /// First seed to try (default: 1).
    pub start_seed: u64,
    /// Maximum number of seeds to try before giving up (default: 100).
    pub max_attempts: u32,
    /// Required difficulty tier. `None` matches any solvable deal (and skips playouts unless
    /// `compute_grade` is `true`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub difficulty: Option<Difficulty>,
    /// Grading options used when `difficulty` is `Some` or `compute_grade` is `true`
    /// (also supplies `grade.solve` for solvability checks).
    pub grade: GradeOptions,
    /// Compute a full [`DealGrade`] even when `difficulty` is `None` (default: false).
    pub compute_grade: bool,
    /// Include the winning line of steps in [`FoundDeal::steps`] (default: false).
    pub include_solution: bool,
}

impl Default for FindDealOptions {
    fn default() -> Self {
        FindDealOptions {
            start_seed: 1,
            max_attempts: 100,
            difficulty: None,
            grade: GradeOptions::default(),
            compute_grade: false,
            include_solution: false,
        }
    }
}

impl FindDealOptions {
    pub fn start_seed(mut self, seed: u64) -> Self {
        self.start_seed = seed;
        self
    }

    pub fn max_attempts(mut self, n: u32) -> Self {
        self.max_attempts = n;
        self
    }

    pub fn difficulty(mut self, d: Difficulty) -> Self {
        self.difficulty = Some(d);
        self
    }

    pub fn grade(mut self, opts: GradeOptions) -> Self {
        self.grade = opts;
        self
    }

    pub fn compute_grade(mut self, on: bool) -> Self {
        self.compute_grade = on;
        self
    }

    pub fn include_solution(mut self, on: bool) -> Self {
        self.include_solution = on;
        self
    }
}

/// A deal found by [`find_deal`] matching the requested solvability / difficulty criteria.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct FoundDeal {
    /// Seed that produced this deal.
    pub seed: u64,
    /// Initial position of the found deal.
    pub state: crate::StateData,
    /// Number of seeds tried (1 = first seed matched).
    pub attempts: u32,
    /// Deal grade, populated when `difficulty` was requested or `compute_grade` was `true`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grade: Option<DealGrade>,
    /// Winning steps, populated when `include_solution` was `true`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub steps: Option<Vec<crate::Step>>,
}

/// Search sequentially from `opts.start_seed` for a solvable deal (optionally matching a target
/// [`Difficulty`]). Returns `None` if no matching deal is found within `opts.max_attempts`.
pub fn find_deal(game: &Game, opts: &FindDealOptions) -> Option<FoundDeal> {
    find_deal_inner(game, opts, None)
}

/// Like [`find_deal`], stopping early with `None` if `cancel` becomes `true`.
pub fn find_deal_with_cancel(
    game: &Game,
    opts: &FindDealOptions,
    cancel: &AtomicBool,
) -> Option<FoundDeal> {
    find_deal_inner(game, opts, Some(cancel))
}

fn find_deal_inner(
    game: &Game,
    opts: &FindDealOptions,
    cancel: Option<&AtomicBool>,
) -> Option<FoundDeal> {
    if game.is_scored() && game.target_score().is_none() {
        return None;
    }
    let need_grade = opts.difficulty.is_some() || opts.compute_grade;
    let mut solve_opts = opts.grade.solve.clone();
    if !opts.include_solution {
        solve_opts.shorten = false;
    }
    for attempt in 0..opts.max_attempts {
        if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
            return None;
        }
        let seed = opts.start_seed.wrapping_add(attempt as u64);
        let state = game.deal(seed);
        let res = match cancel {
            Some(c) => solve_with_cancel(game, &state, &solve_opts, c),
            None => solve(game, &state, &solve_opts),
        };
        let Outcome::Solved(moves) = res.outcome else {
            continue;
        };
        if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
            return None;
        }
        let mut deal_grade = None;
        if need_grade {
            let step_count = game.steps(&state, &moves).len();
            let playout_seed = opts.grade.seed.wrapping_add(seed);
            let playout_wins =
                run_playouts(game, &state, opts.grade.playouts, playout_seed, cancel);
            if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                return None;
            }
            let score = deal_score(res.states, playout_wins, opts.grade.playouts);
            let playout_win_rate =
                (opts.grade.playouts > 0).then(|| playout_wins as f32 / opts.grade.playouts as f32);
            let cutoffs = opts.grade.cutoffs.unwrap_or_default();
            let difficulty = cutoffs.classify(score);
            if let Some(want) = opts.difficulty {
                if difficulty != want {
                    continue;
                }
            }
            deal_grade = Some(DealGrade::Solvable {
                difficulty,
                metrics: DealMetrics {
                    score,
                    playout_win_rate,
                    playout_wins,
                    playouts: opts.grade.playouts,
                    states: res.states,
                    steps: step_count,
                },
            });
        }
        let steps = opts.include_solution.then(|| game.steps(&state, &moves));
        return Some(FoundDeal {
            seed,
            state: game.state_to_data(&state),
            attempts: attempt + 1,
            grade: deal_grade,
            steps,
        });
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{microsoft_deal, presets};

    #[test]
    fn unsolvable_and_gave_up_have_no_difficulty() {
        let fc = Game::new(presets::freecell()).unwrap();

        // MS #11982 is famously unsolvable.
        let unsolvable_deal = fc.deal_ordered(&microsoft_deal(11982)).unwrap();
        let g = grade(
            &fc,
            &unsolvable_deal,
            &GradeOptions::default()
                .solve(SolveOptions::default().max_states(500_000))
                .playouts(4),
        );
        assert!(g.is_unsolvable(), "expected unsolvable, got {g:?}");
        assert_eq!(g.difficulty(), None);
        assert_eq!(g.metrics(), None);
        let json = serde_json::to_string(&g).unwrap();
        assert!(json.contains("\"status\":\"unsolvable\""), "{json}");
        assert!(!json.contains("difficulty"), "{json}");

        // Tiny budget produces Unknown with no difficulty.
        let solvable_deal = fc.deal_ordered(&microsoft_deal(1)).unwrap();
        let unk = grade(
            &fc,
            &solvable_deal,
            &GradeOptions::default()
                .solve(SolveOptions::default().max_states(1))
                .playouts(4),
        );
        assert!(matches!(unk, DealGrade::Unknown { .. }), "{unk:?}");
        assert_eq!(unk.difficulty(), None);
        let ujson = serde_json::to_string(&unk).unwrap();
        assert!(ujson.contains("\"status\":\"unknown\""), "{ujson}");
        assert!(!ujson.contains("difficulty"), "{ujson}");
    }

    #[test]
    fn solvable_deal_is_graded_deterministically() {
        let fc = Game::new(presets::freecell()).unwrap();
        let deal = fc.deal_ordered(&microsoft_deal(1)).unwrap();
        let opts = GradeOptions::default()
            .solve(SolveOptions::default().max_states(200_000))
            .playouts(8)
            .seed(42);
        let g1 = grade(&fc, &deal, &opts);
        let g2 = grade(&fc, &deal, &opts);
        assert_eq!(g1, g2);
        assert!(g1.is_solvable());
        assert!(g1.difficulty().is_some());
        let m = g1.metrics().unwrap();
        assert!((0.0..=1.0).contains(&m.score));
        assert_eq!(m.playouts, 8);
        assert!(m.playout_win_rate.is_some());
        assert!(m.steps > 0);
    }

    #[test]
    fn scored_game_with_target_is_graded() {
        let ps = Game::new(presets::poker_squares()).unwrap();
        let deal = ps.deal(1);
        let g = grade(
            &ps,
            &deal,
            &GradeOptions::default()
                .solve(SolveOptions::default().max_states(50_000))
                .playouts(8),
        );
        assert!(
            g.is_solvable(),
            "expected poker squares seed 1 to solve: {g:?}"
        );
        assert!(g.difficulty().is_some());
    }

    #[test]
    fn batch_grading_excludes_unsolvable_and_computes_summary() {
        let g = Game::new(presets::golf()).unwrap();
        let deals: Vec<State> = (1..=15).map(|s| g.deal(s)).collect();
        let opts = GradeOptions::default()
            .solve(SolveOptions::default().max_states(100_000))
            .playouts(12)
            .seed(7);
        let batch = grade_batch(&g, &deals, &opts);
        assert_eq!(batch.deals.len(), 15);
        assert_eq!(batch.summary.deals, 15);
        assert_eq!(
            batch.summary.solved + batch.summary.unsolvable + batch.summary.unknown,
            15
        );
        assert_eq!(
            batch.summary.easy + batch.summary.medium + batch.summary.hard,
            batch.summary.solved
        );
        assert!(batch.summary.game_difficulty.is_some());
        for d in &batch.deals {
            if d.is_unsolvable() {
                assert_eq!(d.difficulty(), None);
            }
        }
    }

    #[test]
    fn find_deal_solvable_and_difficulty_targeted() {
        let fc = Game::new(presets::freecell()).unwrap();
        let found = find_deal(
            &fc,
            &FindDealOptions::default()
                .start_seed(1)
                .max_attempts(10)
                .include_solution(true),
        )
        .expect("freecell should find a solvable deal quickly");
        assert_eq!(found.seed, 1);
        assert_eq!(found.attempts, 1);
        assert!(found.grade.is_none());
        let steps = found.steps.as_ref().expect("solution requested");
        let mut s = fc.state_from_data(&found.state).unwrap();
        for st in steps {
            fc.play_step(&mut s, st).unwrap();
        }
        assert!(fc.is_won(&s));

        // Difficulty-targeted deal with grading enabled.
        let easy = find_deal(
            &fc,
            &FindDealOptions::default()
                .start_seed(1)
                .max_attempts(20)
                .difficulty(Difficulty::Easy)
                .grade(
                    GradeOptions::default()
                        .playouts(8)
                        .cutoffs(DifficultyCutoffs::new(0.8, 0.95)),
                ),
        )
        .expect("should find an easy deal with generous cutoff");
        assert_eq!(
            easy.grade.as_ref().and_then(DealGrade::difficulty),
            Some(Difficulty::Easy)
        );

        // Pre-triggered cancel returns None immediately.
        let cancel = AtomicBool::new(true);
        assert!(find_deal_with_cancel(&fc, &FindDealOptions::default(), &cancel).is_none());
    }
}