sheetkit-core 0.5.1

Core library for reading and writing Excel (.xlsx) files
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
//! Row operations for worksheet manipulation.
//!
//! All functions operate directly on a [`WorksheetXml`] structure, keeping the
//! business logic decoupled from the [`Workbook`](crate::workbook::Workbook)
//! wrapper.

use sheetkit_xml::worksheet::{CellTypeTag, Row, WorksheetXml};

use crate::cell::CellValue;
use crate::error::{Error, Result};
use crate::sst::SharedStringTable;
use crate::utils::cell_ref::{cell_name_to_coordinates, coordinates_to_cell_name};
use crate::utils::constants::{MAX_ROWS, MAX_ROW_HEIGHT};

/// Get all rows with their data from a worksheet.
///
/// Returns a Vec of `(row_number, Vec<(column_number, CellValue)>)` tuples.
/// Column numbers are 1-based (A=1, B=2, ...). Only rows that contain at
/// least one cell are included (sparse).
///
/// `style_is_date` is a per-style-index flag (from
/// [`crate::style::compute_style_is_date`]) that marks which styles carry
/// a date number format. Pass an empty slice to skip date promotion, or
/// the workbook's precomputed lookup to have `t="n"` cells with a date
/// format returned as [`CellValue::Date`].
#[allow(clippy::type_complexity)]
pub fn get_rows(
    ws: &WorksheetXml,
    sst: &SharedStringTable,
    style_is_date: &[bool],
) -> Result<Vec<(u32, Vec<(u32, CellValue)>)>> {
    let mut result = Vec::new();

    for row in &ws.sheet_data.rows {
        if row.cells.is_empty() {
            continue;
        }

        let mut cells = Vec::new();
        for cell in &row.cells {
            let col_num = if cell.col > 0 {
                cell.col
            } else {
                cell_name_to_coordinates(cell.r.as_str())?.0
            };
            let value = resolve_cell_value(cell, sst, style_is_date);
            cells.push((col_num, value));
        }

        result.push((row.r, cells));
    }

    Ok(result)
}

/// Look up a shared string by index string. Returns `CellValue::Empty` if the
/// index is not a valid integer or the SST does not contain the entry.
pub fn resolve_sst_value(sst: &SharedStringTable, index: &str) -> CellValue {
    let idx: usize = match index.parse() {
        Ok(i) => i,
        Err(_) => return CellValue::Empty,
    };
    let s = sst.get(idx).unwrap_or("").to_string();
    CellValue::String(s)
}

/// Resolve a cell's typed value from its raw XML components.
///
/// Handles all cell type tags (shared string, boolean, error, inline string,
/// formula string, number) and SST lookup. This is the core dispatch that both
/// `resolve_cell_value` and future buffer-pack paths share.
///
/// When `promote_number_to_date` is `true`, non-formula numeric cells are
/// returned as [`CellValue::Date`] rather than [`CellValue::Number`]. The
/// caller decides whether promotion applies by consulting the cell's style
/// index against its precomputed date-style lookup; this function stays
/// style-agnostic.
pub fn parse_cell_type_value(
    cell_type: CellTypeTag,
    value: Option<&str>,
    formula: Option<&sheetkit_xml::worksheet::CellFormula>,
    inline_str: Option<&sheetkit_xml::worksheet::InlineString>,
    sst: &SharedStringTable,
    promote_number_to_date: bool,
) -> CellValue {
    if let Some(f) = formula {
        let expr = f.value.clone().unwrap_or_default();
        let cached = match (cell_type, value) {
            (CellTypeTag::Boolean, Some(v)) => Some(Box::new(CellValue::Bool(v == "1"))),
            (CellTypeTag::Error, Some(v)) => Some(Box::new(CellValue::Error(v.to_string()))),
            (_, Some(v)) => v
                .parse::<f64>()
                .ok()
                .map(|n| Box::new(CellValue::Number(n))),
            _ => None,
        };
        return CellValue::Formula {
            expr,
            result: cached,
        };
    }

    match (cell_type, value) {
        (CellTypeTag::SharedString, Some(v)) => resolve_sst_value(sst, v),
        (CellTypeTag::Boolean, Some(v)) => CellValue::Bool(v == "1"),
        (CellTypeTag::Error, Some(v)) => CellValue::Error(v.to_string()),
        (CellTypeTag::InlineString, _) => {
            let s = inline_str.and_then(|is| is.t.clone()).unwrap_or_default();
            CellValue::String(s)
        }
        (CellTypeTag::FormulaString, Some(v)) => CellValue::String(v.to_string()),
        (CellTypeTag::None | CellTypeTag::Number, Some(v)) => match v.parse::<f64>() {
            Ok(n) => {
                if promote_number_to_date {
                    CellValue::Date(n)
                } else {
                    CellValue::Number(n)
                }
            }
            Err(_) => CellValue::Empty,
        },
        _ => CellValue::Empty,
    }
}

