rustoku-lib 0.15.0

Lightning-fast Sudoku solving and generation
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
//! Core module for the Rustoku solver and generator.
//!
//! This module includes the `Rustoku` struct for representing and solving Sudoku puzzles using
//! backtracking and Minimum Remaining Values (MRV). It provides functionality for solving
//! puzzles and checking solutions.
//!
//! This module also includes a function to generate new Sudoku puzzles with a specified
//! number of clues, ensuring that the generated puzzle has a unique solution.

mod board;
mod candidates;
mod masks;
mod solution;
mod techniques;

pub use board::Board;
pub use candidates::Candidates;
pub use masks::Masks;
pub use solution::{Solution, SolvePath, SolveStep};
pub use techniques::flags::{Difficulty, TechniqueFlags};

use crate::error::RustokuError;
use rand::prelude::SliceRandom;
use rand::rng;
use std::collections::HashSet;
use techniques::TechniquePropagator;

/// Represents the type of symmetry to apply during board generation.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub enum Symmetry {
    /// No symmetry (clues placed randomly).
    #[default]
    None,
    /// 180-degree rotational (point) symmetry.
    Rotational180,
    /// 90-degree rotational symmetry.
    Rotational90,
    /// Mirror symmetry across the vertical center line.
    MirrorVertical,
    /// Mirror symmetry across the horizontal center line.
    MirrorHorizontal,
    /// Mirror symmetry across the main diagonal (top-left to bottom-right).
    MirrorDiagonal,
}

impl Symmetry {
    /// Returns the symmetric partners for a given cell (r, c).
    pub fn get_partners(&self, r: usize, c: usize) -> Vec<(usize, usize)> {
        let mut partners = HashSet::new();
        partners.insert((r, c));

        match self {
            Symmetry::None => {}
            Symmetry::Rotational180 => {
                partners.insert((8 - r, 8 - c));
            }
            Symmetry::Rotational90 => {
                partners.insert((c, 8 - r));
                partners.insert((8 - r, 8 - c));
                partners.insert((8 - c, r));
            }
            Symmetry::MirrorVertical => {
                partners.insert((r, 8 - c));
            }
            Symmetry::MirrorHorizontal => {
                partners.insert((8 - r, c));
            }
            Symmetry::MirrorDiagonal => {
                partners.insert((c, r));
            }
        }

        partners.into_iter().collect()
    }
}

/// A builder for generating Sudoku puzzles with various constraints and properties.
///
/// `BoardGenerator` provides a unified interface for creating puzzles with specific
/// clue counts, symmetry types, and difficulty levels.
///
/// # Example
///
/// ```
/// use rustoku_lib::{BoardGenerator, Symmetry};
///
/// let board = BoardGenerator::new()
///     .clues(25)
///     .symmetry(Symmetry::Rotational180)
///     .generate();
///
/// assert!(board.is_ok());
/// ```
#[derive(Debug, Clone, Copy)]
pub struct BoardGenerator {
    num_clues: usize,
    symmetry: Symmetry,
    difficulty: Option<Difficulty>,
    max_attempts: usize,
}

impl Default for BoardGenerator {
    fn default() -> Self {
        Self {
            num_clues: 30,
            symmetry: Symmetry::None,
            difficulty: None,
            max_attempts: 1,
        }
    }
}

impl BoardGenerator {
    /// Creates a new `BoardGenerator` with default settings (30 clues, no symmetry).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the target number of clues for the generated puzzle.
    pub fn clues(mut self, num_clues: usize) -> Self {
        self.num_clues = num_clues;
        self
    }

    /// Sets the type of symmetry to apply to the generated puzzle.
    pub fn symmetry(mut self, symmetry: Symmetry) -> Self {
        self.symmetry = symmetry;
        self
    }

    /// Sets the target difficulty for the generated puzzle.
    ///
    /// If a difficulty is set, the generator will attempt to find a puzzle
    /// of that exact difficulty by repeatedly generating candidates.
    pub fn difficulty(mut self, difficulty: Difficulty) -> Self {
        self.difficulty = Some(difficulty);
        self
    }

    /// Sets the maximum number of attempts when generating a puzzle with a specific difficulty.
    pub fn max_attempts(mut self, max_attempts: usize) -> Self {
        self.max_attempts = max_attempts;
        self
    }

    /// Generates a new Sudoku puzzle based on the current configuration.
    pub fn generate(&self) -> Result<Board, RustokuError> {
        if let Some(target_difficulty) = self.difficulty {
            self.generate_with_difficulty(target_difficulty)
        } else {
            self.generate_single()
        }
    }

    fn generate_single(&self) -> Result<Board, RustokuError> {
        if !(17..=81).contains(&self.num_clues) {
            return Err(RustokuError::InvalidClueCount);
        }

        // Start with a fully solved board
        let mut rustoku = Rustoku::new(Board::default())?;
        let solution = rustoku.solve_any().ok_or(RustokuError::DuplicateValues)?;
        let mut board = solution.board;

        // Collect all unique symmetric groups
        let mut visited = [[false; 9]; 9];
        let mut groups = Vec::new();

        // Iterate in a deterministic but shuffled order to ensure variety
        let mut cells: Vec<(usize, usize)> = board.iter_cells().collect();
        cells.shuffle(&mut rng());

        for (r, c) in cells {
            if !visited[r][c] {
                let partners = self.symmetry.get_partners(r, c);
                for &(pr, pc) in &partners {
                    visited[pr][pc] = true;
                }
                groups.push(partners);
            }
        }

        // Re-shuffle groups to ensure we don't always try to remove the same regions first
        groups.shuffle(&mut rng());

        let mut clues = 81;

        // Remove numbers while maintaining a unique solution
        for group in groups {
            if clues <= self.num_clues {
                break;
            }

            // Potential clues to remove (only those currently filled)
            let mut group_clues = Vec::new();
            for &(r, c) in &group {
                let val = board.cells[r][c];
                if val != 0 {
                    group_clues.push((r, c, val));
                }
            }

            if group_clues.is_empty() {
                continue;
            }

            // Temporarily remove the entire group
            for &(r, c, _) in &group_clues {
                board.cells[r][c] = 0;
            }

            if Rustoku::new(board)?.solve_until(2).len() != 1 {
                // Restore if not unique
                for &(r, c, val) in &group_clues {
                    board.cells[r][c] = val;
                }
            } else {
                clues -= group_clues.len();
            }
        }

        // Final safety check
        if Rustoku::new(board)?.solve_until(2).len() != 1 {
            return Err(RustokuError::GenerateFailure);
        }

        Ok(board)
    }

    fn generate_with_difficulty(
        &self,
        target_difficulty: Difficulty,
    ) -> Result<Board, RustokuError> {
        use rand::RngExt;

        for _ in 0..self.max_attempts {
            // Ignore num_clues if difficulty is set, and use a range appropriate for the level
            let clues = match target_difficulty {
                Difficulty::Easy => rand::rng().random_range(34..=42),
                Difficulty::Medium => rand::rng().random_range(28..=34),
                Difficulty::Hard => rand::rng().random_range(22..=28),
                Difficulty::Expert => rand::rng().random_range(17..=22),
            };

            // Generate a uniquely solvable board with symmetry
            let mut sub_generator = *self;
            sub_generator.num_clues = clues;
            sub_generator.difficulty = None; // Avoid recursion

            if let Ok(board) = sub_generator.generate_single() {
                let mut rustoku = Rustoku::builder()
                    .board(board)
                    .techniques(TechniqueFlags::all())
                    .build()?;

                // Check if human techniques can fully solve the board
                let solutions = rustoku.solve_all();
                if solutions.len() == 1 {
                    let solution = &solutions[0];

                    // Inspect the solve path to find the highest difficulty technique used
                    let mut max_difficulty = Difficulty::Easy;
                    let mut required_guessing = false;

                    for step in &solution.solve_path.steps {
                        match step {
                            SolveStep::Placement { flags, .. } => {
                                if flags.is_empty() {
                                    required_guessing = true;
                                    break;
                                }
                                let step_diff = flags.difficulty();
                                if step_diff > max_difficulty {
                                    max_difficulty = step_diff;
                                }
                            }
                            SolveStep::CandidateElimination { flags, .. } => {
                                if !flags.is_empty() {
                                    let step_diff = flags.difficulty();
                                    if step_diff > max_difficulty {
                                        max_difficulty = step_diff;
                                    }
                                }
                            }
                        }
                    }

                    if !required_guessing && max_difficulty == target_difficulty {
                        return Ok(board);
                    }
                }
            }
        }

        Err(RustokuError::GenerateFailure)
    }
}