/// Resolve the value of an XML cell to a [`CellValue`], using the SST for
/// shared string lookups. Thin wrapper over [`parse_cell_type_value`] that
/// also consults `style_is_date` (indexed by `cell.s`) to decide whether a
/// numeric cell should be surfaced as a date.
///
/// Pass an empty slice to disable date promotion; the returned values will
/// then be spec-literal (`CellValue::Number` for `t="n"` cells regardless
/// of number format).
pub fn resolve_cell_value(
    cell: &sheetkit_xml::worksheet::Cell,
    sst: &SharedStringTable,
    style_is_date: &[bool],
) -> CellValue {
    let promote_number_to_date = cell
        .s
        .and_then(|idx| style_is_date.get(idx as usize).copied())
        .unwrap_or(false);
    parse_cell_type_value(
        cell.t,
        cell.v.as_deref(),
        cell.f.as_deref(),
        cell.is.as_deref(),
        sst,
        promote_number_to_date,
    )
}

/// Insert `count` empty rows starting at `start_row`, shifting existing rows
/// at and below `start_row` downward.
///
/// Cell references inside shifted rows are updated so that e.g. "B5" becomes
/// "B8" when 3 rows are inserted at row 5.
pub fn insert_rows(ws: &mut WorksheetXml, start_row: u32, count: u32) -> Result<()> {
    if start_row == 0 {
        return Err(Error::InvalidRowNumber(0));
    }
    if count == 0 {
        return Ok(());
    }
    // Validate that shifting won't exceed MAX_ROWS.
    let max_existing = ws.sheet_data.rows.iter().map(|r| r.r).max().unwrap_or(0);
    let furthest = max_existing.max(start_row);
    if furthest.checked_add(count).is_none_or(|v| v > MAX_ROWS) {
        return Err(Error::InvalidRowNumber(furthest + count));
    }

    // Shift rows that are >= start_row downward by `count`.
    // Iterate in reverse to avoid overwriting.
    for row in ws.sheet_data.rows.iter_mut().rev() {
        if row.r >= start_row {
            let new_row_num = row.r + count;
            shift_row_cells(row, new_row_num)?;
            row.r = new_row_num;
        }
    }

    Ok(())
}

/// Remove a single row, shifting rows below it upward by one.
pub fn remove_row(ws: &mut WorksheetXml, row: u32) -> Result<()> {
    if row == 0 {
        return Err(Error::InvalidRowNumber(0));
    }

    // Remove the target row via binary search.
    if let Ok(idx) = ws.sheet_data.rows.binary_search_by_key(&row, |r| r.r) {
        ws.sheet_data.rows.remove(idx);
    }

    // Shift rows above `row` upward.
    for r in ws.sheet_data.rows.iter_mut() {
        if r.r > row {
            let new_row_num = r.r - 1;
            shift_row_cells(r, new_row_num)?;
            r.r = new_row_num;
        }
    }

    Ok(())
}

/// Duplicate a row, inserting the copy directly below the source row.
pub fn duplicate_row(ws: &mut WorksheetXml, row: u32) -> Result<()> {
    duplicate_row_to(ws, row, row + 1)
}

/// Duplicate a row to a specific target row number. Existing rows at and
/// below `target` are shifted down to make room.
pub fn duplicate_row_to(ws: &mut WorksheetXml, row: u32, target: u32) -> Result<()> {
    if row == 0 {
        return Err(Error::InvalidRowNumber(0));
    }
    if target == 0 {
        return Err(Error::InvalidRowNumber(0));
    }
    if target > MAX_ROWS {
        return Err(Error::InvalidRowNumber(target));
    }

    // Find and clone the source row via binary search.
    let source = ws
        .sheet_data
        .rows
        .binary_search_by_key(&row, |r| r.r)
        .ok()
        .map(|idx| ws.sheet_data.rows[idx].clone())
        .ok_or(Error::InvalidRowNumber(row))?;

    // Shift existing rows at target downward.
    insert_rows(ws, target, 1)?;

    // Build the duplicated row with updated cell references.
    let mut new_row = source;
    shift_row_cells(&mut new_row, target)?;
    new_row.r = target;

    // Insert the new row in sorted position via binary search.
    match ws.sheet_data.rows.binary_search_by_key(&target, |r| r.r) {
        Ok(idx) => ws.sheet_data.rows[idx] = new_row,
        Err(pos) => ws.sheet_data.rows.insert(pos, new_row),
    }

    Ok(())
}

/// Set the height of a row in points. Creates the row if it does not exist.
///
/// Valid range: `0.0 ..= 409.0`.
pub fn set_row_height(ws: &mut WorksheetXml, row: u32, height: f64) -> Result<()> {
    if row == 0 || row > MAX_ROWS {
        return Err(Error::InvalidRowNumber(row));
    }
    if !(0.0..=MAX_ROW_HEIGHT).contains(&height) {
        return Err(Error::RowHeightExceeded {
            height,
            max: MAX_ROW_HEIGHT,
        });
    }

    let r = find_or_create_row(ws, row);
    r.ht = Some(height);
    r.custom_height = Some(true);
    Ok(())
}

/// Get the height of a row. Returns `None` if the row does not exist or has
/// no explicit height set.
pub fn get_row_height(ws: &WorksheetXml, row: u32) -> Option<f64> {
    ws.sheet_data
        .rows
        .binary_search_by_key(&row, |r| r.r)
        .ok()
        .and_then(|idx| ws.sheet_data.rows[idx].ht)
}

/// Set the visibility of a row. Creates the row if it does not exist.
pub fn set_row_visible(ws: &mut WorksheetXml, row: u32, visible: bool) -> Result<()> {
    if row == 0 || row > MAX_ROWS {
        return Err(Error::InvalidRowNumber(row));
    }

    let r = find_or_create_row(ws, row);
    r.hidden = if visible { None } else { Some(true) };
    Ok(())
}

/// Get the visibility of a row. Returns true if visible (not hidden).
///
/// Rows are visible by default, so this returns true if the row does not
/// exist or has no explicit `hidden` attribute.
pub fn get_row_visible(ws: &WorksheetXml, row: u32) -> bool {
    ws.sheet_data
        .rows
        .binary_search_by_key(&row, |r| r.r)
        .ok()
        .and_then(|idx| ws.sheet_data.rows[idx].hidden)
        .map(|h| !h)
        .unwrap_or(true)
}

/// Get the outline (grouping) level of a row. Returns 0 if not set.
pub fn get_row_outline_level(ws: &WorksheetXml, row: u32) -> u8 {
    ws.sheet_data
        .rows
        .binary_search_by_key(&row, |r| r.r)
        .ok()
        .and_then(|idx| ws.sheet_data.rows[idx].outline_level)
        .unwrap_or(0)
}

/// Set the outline (grouping) level of a row.
///
/// Valid range: `0..=7` (Excel supports up to 7 outline levels).
pub fn set_row_outline_level(ws: &mut WorksheetXml, row: u32, level: u8) -> Result<()> {
    if row == 0 || row > MAX_ROWS {
        return Err(Error::InvalidRowNumber(row));
    }
    if level > 7 {
        return Err(Error::OutlineLevelExceeded { level, max: 7 });
    }

    let r = find_or_create_row(ws, row);
    r.outline_level = if level == 0 { None } else { Some(level) };
    Ok(())
}

/// Set the style for an entire row. The `style_id` is the ID returned by
/// `add_style()`. Setting a row style applies the `s` attribute on the row
/// element and marks `customFormat` so Excel honours it.  Existing cells in
/// the row also have their individual style updated.
pub fn set_row_style(ws: &mut WorksheetXml, row: u32, style_id: u32) -> Result<()> {
    if row == 0 || row > MAX_ROWS {
        return Err(Error::InvalidRowNumber(row));
    }

    let r = find_or_create_row(ws, row);
    r.s = Some(style_id);
    r.custom_format = if style_id == 0 { None } else { Some(true) };

    // Apply to all existing cells in the row.
    for cell in r.cells.iter_mut() {
        cell.s = Some(style_id);
    }
    Ok(())
}

/// Get the style ID for a row. Returns 0 (default) if the row does not
/// exist or has no explicit style.
pub fn get_row_style(ws: &WorksheetXml, row: u32) -> u32 {
    ws.sheet_data
        .rows
        .binary_search_by_key(&row, |r| r.r)
        .ok()
        .and_then(|idx| ws.sheet_data.rows[idx].s)
        .unwrap_or(0)
}

/// Update all cell references in a row to point to `new_row_num`.
fn shift_row_cells(row: &mut Row, new_row_num: u32) -> Result<()> {
    for cell in row.cells.iter_mut() {
        let (col, _) = cell_name_to_coordinates(cell.r.as_str())?;
        cell.r = coordinates_to_cell_name(col, new_row_num)?.into();
        cell.col = col;
    }
    Ok(())
}

/// Find an existing row or create a new empty one, keeping rows sorted.
/// Uses binary search for O(log n) lookup instead of linear scan.
fn find_or_create_row(ws: &mut WorksheetXml, row: u32) -> &mut Row {
    match ws.sheet_data.rows.binary_search_by_key(&row, |r| r.r) {
        Ok(idx) => &mut ws.sheet_data.rows[idx],
        Err(pos) => {
            ws.sheet_data.rows.insert(
                pos,
                Row {
                    r: row,
                    spans: None,
                    s: None,
                    custom_format: None,
                    ht: None,
                    hidden: None,
                    custom_height: None,
                    outline_level: None,
                    cells: vec![],
                },
            );
            &mut ws.sheet_data.rows[pos]
        }
    }
}

#[cfg(test)]
#[allow(clippy::field_reassign_with_default)]
mod tests {
    use super::*;
    use sheetkit_xml::worksheet::{Cell, CellTypeTag, SheetData};