/// Solver primitive that uses backtracking and bitmasking for constraints.
///
/// This struct supports the ability to:
/// - Initialize from a 2D array, a flat byte array, or a string representation
/// - Solve a Sudoku puzzle using backtracking with Minimum Remaining Values (MRV)
/// - Generate a Sudoku puzzle with a unique solution based on the number of clues specified
/// - Check if a Sudoku puzzle is solved correctly
///
/// # Examples
///
/// Solve a Sudoku puzzle:
/// ```
/// use rustoku_lib::Rustoku;
/// let puzzle = "530070000600195000098000060800060003400803001700020006060000280000419005000080079";
/// let mut rustoku = Rustoku::new_from_str(puzzle).unwrap();
/// assert!(rustoku.solve_any().is_some());
/// ```
///
/// Generate a Sudoku puzzle:
/// ```
/// use rustoku_lib::{Rustoku, generate_board};
/// let board = generate_board(30).unwrap();
/// let solution = Rustoku::new(board).unwrap().solve_all();
/// assert_eq!(solution.len(), 1);
/// ```
///
/// Check if a Sudoku puzzle is solved:
/// ```
/// use rustoku_lib::Rustoku;
/// let puzzle = "534678912672195348198342567859761423426853791713924856961537284287419635345286179";
/// let rustoku = Rustoku::new_from_str(puzzle).unwrap();
/// assert!(rustoku.is_solved());
/// ```
#[derive(Debug, Copy, Clone)]
pub struct Rustoku {
    /// The current state of the Sudoku board.
    pub board: Board,
    /// Bitmasks that check if a cell is safe in a row, column and box.
    pub masks: Masks,
    /// Candidate cache from computing the bitmasks.
    pub candidates: Candidates,
    /// Techniques used during the initial phase of solving.
    pub techniques: TechniqueFlags,
}

impl Rustoku {
    /// Constructs a new `Rustoku` instance from an initial `Board`.
    pub fn new(initial_board: Board) -> Result<Self, RustokuError> {
        let board = initial_board; // Now takes a Board directly
        let mut masks = Masks::new();
        let mut candidates = Candidates::new();

        // Initialize masks and check for duplicates based on the provided board
        for r in 0..9 {
            for c in 0..9 {
                let num = board.get(r, c);
                if num != 0 {
                    if !masks.is_safe(r, c, num) {
                        return Err(RustokuError::DuplicateValues);
                    }
                    masks.add_number(r, c, num);
                }
            }
        }

        // Initialize the candidates cache for empty cells based on initial masks and board
        for r in 0..9 {
            for c in 0..9 {
                if board.is_empty(r, c) {
                    candidates.set(r, c, masks.compute_candidates_mask_for_cell(r, c));
                }
            }
        }

        Ok(Self {
            board,
            masks,
            candidates,
            techniques: TechniqueFlags::EASY, // Default
        })
    }

    /// Start building a configured `Rustoku` via a builder pattern.
    pub fn builder() -> RustokuBuilder {
        RustokuBuilder::new()
    }

    /// Constructs a new `Rustoku` instance from a string representation of the board.
    pub fn new_from_str(s: &str) -> Result<Self, RustokuError> {
        let board = Board::try_from(s)?;
        Self::new(board)
    }

    /// Returns the existing Rustoku instance, with modified techniques.
    pub fn with_techniques(mut self, techniques: TechniqueFlags) -> Self {
        self.techniques = techniques;
        self
    }

    pub(crate) fn candidate_grid_snapshot(&self) -> Vec<Vec<Vec<u8>>> {
        (0..9)
            .map(|r| {
                (0..9)
                    .map(|c| {
                        if self.board.get(r, c) != 0 {
                            vec![]
                        } else {
                            self.candidates.get_candidates(r, c)
                        }
                    })
                    .collect()
            })
            .collect()
    }

    pub(crate) fn apply_trace_step(&mut self, step: &SolveStep) {
        match *step {
            SolveStep::Placement {
                row, col, value, ..
            } => {
                self.place_number(row, col, value);
            }
            SolveStep::CandidateElimination {
                row, col, value, ..
            } => {
                let initial_mask = self.candidates.get(row, col);
                let refined_mask = initial_mask & !(1 << (value - 1));
                self.candidates.set(row, col, refined_mask);
            }
        }
    }

    /// Extracts candidate numbers (1-9) from a bitmask into a Vec.
    fn candidates_from_mask(mask: u16) -> Vec<u8> {
        let mut nums = Vec::with_capacity(mask.count_ones() as usize);
        for v in 1..=9u8 {
            if mask & (1 << (v - 1)) != 0 {
                nums.push(v);
            }
        }
        nums
    }

    /// Helper for solver to find the next empty cell (MRV).
    #[inline]
    fn find_next_empty_cell(&self) -> Option<(usize, usize)> {
        let mut min = (10, None); // Min candidates, (r, c)
        for (r, c) in self.board.iter_empty_cells() {
            let count = self.candidates.get(r, c).count_ones() as u8;
            if count < min.0 {
                min = (count, Some((r, c)));
                if count == 1 {
                    return min.1;
                }
            }
        }
        min.1
    }

    /// Place and remove operations for the solver, updated to use the new structs.
    #[inline]
    fn place_number(&mut self, r: usize, c: usize, num: u8) {
        self.board.set(r, c, num);
        self.masks.add_number(r, c, num);
        self.candidates
            .update_affected_cells_for(r, c, &self.masks, &self.board, Some(num));
    }

    /// Remove a number from the board and update masks and candidates.
    #[inline]
    fn remove_number(&mut self, r: usize, c: usize, num: u8) {
        self.board.set(r, c, 0); // Set back to empty
        self.masks.remove_number(r, c, num);
        self.candidates
            .update_affected_cells(r, c, &self.masks, &self.board);
        // Note: `update_affected_cells` will recalculate candidates for the removed cell.
    }

    /// Recursive function to solve the Sudoku puzzle with backtracking.
    fn solve_until_recursive(
        &mut self,
        solutions: &mut Vec<Solution>,
        path: &mut SolvePath,
        bound: usize,
    ) -> usize {
        // Early return for base case: no empty cells means puzzle is solved
        let Some((r, c)) = self.find_next_empty_cell() else {
            solutions.push(Solution {
                board: self.board,
                solve_path: path.clone(),
            });
            return 1;
        };

        let mut count = 0;
        // Use the candidate cache to only iterate valid candidates
        let mask = self.candidates.get(r, c);
        let mut nums = Self::candidates_from_mask(mask);
        nums.shuffle(&mut rng());

        for &num in &nums {
            if !self.masks.is_safe(r, c, num) {
                continue;
            }

            self.place_number(r, c, num);
            let step_number = path.steps.len() as u32;
            path.steps.push(SolveStep::Placement {
                row: r,
                col: c,
                value: num,
                flags: TechniqueFlags::empty(),
                step_number,
                candidates_eliminated: 0,
                related_cell_count: 0,
                difficulty_point: 0,
            });

            count += self.solve_until_recursive(solutions, path, bound);
            path.steps.pop();
            self.remove_number(r, c, num);

            // Early return if we've found enough solutions
            if bound > 0 && solutions.len() >= bound {
                return count;
            }
        }

        count
    }

    /// Run techniques and check if they make valid changes.
    fn techniques_make_valid_changes(&mut self, path: &mut SolvePath) -> bool {
        let mut propagator = TechniquePropagator::new(
            &mut self.board,
            &mut self.masks,
            &mut self.candidates,
            self.techniques,
        );
        propagator.propagate_constraints(path, 0)
    }

    /// Solves the Sudoku puzzle up to a certain bound, returning solutions with their solve paths.
    pub fn solve_until(&mut self, bound: usize) -> Vec<Solution> {
        let mut solutions = Vec::new();
        let mut path = SolvePath::default();

        if !self.techniques_make_valid_changes(&mut path) {
            return solutions;
        }

        self.solve_until_recursive(&mut solutions, &mut path, bound);
        solutions
    }

    /// Attempts to solve the Sudoku puzzle using backtracking with MRV (Minimum Remaining Values).
    pub fn solve_any(&mut self) -> Option<Solution> {
        self.solve_until(1).into_iter().next()
    }