    /// Helper: build a minimal worksheet with some pre-populated rows.
    fn sample_ws() -> WorksheetXml {
        let mut ws = WorksheetXml::default();
        ws.sheet_data = SheetData {
            rows: vec![
                Row {
                    r: 1,
                    spans: None,
                    s: None,
                    custom_format: None,
                    ht: None,
                    hidden: None,
                    custom_height: None,
                    outline_level: None,
                    cells: vec![
                        Cell {
                            r: "A1".into(),
                            col: 1,
                            s: None,
                            t: CellTypeTag::None,
                            v: Some("10".to_string()),
                            f: None,
                            is: None,
                        },
                        Cell {
                            r: "B1".into(),
                            col: 2,
                            s: None,
                            t: CellTypeTag::None,
                            v: Some("20".to_string()),
                            f: None,
                            is: None,
                        },
                    ],
                },
                Row {
                    r: 2,
                    spans: None,
                    s: None,
                    custom_format: None,
                    ht: None,
                    hidden: None,
                    custom_height: None,
                    outline_level: None,
                    cells: vec![Cell {
                        r: "A2".into(),
                        col: 1,
                        s: None,
                        t: CellTypeTag::None,
                        v: Some("30".to_string()),
                        f: None,
                        is: None,
                    }],
                },
                Row {
                    r: 5,
                    spans: None,
                    s: None,
                    custom_format: None,
                    ht: None,
                    hidden: None,
                    custom_height: None,
                    outline_level: None,
                    cells: vec![Cell {
                        r: "C5".into(),
                        col: 3,
                        s: None,
                        t: CellTypeTag::None,
                        v: Some("50".to_string()),
                        f: None,
                        is: None,
                    }],
                },
            ],
        };
        ws
    }

    #[test]
    fn test_insert_rows_shifts_cells_down() {
        let mut ws = sample_ws();
        insert_rows(&mut ws, 2, 3).unwrap();

        // Row 1 should be untouched.
        assert_eq!(ws.sheet_data.rows[0].r, 1);
        assert_eq!(ws.sheet_data.rows[0].cells[0].r, "A1");

        // Row 2 -> 5 (shifted by 3).
        assert_eq!(ws.sheet_data.rows[1].r, 5);
        assert_eq!(ws.sheet_data.rows[1].cells[0].r, "A5");

        // Row 5 -> 8 (shifted by 3).
        assert_eq!(ws.sheet_data.rows[2].r, 8);
        assert_eq!(ws.sheet_data.rows[2].cells[0].r, "C8");
    }

    #[test]
    fn test_insert_rows_at_row_1() {
        let mut ws = sample_ws();
        insert_rows(&mut ws, 1, 2).unwrap();

        // All rows shift by 2.
        assert_eq!(ws.sheet_data.rows[0].r, 3);
        assert_eq!(ws.sheet_data.rows[0].cells[0].r, "A3");
        assert_eq!(ws.sheet_data.rows[1].r, 4);
        assert_eq!(ws.sheet_data.rows[2].r, 7);
    }

    #[test]
    fn test_insert_rows_count_zero_is_noop() {
        let mut ws = sample_ws();
        insert_rows(&mut ws, 1, 0).unwrap();
        assert_eq!(ws.sheet_data.rows[0].r, 1);
        assert_eq!(ws.sheet_data.rows[1].r, 2);
        assert_eq!(ws.sheet_data.rows[2].r, 5);
    }