    /// Finds all possible solutions for the Sudoku puzzle.
    pub fn solve_all(&mut self) -> Vec<Solution> {
        use rayon::prelude::*;

        // Run technique propagation once on the current solver state.
        let mut path = SolvePath::default();
        if !self.techniques_make_valid_changes(&mut path) {
            return Vec::new();
        }

        // If there is at least one empty cell, split work by the first MRV cell's candidates.
        if let Some((r, c)) = self.find_next_empty_cell() {
            let mask = self.candidates.get(r, c);
            let nums = Self::candidates_from_mask(mask);

            let initial_path = path.clone();

            // Parallelize each top-level candidate branch.
            let chunks: Vec<Vec<Solution>> = nums
                .par_iter()
                .map(|&num| {
                    let mut cloned = *self; // Rustoku is Copy/Clone
                    let mut local_solutions: Vec<Solution> = Vec::new();
                    let mut local_path = initial_path.clone();

                    // Place the candidate and record the placement in the path.
                    cloned.place_number(r, c, num);
                    let step_number = local_path.steps.len() as u32;
                    local_path.steps.push(SolveStep::Placement {
                        row: r,
                        col: c,
                        value: num,
                        flags: TechniqueFlags::empty(),
                        step_number,
                        candidates_eliminated: 0,
                        related_cell_count: 0,
                        difficulty_point: 0,
                    });

                    // Continue DFS from this state without re-running the propagator.
                    cloned.solve_until_recursive(&mut local_solutions, &mut local_path, 0);
                    local_solutions
                })
                .collect();

            // Flatten results
            let mut solutions = Vec::new();
            for mut s in chunks {
                solutions.append(&mut s);
            }
            solutions
        } else {
            // Already solved after propagation
            vec![Solution {
                board: self.board,
                solve_path: path,
            }]
        }
    }

    /// Checks if the Sudoku puzzle is solved correctly.
    pub fn is_solved(&self) -> bool {
        self.board.cells.iter().flatten().all(|&val| val != 0) && Rustoku::new(self.board).is_ok()
    }
}

/// A simple builder for constructing `Rustoku` with fluent configuration.
pub struct RustokuBuilder {
    board: Option<Board>,
    techniques: TechniqueFlags,
    max_solutions: Option<usize>,
}

impl RustokuBuilder {
    /// Create a new builder with reasonable defaults.
    pub fn new() -> Self {
        RustokuBuilder {
            board: None,
            techniques: TechniqueFlags::EASY,
            max_solutions: None,
        }
    }
}

impl Default for RustokuBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl RustokuBuilder {
    /// Provide the initial `Board` for the solver.
    pub fn board(mut self, board: Board) -> Self {
        self.board = Some(board);
        self
    }

    /// Provide the initial board as a string (convenience).
    pub fn board_from_str(mut self, s: &str) -> Result<Self, RustokuError> {
        let board = Board::try_from(s)?;
        self.board = Some(board);
        Ok(self)
    }

    /// Configure which techniques the solver should use.
    pub fn techniques(mut self, techniques: TechniqueFlags) -> Self {
        self.techniques = techniques;
        self
    }

    /// Optionally hint the builder with a maximum number of solutions.
    pub fn max_solutions(mut self, max: usize) -> Self {
        self.max_solutions = Some(max);
        self
    }

    /// Finalize the builder and construct the `Rustoku` instance.
    pub fn build(self) -> Result<Rustoku, RustokuError> {
        let board = self.board.unwrap_or_default();
        let mut r = Rustoku::new(board)?;
        r.techniques = self.techniques;
        // If the user provided a max_solutions hint, we store it in techniques as not applicable
        // for now; the builder primarily configures creation state.
        Ok(r)
    }
}

/// Lazy iterator wrapper for solutions. Uses an explicit DFS stack and yields
/// solutions one-by-one without computing them all up-front.
#[derive(Debug)]
pub struct Solutions {
    solver: Rustoku,
    path: SolvePath,
    stack: Vec<Frame>,
    finished: bool,
}

#[derive(Debug)]
struct Frame {
    r: usize,
    c: usize,
    nums: Vec<u8>,
    idx: usize,
    placed: Option<u8>,
}

impl Solutions {
    /// Construct a `Solutions` iterator from an existing `Rustoku` solver.
    /// This will run the technique propagator once before starting DFS.
    pub fn from_solver(mut solver: Rustoku) -> Self {
        let mut path = SolvePath::default();
        let mut finished = false;

        if !solver.techniques_make_valid_changes(&mut path) {
            finished = true;
        }

        let mut stack = Vec::new();
        if !finished {
            if let Some((r, c)) = solver.find_next_empty_cell() {
                let mask = solver.candidates.get(r, c);
                let mut nums = Rustoku::candidates_from_mask(mask);
                nums.shuffle(&mut rng());
                stack.push(Frame {
                    r,
                    c,
                    nums,
                    idx: 0,
                    placed: None,
                });
            } else {
                // Already solved; leave stack empty and let next() yield the board once
            }
        }

        Solutions {
            solver,
            path,
            stack,
            finished,
        }
    }
}