    #[test]
    fn test_insert_rows_row_zero_returns_error() {
        let mut ws = sample_ws();
        let result = insert_rows(&mut ws, 0, 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_insert_rows_beyond_max_returns_error() {
        let mut ws = WorksheetXml::default();
        ws.sheet_data.rows.push(Row {
            r: MAX_ROWS,
            spans: None,
            s: None,
            custom_format: None,
            ht: None,
            hidden: None,
            custom_height: None,
            outline_level: None,
            cells: vec![],
        });
        let result = insert_rows(&mut ws, 1, 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_insert_rows_on_empty_sheet() {
        let mut ws = WorksheetXml::default();
        insert_rows(&mut ws, 1, 5).unwrap();
        assert!(ws.sheet_data.rows.is_empty());
    }

    #[test]
    fn test_remove_row_shifts_up() {
        let mut ws = sample_ws();
        remove_row(&mut ws, 2).unwrap();

        // Row 1 untouched.
        assert_eq!(ws.sheet_data.rows[0].r, 1);
        assert_eq!(ws.sheet_data.rows[0].cells[0].r, "A1");

        // Original row 2 is gone; row 5 shifted to 4.
        assert_eq!(ws.sheet_data.rows.len(), 2);
        assert_eq!(ws.sheet_data.rows[1].r, 4);
        assert_eq!(ws.sheet_data.rows[1].cells[0].r, "C4");
    }

    #[test]
    fn test_remove_first_row() {
        let mut ws = sample_ws();
        remove_row(&mut ws, 1).unwrap();

        // Remaining rows shift up.
        assert_eq!(ws.sheet_data.rows[0].r, 1);
        assert_eq!(ws.sheet_data.rows[0].cells[0].r, "A1");
        assert_eq!(ws.sheet_data.rows[1].r, 4);
    }

    #[test]
    fn test_remove_nonexistent_row_still_shifts() {
        let mut ws = sample_ws();
        // Row 3 doesn't exist, but rows below should shift.
        remove_row(&mut ws, 3).unwrap();
        assert_eq!(ws.sheet_data.rows.len(), 3); // no row removed
        assert_eq!(ws.sheet_data.rows[2].r, 4); // row 5 -> 4
    }

    #[test]
    fn test_remove_row_zero_returns_error() {
        let mut ws = sample_ws();
        let result = remove_row(&mut ws, 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_duplicate_row_inserts_copy_below() {
        let mut ws = sample_ws();
        duplicate_row(&mut ws, 1).unwrap();

        // Row 1 stays.
        assert_eq!(ws.sheet_data.rows[0].r, 1);
        assert_eq!(ws.sheet_data.rows[0].cells[0].r, "A1");
        assert_eq!(ws.sheet_data.rows[0].cells[0].v, Some("10".to_string()));

        // Row 2 is the duplicate with updated refs.
        assert_eq!(ws.sheet_data.rows[1].r, 2);
        assert_eq!(ws.sheet_data.rows[1].cells[0].r, "A2");
        assert_eq!(ws.sheet_data.rows[1].cells[0].v, Some("10".to_string()));
        assert_eq!(ws.sheet_data.rows[1].cells.len(), 2);

        // Original row 2 shifted to 3.
        assert_eq!(ws.sheet_data.rows[2].r, 3);
        assert_eq!(ws.sheet_data.rows[2].cells[0].r, "A3");
    }

    #[test]
    fn test_duplicate_row_to_specific_target() {
        let mut ws = sample_ws();
        duplicate_row_to(&mut ws, 1, 5).unwrap();

        // Row 1 unchanged.
        assert_eq!(ws.sheet_data.rows[0].r, 1);

        // Target row 5 is the copy.
        let row5 = ws.sheet_data.rows.iter().find(|r| r.r == 5).unwrap();
        assert_eq!(row5.cells[0].r, "A5");
        assert_eq!(row5.cells[0].v, Some("10".to_string()));

        // Original row 5 shifted to 6.
        let row6 = ws.sheet_data.rows.iter().find(|r| r.r == 6).unwrap();
        assert_eq!(row6.cells[0].r, "C6");
    }

    #[test]
    fn test_duplicate_nonexistent_row_returns_error() {
        let mut ws = sample_ws();
        let result = duplicate_row(&mut ws, 99);
        assert!(result.is_err());
    }

    #[test]
    fn test_set_and_get_row_height() {
        let mut ws = sample_ws();
        set_row_height(&mut ws, 1, 25.5).unwrap();

        assert_eq!(get_row_height(&ws, 1), Some(25.5));
        let row = ws.sheet_data.rows.iter().find(|r| r.r == 1).unwrap();
        assert_eq!(row.custom_height, Some(true));
    }

    #[test]
    fn test_set_row_height_creates_row_if_missing() {
        let mut ws = WorksheetXml::default();
        set_row_height(&mut ws, 10, 30.0).unwrap();

        assert_eq!(get_row_height(&ws, 10), Some(30.0));
        assert_eq!(ws.sheet_data.rows.len(), 1);
        assert_eq!(ws.sheet_data.rows[0].r, 10);
    }

    #[test]
    fn test_set_row_height_zero_is_valid() {
        let mut ws = WorksheetXml::default();
        set_row_height(&mut ws, 1, 0.0).unwrap();
        assert_eq!(get_row_height(&ws, 1), Some(0.0));
    }

    #[test]
    fn test_set_row_height_max_is_valid() {
        let mut ws = WorksheetXml::default();
        set_row_height(&mut ws, 1, 409.0).unwrap();
        assert_eq!(get_row_height(&ws, 1), Some(409.0));
    }

    #[test]
    fn test_set_row_height_exceeds_max_returns_error() {
        let mut ws = WorksheetXml::default();
        let result = set_row_height(&mut ws, 1, 410.0);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            Error::RowHeightExceeded { .. }
        ));
    }

    #[test]
    fn test_set_row_height_negative_returns_error() {
        let mut ws = WorksheetXml::default();
        let result = set_row_height(&mut ws, 1, -1.0);
        assert!(result.is_err());
    }

    #[test]
    fn test_set_row_height_row_zero_returns_error() {
        let mut ws = WorksheetXml::default();
        let result = set_row_height(&mut ws, 0, 15.0);
        assert!(result.is_err());
    }

    #[test]
    fn test_get_row_height_nonexistent_returns_none() {
        let ws = WorksheetXml::default();
        assert_eq!(get_row_height(&ws, 99), None);
    }

    #[test]
    fn test_set_row_hidden() {
        let mut ws = sample_ws();
        set_row_visible(&mut ws, 1, false).unwrap();

        let row = ws.sheet_data.rows.iter().find(|r| r.r == 1).unwrap();
        assert_eq!(row.hidden, Some(true));
    }

    #[test]
    fn test_set_row_visible_clears_hidden() {
        let mut ws = sample_ws();
        set_row_visible(&mut ws, 1, false).unwrap();
        set_row_visible(&mut ws, 1, true).unwrap();

        let row = ws.sheet_data.rows.iter().find(|r| r.r == 1).unwrap();
        assert_eq!(row.hidden, None);
    }

    #[test]
    fn test_set_row_visible_creates_row_if_missing() {
        let mut ws = WorksheetXml::default();
        set_row_visible(&mut ws, 3, false).unwrap();
        assert_eq!(ws.sheet_data.rows.len(), 1);
        assert_eq!(ws.sheet_data.rows[0].r, 3);
        assert_eq!(ws.sheet_data.rows[0].hidden, Some(true));
    }

    #[test]
    fn test_set_row_visible_row_zero_returns_error() {
        let mut ws = WorksheetXml::default();
        let result = set_row_visible(&mut ws, 0, true);
        assert!(result.is_err());
    }

    #[test]
    fn test_set_row_outline_level() {
        let mut ws = sample_ws();
        set_row_outline_level(&mut ws, 1, 3).unwrap();

        let row = ws.sheet_data.rows.iter().find(|r| r.r == 1).unwrap();
        assert_eq!(row.outline_level, Some(3));
    }

    #[test]
    fn test_set_row_outline_level_zero_clears() {
        let mut ws = sample_ws();
        set_row_outline_level(&mut ws, 1, 3).unwrap();
        set_row_outline_level(&mut ws, 1, 0).unwrap();

        let row = ws.sheet_data.rows.iter().find(|r| r.r == 1).unwrap();
        assert_eq!(row.outline_level, None);
    }

    #[test]
    fn test_set_row_outline_level_exceeds_max_returns_error() {
        let mut ws = sample_ws();
        let result = set_row_outline_level(&mut ws, 1, 8);
        assert!(result.is_err());
    }

    #[test]
    fn test_set_row_outline_level_row_zero_returns_error() {
        let mut ws = WorksheetXml::default();
        let result = set_row_outline_level(&mut ws, 0, 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_get_row_visible_default_is_true() {
        let ws = sample_ws();
        assert!(get_row_visible(&ws, 1));
    }

    #[test]
    fn test_get_row_visible_nonexistent_row_is_true() {
        let ws = WorksheetXml::default();
        assert!(get_row_visible(&ws, 99));
    }

    #[test]
    fn test_get_row_visible_after_hide() {
        let mut ws = sample_ws();
        set_row_visible(&mut ws, 1, false).unwrap();
        assert!(!get_row_visible(&ws, 1));
    }

    #[test]
    fn test_get_row_visible_after_hide_then_show() {
        let mut ws = sample_ws();
        set_row_visible(&mut ws, 1, false).unwrap();
        set_row_visible(&mut ws, 1, true).unwrap();
        assert!(get_row_visible(&ws, 1));
    }

    #[test]
    fn test_get_row_outline_level_default_is_zero() {
        let ws = sample_ws();
        assert_eq!(get_row_outline_level(&ws, 1), 0);
    }

    #[test]
    fn test_get_row_outline_level_nonexistent_row() {
        let ws = WorksheetXml::default();
        assert_eq!(get_row_outline_level(&ws, 99), 0);
    }

    #[test]
    fn test_get_row_outline_level_after_set() {
        let mut ws = sample_ws();
        set_row_outline_level(&mut ws, 1, 5).unwrap();
        assert_eq!(get_row_outline_level(&ws, 1), 5);
    }

    #[test]
    fn test_get_row_outline_level_after_clear() {
        let mut ws = sample_ws();
        set_row_outline_level(&mut ws, 1, 3).unwrap();
        set_row_outline_level(&mut ws, 1, 0).unwrap();
        assert_eq!(get_row_outline_level(&ws, 1), 0);
    }

    // -- get_rows tests --

    #[test]
    fn test_get_rows_empty_sheet() {
        let ws = WorksheetXml::default();
        let sst = SharedStringTable::new();
        let rows = get_rows(&ws, &sst, &[]).unwrap();
        assert!(rows.is_empty());
    }

    #[test]
    fn test_get_rows_returns_numeric_values() {
        let ws = sample_ws();
        let sst = SharedStringTable::new();
        let rows = get_rows(&ws, &sst, &[]).unwrap();

        assert_eq!(rows.len(), 3);

        // Row 1: A1=10, B1=20
        assert_eq!(rows[0].0, 1);
        assert_eq!(rows[0].1.len(), 2);
        assert_eq!(rows[0].1[0].0, 1);
        assert_eq!(rows[0].1[0].1, CellValue::Number(10.0));
        assert_eq!(rows[0].1[1].0, 2);
        assert_eq!(rows[0].1[1].1, CellValue::Number(20.0));

        // Row 2: A2=30
        assert_eq!(rows[1].0, 2);
        assert_eq!(rows[1].1.len(), 1);
        assert_eq!(rows[1].1[0].0, 1);
        assert_eq!(rows[1].1[0].1, CellValue::Number(30.0));

        // Row 5: C5=50 (sparse -- rows 3 and 4 skipped)
        assert_eq!(rows[2].0, 5);
        assert_eq!(rows[2].1.len(), 1);
        assert_eq!(rows[2].1[0].0, 3);
        assert_eq!(rows[2].1[0].1, CellValue::Number(50.0));
    }

    #[test]
    fn test_get_rows_shared_strings() {
        let mut sst = SharedStringTable::new();
        sst.add("hello");
        sst.add("world");

        let mut ws = WorksheetXml::default();
        ws.sheet_data = SheetData {
            rows: vec![Row {
                r: 1,
                spans: None,
                s: None,
                custom_format: None,
                ht: None,
                hidden: None,
                custom_height: None,
                outline_level: None,
                cells: vec![
                    Cell {
                        r: "A1".into(),
                        col: 1,
                        s: None,
                        t: CellTypeTag::SharedString,
                        v: Some("0".to_string()),
                        f: None,
                        is: None,
                    },
                    Cell {
                        r: "B1".into(),
                        col: 2,
                        s: None,
                        t: CellTypeTag::SharedString,
                        v: Some("1".to_string()),
                        f: None,
                        is: None,
                    },
                ],
            }],
        };

        let rows = get_rows(&ws, &sst, &[]).unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].1[0].1, CellValue::String("hello".to_string()));
        assert_eq!(rows[0].1[1].1, CellValue::String("world".to_string()));
    }

    #[test]
    fn test_get_rows_mixed_types() {
        let mut sst = SharedStringTable::new();
        sst.add("text");

        let mut ws = WorksheetXml::default();
        ws.sheet_data = SheetData {
            rows: vec![Row {
                r: 1,
                spans: None,
                s: None,
                custom_format: None,
                ht: None,
                hidden: None,
                custom_height: None,
                outline_level: None,
                cells: vec![
                    Cell {
                        r: "A1".into(),
                        col: 1,
                        s: None,
                        t: CellTypeTag::SharedString,
                        v: Some("0".to_string()),
                        f: None,
                        is: None,
                    },
                    Cell {
                        r: "B1".into(),
                        col: 2,
                        s: None,
                        t: CellTypeTag::None,
                        v: Some("42.5".to_string()),
                        f: None,
                        is: None,
                    },
                    Cell {
                        r: "C1".into(),
                        col: 3,
                        s: None,
                        t: CellTypeTag::Boolean,
                        v: Some("1".to_string()),
                        f: None,
                        is: None,
                    },
                    Cell {
                        r: "D1".into(),
                        col: 4,
                        s: None,
                        t: CellTypeTag::Error,
                        v: Some("#DIV/0!".to_string()),
                        f: None,
                        is: None,
                    },
                ],
            }],
        };

        let rows = get_rows(&ws, &sst, &[]).unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].1[0].1, CellValue::String("text".to_string()));
        assert_eq!(rows[0].1[1].1, CellValue::Number(42.5));
        assert_eq!(rows[0].1[2].1, CellValue::Bool(true));
        assert_eq!(rows[0].1[3].1, CellValue::Error("#DIV/0!".to_string()));
    }

    #[test]
    fn test_get_rows_skips_rows_with_no_cells() {
        let mut ws = WorksheetXml::default();
        ws.sheet_data = SheetData {
            rows: vec![
                Row {
                    r: 1,
                    spans: None,
                    s: None,
                    custom_format: None,
                    ht: None,
                    hidden: None,
                    custom_height: None,
                    outline_level: None,
                    cells: vec![Cell {
                        r: "A1".into(),
                        col: 1,
                        s: None,
                        t: CellTypeTag::None,
                        v: Some("1".to_string()),
                        f: None,
                        is: None,
                    }],
                },
                // Row 2 exists but has no cells (e.g., only has row height set).
                Row {
                    r: 2,
                    spans: None,
                    s: None,
                    custom_format: None,
                    ht: Some(30.0),
                    hidden: None,
                    custom_height: Some(true),
                    outline_level: None,
                    cells: vec![],
                },
                Row {
                    r: 3,
                    spans: None,
                    s: None,
                    custom_format: None,
                    ht: None,
                    hidden: None,
                    custom_height: None,
                    outline_level: None,
                    cells: vec![Cell {
                        r: "A3".into(),
                        col: 1,
                        s: None,
                        t: CellTypeTag::None,
                        v: Some("3".to_string()),
                        f: None,
                        is: None,
                    }],
                },
            ],
        };

        let sst = SharedStringTable::new();
        let rows = get_rows(&ws, &sst, &[]).unwrap();
        // Only rows 1 and 3 should be returned (row 2 has no cells).
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].0, 1);
        assert_eq!(rows[1].0, 3);
    }