impl Iterator for Solutions {
    type Item = Solution;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None;
        }

        loop {
            // If stack is empty, check if there are any empty cells left
            if self.stack.is_empty() {
                if let Some((r, c)) = self.solver.find_next_empty_cell() {
                    let mask = self.solver.candidates.get(r, c);
                    let mut nums = Rustoku::candidates_from_mask(mask);
                    nums.shuffle(&mut rng());
                    self.stack.push(Frame {
                        r,
                        c,
                        nums,
                        idx: 0,
                        placed: None,
                    });
                    continue;
                } else {
                    // No empty cells -> current board is a solution
                    let sol = Solution {
                        board: self.solver.board,
                        solve_path: self.path.clone(),
                    };
                    self.finished = true;
                    return Some(sol);
                }
            }

            let last_idx = self.stack.len() - 1;
            let frame = &mut self.stack[last_idx];

            // If we've exhausted candidates for this frame
            if frame.idx >= frame.nums.len() {
                if let Some(num) = frame.placed {
                    // remove the previously placed number
                    self.solver.remove_number(frame.r, frame.c, num);
                    self.path.steps.pop();
                    frame.placed = None;
                } else {
                    // No placement was made for this frame; pop it and continue
                    self.stack.pop();
                }
                continue;
            }

            let num = frame.nums[frame.idx];
            frame.idx += 1;

            if self.solver.masks.is_safe(frame.r, frame.c, num) {
                // place and record
                self.solver.place_number(frame.r, frame.c, num);
                let step_number = self.path.steps.len() as u32;
                self.path.steps.push(SolveStep::Placement {
                    row: frame.r,
                    col: frame.c,
                    value: num,
                    flags: TechniqueFlags::empty(),
                    step_number,
                    candidates_eliminated: 0,
                    related_cell_count: 0,
                    difficulty_point: 0,
                });
                frame.placed = Some(num);

                // Find next empty cell after this placement
                if let Some((nr, nc)) = self.solver.find_next_empty_cell() {
                    let mask = self.solver.candidates.get(nr, nc);
                    let mut nums2 = Rustoku::candidates_from_mask(mask);
                    nums2.shuffle(&mut rng());
                    self.stack.push(Frame {
                        r: nr,
                        c: nc,
                        nums: nums2,
                        idx: 0,
                        placed: None,
                    });
                    continue;
                } else {
                    // Found a solution. Capture it, then backtrack one placement so iteration can continue.
                    let solution = Solution {
                        board: self.solver.board,
                        solve_path: self.path.clone(),
                    };
                    // Backtrack the placement we just made on this frame
                    if let Some(pnum) = frame.placed {
                        self.solver.remove_number(frame.r, frame.c, pnum);
                        self.path.steps.pop();
                        frame.placed = None;
                    }
                    return Some(solution);
                }
            }
            // else try next candidate
        }
    }
}

/// Generates a new Sudoku puzzle with a unique solution and specified symmetry.
///
/// The `num_clues` parameter specifies the desired number of initially
/// filled cells (clues) in the generated puzzle. Fewer clues generally
/// result in a harder puzzle. The actual number of clues may be slightly
/// more than `num_clues` if it's impossible to remove more numbers
/// while maintaining a unique solution.
///
/// # Example
///
/// ```
/// use rustoku_lib::generate_board;
/// let puzzle = generate_board(30);
/// assert!(puzzle.is_ok());
/// ```
/// Generates a new Sudoku puzzle with a unique solution.
///
/// This is a convenience shim for `BoardGenerator::new().clues(num_clues).generate()`.
pub fn generate_board(num_clues: usize) -> Result<Board, RustokuError> {
    BoardGenerator::new().clues(num_clues).generate()
}