    #[test]
    fn test_get_rows_with_formula() {
        let mut ws = WorksheetXml::default();
        ws.sheet_data = SheetData {
            rows: vec![Row {
                r: 1,
                spans: None,
                s: None,
                custom_format: None,
                ht: None,
                hidden: None,
                custom_height: None,
                outline_level: None,
                cells: vec![Cell {
                    r: "A1".into(),
                    col: 1,
                    s: None,
                    t: CellTypeTag::None,
                    v: Some("42".to_string()),
                    f: Some(Box::new(sheetkit_xml::worksheet::CellFormula {
                        t: None,
                        reference: None,
                        si: None,
                        value: Some("B1+C1".to_string()),
                    })),
                    is: None,
                }],
            }],
        };

        let sst = SharedStringTable::new();
        let rows = get_rows(&ws, &sst, &[]).unwrap();
        assert_eq!(rows.len(), 1);
        match &rows[0].1[0].1 {
            CellValue::Formula { expr, result } => {
                assert_eq!(expr, "B1+C1");
                assert_eq!(*result, Some(Box::new(CellValue::Number(42.0))));
            }
            _ => panic!("expected Formula"),
        }
    }

    #[test]
    fn test_get_rows_with_inline_string() {
        let mut ws = WorksheetXml::default();
        ws.sheet_data = SheetData {
            rows: vec![Row {
                r: 1,
                spans: None,
                s: None,
                custom_format: None,
                ht: None,
                hidden: None,
                custom_height: None,
                outline_level: None,
                cells: vec![Cell {
                    r: "A1".into(),
                    col: 1,
                    s: None,
                    t: CellTypeTag::InlineString,
                    v: None,
                    f: None,
                    is: Some(Box::new(sheetkit_xml::worksheet::InlineString {
                        t: Some("inline text".to_string()),
                    })),
                }],
            }],
        };

        let sst = SharedStringTable::new();
        let rows = get_rows(&ws, &sst, &[]).unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].1[0].1, CellValue::String("inline text".to_string()));
    }

    // -- set_row_style / get_row_style tests --

    #[test]
    fn test_get_row_style_default_is_zero() {
        let ws = WorksheetXml::default();
        assert_eq!(get_row_style(&ws, 1), 0);
    }

    #[test]
    fn test_get_row_style_nonexistent_row_is_zero() {
        let ws = sample_ws();
        assert_eq!(get_row_style(&ws, 99), 0);
    }

    #[test]
    fn test_set_row_style_applies_style() {
        let mut ws = sample_ws();
        set_row_style(&mut ws, 1, 5).unwrap();

        let row = ws.sheet_data.rows.iter().find(|r| r.r == 1).unwrap();
        assert_eq!(row.s, Some(5));
        assert_eq!(row.custom_format, Some(true));
    }

    #[test]
    fn test_set_row_style_applies_to_existing_cells() {
        let mut ws = sample_ws();
        set_row_style(&mut ws, 1, 3).unwrap();

        let row = ws.sheet_data.rows.iter().find(|r| r.r == 1).unwrap();
        for cell in &row.cells {
            assert_eq!(cell.s, Some(3));
        }
    }

    #[test]
    fn test_get_row_style_after_set() {
        let mut ws = sample_ws();
        set_row_style(&mut ws, 2, 7).unwrap();
        assert_eq!(get_row_style(&ws, 2), 7);
    }

    #[test]
    fn test_set_row_style_creates_row_if_missing() {
        let mut ws = WorksheetXml::default();
        set_row_style(&mut ws, 5, 2).unwrap();

        assert_eq!(ws.sheet_data.rows.len(), 1);
        assert_eq!(ws.sheet_data.rows[0].r, 5);
        assert_eq!(ws.sheet_data.rows[0].s, Some(2));
    }

    #[test]
    fn test_set_row_style_zero_clears_custom_format() {
        let mut ws = sample_ws();
        set_row_style(&mut ws, 1, 5).unwrap();
        set_row_style(&mut ws, 1, 0).unwrap();

        let row = ws.sheet_data.rows.iter().find(|r| r.r == 1).unwrap();
        assert_eq!(row.s, Some(0));
        assert_eq!(row.custom_format, None);
    }

    #[test]
    fn test_set_row_style_row_zero_returns_error() {
        let mut ws = WorksheetXml::default();
        let result = set_row_style(&mut ws, 0, 1);
        assert!(result.is_err());
    }
}