/// Generates a new Sudoku puzzle that matches a specific difficulty level.
///
/// This is a convenience shim for `BoardGenerator::new().difficulty(difficulty).max_attempts(max_attempts).generate()`.
pub fn generate_board_by_difficulty(
    difficulty: Difficulty,
    max_attempts: usize,
) -> Result<Board, RustokuError> {
    BoardGenerator::new()
        .difficulty(difficulty)
        .max_attempts(max_attempts)
        .generate()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::board::Board;
    use crate::core::techniques::flags::Difficulty;
    use crate::error::RustokuError;
    use crate::format::format_line;

    const UNIQUE_PUZZLE: &str =
        "530070000600195000098000060800060003400803001700020006060000280000419005000080079";
    const UNIQUE_SOLUTION: &str =
        "534678912672195348198342567859761423426853791713924856961537284287419635345286179";
    const TWO_PUZZLE: &str =
        "295743861431865900876192543387459216612387495549216738763504189928671354154938600";
    const SIX_PUZZLE: &str =
        "295743001431865900876192543387459216612387495549216738763500000000000000000000000";

    #[test]
    fn test_builder_and_iterator() {
        let board = Board::try_from(UNIQUE_PUZZLE).expect("valid puzzle");
        let solver = Rustoku::builder()
            .board(board)
            .techniques(TechniqueFlags::all())
            .build()
            .expect("builder build");

        // Using the iterator wrapper (eager compute, lazy yield)
        let mut sols = Solutions::from_solver(solver);
        let first = sols.next();
        assert!(first.is_some());
        // For unique puzzle, there should be exactly one solution
        assert!(sols.next().is_none());
    }

    #[test]
    fn test_try_from_with_duplicate_initial_values() {
        let s = "530070000600195000098000060800060003400803001700020006060000280000419005500080079";
        let board = Board::try_from(s).expect("Board parsing failed before duplicate check");
        let rustoku = Rustoku::new(board);
        assert!(matches!(rustoku, Err(RustokuError::DuplicateValues)));
    }

    #[test]
    fn test_solve_any_with_solvable_sudoku() {
        let s = UNIQUE_PUZZLE;
        let mut rustoku =
            Rustoku::new_from_str(s).expect("Rustoku creation failed from puzzle string");
        let solution = rustoku.solve_any().expect("Solving solvable puzzle failed");

        assert_eq!(
            UNIQUE_SOLUTION,
            format_line(&solution.board),
            "Solution does not match the expected result"
        );
    }

    #[test]
    fn test_solve_any_with_unsolvable_sudoku() {
        let s = "078002609030008020002000083000000040043090000007300090200001036001840902050003007";
        let mut rustoku = Rustoku::new_from_str(s).expect("Rustoku creation failed");
        let solution = rustoku.solve_any();
        assert!(
            solution.is_none(),
            "Expected no solution for this unsolvable puzzle"
        );
    }

    #[test]
    fn test_solve_until_with_bound() {
        let s = UNIQUE_PUZZLE;
        let mut rustoku =
            Rustoku::new_from_str(s).expect("Rustoku creation failed from puzzle string");

        let solutions = rustoku.solve_until(1);
        assert_eq!(
            1,
            solutions.len(),
            "Expected exactly one solution with bound = 1"
        );

        let all_solutions = rustoku.solve_until(0);
        assert_eq!(
            1,
            all_solutions.len(),
            "Expected exactly one solution for this board with bound = 0"
        );

        assert_eq!(
            solutions[0].board, all_solutions[0].board,
            "Solution with bound = 1 does not match the solution with bound = 0"
        );
    }

    #[test]
    fn test_solve_all_with_unique_puzzle() {
        let s = UNIQUE_PUZZLE;
        let mut rustoku =
            Rustoku::new_from_str(s).expect("Rustoku creation failed from unique puzzle string");
        let solutions = rustoku.solve_all();
        assert_eq!(
            1,
            solutions.len(),
            "Expected a unique solution for the board"
        );
    }

    #[test]
    fn test_solve_all_with_two_puzzle() {
        let s = TWO_PUZZLE;
        let mut rustoku =
            Rustoku::new_from_str(s).expect("Rustoku creation failed from two puzzle string");
        let solutions = rustoku.solve_all();
        assert_eq!(
            2,
            solutions.len(),
            "Expected two solutions for the given board"
        );
    }

    #[test]
    fn test_solve_all_with_six_puzzle() {
        let s = SIX_PUZZLE;
        let mut rustoku =
            Rustoku::new_from_str(s).expect("Rustoku creation failed from six puzzle string");
        let solutions = rustoku.solve_all();
        assert_eq!(
            6,
            solutions.len(),
            "Expected one solution for the six puzzle"
        );
    }

    #[test]
    fn test_solve_any_with_all_techniques() {
        let s = UNIQUE_PUZZLE;
        let rustoku = Rustoku::new_from_str(s).expect("Rustoku creation failed for technique test");
        let solution = rustoku
            .with_techniques(TechniqueFlags::all())
            .solve_any()
            .expect("Solving with all techniques failed");

        assert_eq!(
            UNIQUE_SOLUTION,
            format_line(&solution.board),
            "Solution does not match the expected result with all techniques"
        );
    }

    #[test]
    fn test_solve_all_with_all_techniques() {
        let s = TWO_PUZZLE;
        let rustoku = Rustoku::new_from_str(s)
            .expect("Rustoku creation failed for multi-solution technique test");
        let solutions = rustoku.with_techniques(TechniqueFlags::all()).solve_all();

        assert_eq!(
            2,
            solutions.len(),
            "Expected two solutions for the given board with all techniques"
        );
    }

    #[test]
    fn test_generate_with_enough_clues() {
        (20..=80).step_by(20).for_each(|num_clues| {
            let board = generate_board(num_clues)
                .expect("Board generation failed - check clue count is between 17 and 81");
            let mut rustoku =
                Rustoku::new(board).expect("Rustoku creation failed from generated board");
            let clues_count = board
                .cells
                .iter()
                .flatten()
                .filter(|&&cell| cell != 0)
                .count();
            assert!(
                clues_count >= num_clues,
                "Expected at least {num_clues} clues, but found {clues_count} clues"
            );

            let solutions = rustoku.solve_all();
            assert_eq!(
                1,
                solutions.len(),
                "Generated puzzle with {num_clues} clues should have a unique solution"
            );
        })
    }

    #[test]
    fn test_generate_with_too_few_clues() {
        let num_clues = 16;
        let result = generate_board(num_clues);
        assert!(matches!(result, Err(RustokuError::InvalidClueCount)));
    }

    #[test]
    fn test_generate_with_too_many_clues() {
        let num_clues = 82;
        let result = generate_board(num_clues);
        assert!(matches!(result, Err(RustokuError::InvalidClueCount)));
    }

    #[test]
    fn test_is_solved_with_valid_solution() {
        let s = UNIQUE_SOLUTION;
        let rustoku = Rustoku::new_from_str(s).expect("Rustoku creation failed for solved check");
        assert!(rustoku.is_solved(), "The Sudoku puzzle should be solved");
    }

    #[test]
    fn test_is_solved_with_unsolved_board() {
        let s = UNIQUE_PUZZLE;
        let rustoku = Rustoku::new_from_str(s).expect("Rustoku creation failed for unsolved check");
        assert!(!rustoku.is_solved(), "The board should not be valid");
    }

    #[test]
    fn test_generate_by_difficulty_easy() {
        let board = generate_board_by_difficulty(Difficulty::Easy, 100)
            .expect("Failed to generate an Easy puzzle within 100 attempts");

        let mut rustoku = Rustoku::builder()
            .board(board)
            .techniques(TechniqueFlags::all())
            .build()
            .unwrap();

        let solutions = rustoku.solve_all();
        assert_eq!(solutions.len(), 1);

        let mut required_guessing = false;
        let mut max_difficulty = Difficulty::Easy;

        for step in &solutions[0].solve_path.steps {
            match step {
                crate::core::solution::SolveStep::Placement { flags, .. } => {
                    if flags.is_empty() {
                        required_guessing = true;
                    }
                    if flags.difficulty() > max_difficulty {
                        max_difficulty = flags.difficulty();
                    }
                }
                crate::core::solution::SolveStep::CandidateElimination { flags, .. } => {
                    if flags.difficulty() > max_difficulty {
                        max_difficulty = flags.difficulty();
                    }
                }
            }
        }

        assert!(
            !required_guessing,
            "Easy puzzle should not require guessing"
        );
        assert_eq!(
            max_difficulty,
            Difficulty::Easy,
            "Puzzle exceeded target difficulty"
        );
    }

    #[test]
    fn test_generate_by_difficulty_hard() {
        let board = generate_board_by_difficulty(Difficulty::Hard, 1000)
            .expect("Failed to generate a Hard puzzle within 1000 attempts");

        let mut rustoku = Rustoku::builder()
            .board(board)
            .techniques(TechniqueFlags::all())
            .build()
            .unwrap();

        let solutions = rustoku.solve_all();
        assert_eq!(solutions.len(), 1);

        let mut required_guessing = false;
        let mut max_difficulty = Difficulty::Easy;

        for step in &solutions[0].solve_path.steps {
            match step {
                crate::core::solution::SolveStep::Placement { flags, .. } => {
                    if flags.is_empty() {
                        required_guessing = true;
                    }
                    if flags.difficulty() > max_difficulty {
                        max_difficulty = flags.difficulty();
                    }
                }
                crate::core::solution::SolveStep::CandidateElimination { flags, .. } => {
                    if flags.difficulty() > max_difficulty {
                        max_difficulty = flags.difficulty();
                    }
                }
            }
        }

        assert!(
            !required_guessing,
            "Hard puzzle should not require guessing"
        );
        assert_eq!(
            max_difficulty,
            Difficulty::Hard,
            "Puzzle exceeded target difficulty"
        );
    }
}