ftui-harness 0.4.0

Test harness and reference fixtures for FrankenTUI.
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
#![forbid(unsafe_code)]

//! Snapshot/golden testing and time-travel debugging for FrankenTUI.
//!
//! - **Snapshot testing**: Captures `Buffer` output as text, compares against stored `.snap` files.
//! - **Time-travel debugging**: Records compressed frame snapshots for rewind inspection.
//!
//! Captures `Buffer` output as plain text or ANSI-styled text, compares
//! against stored snapshots, and shows diffs on mismatch.
//!
//! # Role in FrankenTUI
//! `ftui-harness` is the verification layer. It powers snapshot tests,
//! time-travel debugging, and deterministic rendering checks used across the
//! workspace.
//!
//! # How it fits in the system
//! The harness is not the primary demo app (use `ftui-demo-showcase` for that).
//! Instead, it is used by tests and CI to validate the behavior of render,
//! widgets, and runtime under controlled conditions.
//!
//! # Quick Start
//!
//! ```ignore
//! use ftui_harness::{assert_snapshot, MatchMode};
//!
//! #[test]
//! fn my_widget_renders_correctly() {
//!     let mut buf = Buffer::new(10, 3);
//!     // ... render widget into buf ...
//!     assert_snapshot!("my_widget_basic", &buf);
//! }
//! ```
//!
//! # Updating Snapshots
//!
//! Run tests with `BLESS=1` to create or update snapshot files:
//!
//! ```sh
//! BLESS=1 cargo test
//! ```
//!
//! Snapshot files are stored under `tests/snapshots/` relative to the
//! crate's `CARGO_MANIFEST_DIR`.

pub mod artifact_manifest;
pub mod asciicast;
pub mod baseline_capture;
pub mod benchmark_gate;
pub mod cost_surface;
pub mod determinism;
pub mod doctor_cost_profile;
pub mod doctor_topology;
pub mod failure_signatures;
pub mod fixture_runner;
pub mod fixture_suite;
pub mod flicker_detection;
pub mod frame_comparison;
pub mod golden;
pub mod hdd;
pub mod hotspot_extraction;
pub mod input_storm;
pub mod lab_integration;
pub mod layout_reuse;
pub mod optimization_policy;
pub mod presenter_equivalence;
pub mod proof_oracle;
pub mod proptest_support;
pub mod render_certificate;
pub mod resize_storm;
pub mod rollout_runbook;
pub mod rollout_scorecard;
pub mod shadow_run;
pub mod terminal_model;
pub mod time_travel;
pub mod time_travel_inspector;
pub mod trace_replay;
pub mod validation_matrix;

#[cfg(feature = "pty-capture")]
pub mod pty_capture;

use std::fmt::Write as FmtWrite;
use std::path::{Path, PathBuf};

use ftui_core::terminal_capabilities::{TerminalCapabilities, TerminalProfile};
use ftui_render::buffer::Buffer;
use ftui_render::cell::{PackedRgba, StyleFlags};
use ftui_render::grapheme_pool::GraphemePool;

// Re-export types useful for harness users.
pub use determinism::{
    DeterminismFixture, JsonValue, LabScenario, LabScenarioContext, LabScenarioResult,
    LabScenarioRun, TestJsonlLogger, lab_scenarios_run_total,
};
pub use ftui_core::geometry::Rect;
pub use ftui_render::buffer;
pub use ftui_render::cell;
pub use lab_integration::{
    Lab, LabConfig, LabOutput, LabSession, Recording, ReplayResult, assert_outputs_match,
    lab_recordings_total, lab_replays_total,
};
pub use time_travel_inspector::TimeTravelInspector;

// Validation infrastructure re-exports.
pub use benchmark_gate::{BenchmarkGate, GateResult, Measurement, MetricVerdict, Threshold};
pub use rollout_scorecard::{
    RolloutEvidenceBundle, RolloutScorecard, RolloutScorecardConfig, RolloutSummary, RolloutVerdict,
};
pub use shadow_run::{ShadowRun, ShadowRunConfig, ShadowRunResult, ShadowVerdict};

// ============================================================================
// Buffer → Text Conversion
// ============================================================================

/// Convert a `Buffer` to a plain text string.
///
/// Each row becomes one line. Empty cells become spaces. Continuation cells
/// (trailing cells of wide characters) are skipped so wide characters occupy
/// their natural display width in the output string.
///
/// Grapheme-pool references (multi-codepoint clusters) are rendered as `?`
/// repeated to match the grapheme's display width, since the pool is not
/// available here. This ensures each output line has consistent display width.
pub fn buffer_to_text(buf: &Buffer) -> String {
    let capacity = (buf.width() as usize + 1) * buf.height() as usize;
    let mut out = String::with_capacity(capacity);

    for y in 0..buf.height() {
        if y > 0 {
            out.push('\n');
        }
        for x in 0..buf.width() {
            let cell = buf.get(x, y).unwrap();
            if cell.is_continuation() {
                continue;
            }
            if cell.is_empty() {
                out.push(' ');
            } else if let Some(c) = cell.content.as_char() {
                out.push(c);
            } else {
                // Grapheme ID — pool not available, use width-correct placeholder
                let w = cell.content.width();
                for _ in 0..w.max(1) {
                    out.push('?');
                }
            }
        }
    }
    out
}

/// Convert a `Buffer` to a plain text string, resolving grapheme pool references.
///
/// Like [`buffer_to_text`], but takes an optional [`GraphemePool`] to resolve
/// multi-codepoint grapheme clusters to their actual text. When the pool is
/// `None` or a grapheme ID cannot be resolved, falls back to `?` repeated to
/// match the grapheme's display width.
pub fn buffer_to_text_with_pool(buf: &Buffer, pool: Option<&GraphemePool>) -> String {
    let capacity = (buf.width() as usize + 1) * buf.height() as usize;
    let mut out = String::with_capacity(capacity);

    for y in 0..buf.height() {
        if y > 0 {
            out.push('\n');
        }
        for x in 0..buf.width() {
            let cell = buf.get(x, y).unwrap();
            if cell.is_continuation() {
                continue;
            }
            if cell.is_empty() {
                out.push(' ');
            } else if let Some(c) = cell.content.as_char() {
                out.push(c);
            } else if let (Some(pool), Some(gid)) = (pool, cell.content.grapheme_id()) {
                if let Some(text) = pool.get(gid) {
                    out.push_str(text);
                } else {
                    let w = cell.content.width();
                    for _ in 0..w.max(1) {
                        out.push('?');
                    }
                }
            } else {
                // No pool or not a grapheme — width-correct placeholder
                let w = cell.content.width();
                for _ in 0..w.max(1) {
                    out.push('?');
                }
            }
        }
    }
    out
}

/// Convert a `Buffer` to text with inline ANSI escape codes.
///
/// Emits SGR sequences when foreground, background, or style flags change
/// between adjacent cells. Resets styling at the end of each row.
pub fn buffer_to_ansi(buf: &Buffer) -> String {
    let capacity = (buf.width() as usize + 32) * buf.height() as usize;
    let mut out = String::with_capacity(capacity);

    for y in 0..buf.height() {
        if y > 0 {
            out.push('\n');
        }

        let mut prev_fg = PackedRgba::WHITE; // Cell default fg
        let mut prev_bg = PackedRgba::TRANSPARENT; // Cell default bg
        let mut prev_flags = StyleFlags::empty();
        let mut style_active = false;

        for x in 0..buf.width() {
            let cell = buf.get(x, y).unwrap();
            if cell.is_continuation() {
                continue;
            }

            let fg = cell.fg;
            let bg = cell.bg;
            let flags = cell.attrs.flags();

            let style_changed = fg != prev_fg || bg != prev_bg || flags != prev_flags;

            if style_changed {
                let has_style =
                    fg != PackedRgba::WHITE || bg != PackedRgba::TRANSPARENT || !flags.is_empty();

                if has_style {
                    // Reset and re-emit
                    if style_active {
                        out.push_str("\x1b[0m");
                    }

                    let mut params: Vec<String> = Vec::new();
                    if !flags.is_empty() {
                        if flags.contains(StyleFlags::BOLD) {
                            params.push("1".into());
                        }
                        if flags.contains(StyleFlags::DIM) {
                            params.push("2".into());
                        }
                        if flags.contains(StyleFlags::ITALIC) {
                            params.push("3".into());
                        }
                        if flags.contains(StyleFlags::UNDERLINE) {
                            params.push("4".into());
                        }
                        if flags.contains(StyleFlags::BLINK) {
                            params.push("5".into());
                        }
                        if flags.contains(StyleFlags::REVERSE) {
                            params.push("7".into());
                        }
                        if flags.contains(StyleFlags::HIDDEN) {
                            params.push("8".into());
                        }
                        if flags.contains(StyleFlags::STRIKETHROUGH) {
                            params.push("9".into());
                        }
                    }
                    if fg.a() > 0 && fg != PackedRgba::WHITE {
                        params.push(format!("38;2;{};{};{}", fg.r(), fg.g(), fg.b()));
                    }
                    if bg.a() > 0 && bg != PackedRgba::TRANSPARENT {
                        params.push(format!("48;2;{};{};{}", bg.r(), bg.g(), bg.b()));
                    }

                    if !params.is_empty() {
                        write!(out, "\x1b[{}m", params.join(";")).unwrap();
                        style_active = true;
                    }
                } else if style_active {
                    out.push_str("\x1b[0m");
                    style_active = false;
                }

                prev_fg = fg;
                prev_bg = bg;
                prev_flags = flags;
            }

            if cell.is_empty() {
                out.push(' ');
            } else if let Some(c) = cell.content.as_char() {
                out.push(c);
            } else {
                // Grapheme ID — pool not available, use width-correct placeholder
                let w = cell.content.width();
                for _ in 0..w.max(1) {
                    out.push('?');
                }
            }
        }

        if style_active {
            out.push_str("\x1b[0m");
        }
    }
    out
}

// ============================================================================
// Match Modes & Normalization
// ============================================================================

/// Comparison mode for snapshot testing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MatchMode {
    /// Byte-exact string comparison.
    Exact,
    /// Trim trailing whitespace on each line before comparing.
    TrimTrailing,
    /// Collapse all whitespace runs to single spaces and trim each line.
    Fuzzy,
}

/// Normalize text according to the requested match mode.
fn normalize(text: &str, mode: MatchMode) -> String {
    match mode {
        MatchMode::Exact => text.to_string(),
        MatchMode::TrimTrailing => text
            .lines()
            .map(|l| l.trim_end())
            .collect::<Vec<_>>()
            .join("\n"),
        MatchMode::Fuzzy => text
            .lines()
            .map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
            .collect::<Vec<_>>()
            .join("\n"),
    }
}

// ============================================================================
// Diff
// ============================================================================

/// Compute a simple line-by-line diff between two text strings.
///
/// Returns a human-readable string where:
/// - Lines prefixed with ` ` are identical in both.
/// - Lines prefixed with `-` appear only in `expected`.
/// - Lines prefixed with `+` appear only in `actual`.
///
/// Returns an empty string when the inputs are identical.
pub fn diff_text(expected: &str, actual: &str) -> String {
    let expected_lines: Vec<&str> = expected.lines().collect();
    let actual_lines: Vec<&str> = actual.lines().collect();

    let max_lines = expected_lines.len().max(actual_lines.len());
    let mut out = String::new();
    let mut has_diff = false;

    for i in 0..max_lines {
        let exp = expected_lines.get(i).copied();
        let act = actual_lines.get(i).copied();

        match (exp, act) {
            (Some(e), Some(a)) if e == a => {
                writeln!(out, " {e}").unwrap();
            }
            (Some(e), Some(a)) => {
                writeln!(out, "-{e}").unwrap();
                writeln!(out, "+{a}").unwrap();
                has_diff = true;
            }
            (Some(e), None) => {
                writeln!(out, "-{e}").unwrap();
                has_diff = true;
            }
            (None, Some(a)) => {
                writeln!(out, "+{a}").unwrap();
                has_diff = true;
            }
            (None, None) => {}
        }
    }

    if has_diff { out } else { String::new() }
}

// ============================================================================
// Snapshot Assertion
// ============================================================================

/// Resolve the active test profile from the environment.
///
/// Returns `None` when unset or when explicitly set to `detected`.
#[must_use]
pub fn current_test_profile() -> Option<TerminalProfile> {
    std::env::var("FTUI_TEST_PROFILE")
        .ok()
        .and_then(|value| value.parse::<TerminalProfile>().ok())
        .filter(|profile| *profile != TerminalProfile::Detected)
}

fn snapshot_name_with_profile(name: &str) -> String {
    if let Some(profile) = current_test_profile() {
        let suffix = format!("__{}", profile.as_str());
        if name.ends_with(&suffix) {
            return name.to_string();
        }
        return format!("{name}{suffix}");
    }
    name.to_string()
}

/// Resolve the snapshot file path.
fn snapshot_path(base_dir: &Path, name: &str) -> PathBuf {
    let resolved_name = snapshot_name_with_profile(name);
    base_dir
        .join("tests")
        .join("snapshots")
        .join(format!("{resolved_name}.snap"))
}

/// Check if the `BLESS` environment variable is set.
fn is_bless() -> bool {
    std::env::var("BLESS").is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
}

/// Assert that a buffer's text representation matches a stored snapshot.
///
/// # Arguments
///
/// * `name`     – Snapshot identifier (used as the `.snap` filename).
/// * `buf`      – The buffer to compare.
/// * `base_dir` – Root directory for snapshot storage (use `env!("CARGO_MANIFEST_DIR")`).
/// * `mode`     – How to compare the text (exact, trim trailing, or fuzzy).
///
/// # Panics
///
/// * If the snapshot file does not exist and `BLESS=1` is **not** set.
/// * If the buffer output does not match the stored snapshot.
///
/// # Updating Snapshots
///
/// Set `BLESS=1` to write the current buffer output as the new snapshot:
///
/// ```sh
/// BLESS=1 cargo test
/// ```
pub fn assert_buffer_snapshot(name: &str, buf: &Buffer, base_dir: &str, mode: MatchMode) {
    let base = Path::new(base_dir);
    let path = snapshot_path(base, name);
    let actual = buffer_to_text(buf);

    if is_bless() {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create snapshot directory");
        }
        std::fs::write(&path, &actual).expect("failed to write snapshot");
        return;
    }

    match std::fs::read_to_string(&path) {
        Ok(expected) => {
            let norm_expected = normalize(&expected, mode);
            let norm_actual = normalize(&actual, mode);

            if norm_expected != norm_actual {
                let diff = diff_text(&norm_expected, &norm_actual);
                std::panic::panic_any(format!(
                    // ubs:ignore — snapshot assertion helper intentionally panics in tests
                    "\n\
                     === Snapshot mismatch: '{name}' ===\n\
                     File: {}\n\
                     Mode: {mode:?}\n\
                     Set BLESS=1 to update.\n\n\
                     Diff (- expected, + actual):\n{diff}",
                    path.display()
                ));
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            std::panic::panic_any(format!(
                // ubs:ignore — snapshot assertion helper intentionally panics in tests
                "\n\
                 === No snapshot found: '{name}' ===\n\
                 Expected at: {}\n\
                 Run with BLESS=1 to create it.\n\n\
                 Actual output ({w}x{h}):\n{actual}",
                path.display(),
                w = buf.width(),
                h = buf.height(),
            ));
        }
        Err(e) => {
            std::panic::panic_any(format!(
                // ubs:ignore — snapshot assertion helper intentionally panics in tests
                "Failed to read snapshot '{}': {e}",
                path.display()
            ));
        }
    }
}

/// Assert that a buffer's ANSI-styled representation matches a stored snapshot.
///
/// Behaves like [`assert_buffer_snapshot`] but captures ANSI escape codes.
/// Snapshot files have the `.ansi.snap` suffix.
pub fn assert_buffer_snapshot_ansi(name: &str, buf: &Buffer, base_dir: &str) {
    let base = Path::new(base_dir);
    let resolved_name = snapshot_name_with_profile(name);
    let path = base
        .join("tests")
        .join("snapshots")
        .join(format!("{resolved_name}.ansi.snap"));
    let actual = buffer_to_ansi(buf);

    if is_bless() {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create snapshot directory");
        }
        std::fs::write(&path, &actual).expect("failed to write snapshot");
        return;
    }

    match std::fs::read_to_string(&path) {
        Ok(expected) => {
            if expected != actual {
                let diff = diff_text(&expected, &actual);
                std::panic::panic_any(format!(
                    // ubs:ignore — snapshot assertion helper intentionally panics in tests
                    "\n\
                     === ANSI snapshot mismatch: '{name}' ===\n\
                     File: {}\n\
                     Set BLESS=1 to update.\n\n\
                     Diff (- expected, + actual):\n{diff}",
                    path.display()
                ));
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            std::panic::panic_any(format!(
                // ubs:ignore — snapshot assertion helper intentionally panics in tests
                "\n\
                 === No ANSI snapshot found: '{resolved_name}' ===\n\
                 Expected at: {}\n\
                 Run with BLESS=1 to create it.\n\n\
                 Actual output:\n{actual}",
                path.display(),
            ));
        }
        Err(e) => {
            std::panic::panic_any(format!(
                // ubs:ignore — snapshot assertion helper intentionally panics in tests
                "Failed to read snapshot '{}': {e}",
                path.display()
            ));
        }
    }
}

// ============================================================================
// Convenience Macros
// ============================================================================

/// Assert that a buffer matches a stored snapshot (plain text).
///
/// Uses `CARGO_MANIFEST_DIR` to locate the snapshot directory automatically.
///
/// # Examples
///
/// ```ignore
/// // Default mode: TrimTrailing
/// assert_snapshot!("widget_basic", &buf);
///
/// // Explicit mode
/// assert_snapshot!("widget_exact", &buf, MatchMode::Exact);
/// ```
#[macro_export]
macro_rules! assert_snapshot {
    ($name:expr, $buf:expr) => {
        $crate::assert_buffer_snapshot(
            $name,
            $buf,
            env!("CARGO_MANIFEST_DIR"),
            $crate::MatchMode::TrimTrailing,
        )
    };
    ($name:expr, $buf:expr, $mode:expr) => {
        $crate::assert_buffer_snapshot($name, $buf, env!("CARGO_MANIFEST_DIR"), $mode)
    };
}

/// Assert that a buffer matches a stored ANSI snapshot (with style info).
///
/// Uses `CARGO_MANIFEST_DIR` to locate the snapshot directory automatically.
#[macro_export]
macro_rules! assert_snapshot_ansi {
    ($name:expr, $buf:expr) => {
        $crate::assert_buffer_snapshot_ansi($name, $buf, env!("CARGO_MANIFEST_DIR"))
    };
}

// ============================================================================
// Profile Matrix (bd-k4lj.5)
// ============================================================================

/// Comparison mode for cross-profile output checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProfileCompareMode {
    /// Do not compare outputs across profiles.
    None,
    /// Report diffs to stderr but do not fail.
    Report,
    /// Fail the test on the first diff.
    Strict,
}

impl ProfileCompareMode {
    /// Resolve compare mode from `FTUI_TEST_PROFILE_COMPARE`.
    #[must_use]
    pub fn from_env() -> Self {
        match std::env::var("FTUI_TEST_PROFILE_COMPARE")
            .ok()
            .map(|v| v.to_lowercase())
            .as_deref()
        {
            Some("strict") | Some("1") | Some("true") => Self::Strict,
            Some("report") | Some("log") => Self::Report,
            _ => Self::None,
        }
    }
}

/// Snapshot output captured for a specific profile.
#[derive(Debug, Clone)]
pub struct ProfileSnapshot {
    pub profile: TerminalProfile,
    pub text: String,
    pub checksum: String,
}

/// Run a test closure across multiple profiles and optionally compare outputs.
///
/// The closure receives the profile id and a `TerminalCapabilities` derived
/// from that profile. Use `FTUI_TEST_PROFILE_COMPARE=strict` to fail on
/// differences or `FTUI_TEST_PROFILE_COMPARE=report` to emit diffs without
/// failing.
pub fn profile_matrix_text<F>(profiles: &[TerminalProfile], mut render: F) -> Vec<ProfileSnapshot>
where
    F: FnMut(TerminalProfile, &TerminalCapabilities) -> String,
{
    profile_matrix_text_with_options(
        profiles,
        ProfileCompareMode::from_env(),
        MatchMode::TrimTrailing,
        &mut render,
    )
}

/// Profile matrix runner with explicit comparison options.
pub fn profile_matrix_text_with_options<F>(
    profiles: &[TerminalProfile],
    compare: ProfileCompareMode,
    mode: MatchMode,
    render: &mut F,
) -> Vec<ProfileSnapshot>
where
    F: FnMut(TerminalProfile, &TerminalCapabilities) -> String,
{
    let mut outputs = Vec::with_capacity(profiles.len());
    for profile in profiles {
        let caps = TerminalCapabilities::from_profile(*profile);
        let text = render(*profile, &caps);
        let checksum = crate::golden::compute_text_checksum(&text);
        outputs.push(ProfileSnapshot {
            profile: *profile,
            text,
            checksum,
        });
    }

    if compare != ProfileCompareMode::None && outputs.len() > 1 {
        let baseline = normalize(&outputs[0].text, mode);
        let baseline_profile = outputs[0].profile;
        for snapshot in outputs.iter().skip(1) {
            let candidate = normalize(&snapshot.text, mode);
            if baseline != candidate {
                let diff = diff_text(&baseline, &candidate);
                match compare {
                    ProfileCompareMode::Report => {
                        eprintln!(
                            "=== Profile comparison drift: {} vs {} ===\n{diff}",
                            baseline_profile.as_str(),
                            snapshot.profile.as_str()
                        );
                    }
                    ProfileCompareMode::Strict => {
                        std::panic::panic_any(format!(
                            // ubs:ignore — snapshot assertion helper intentionally panics in tests
                            "Profile comparison drift: {} vs {}\n{diff}",
                            baseline_profile.as_str(),
                            snapshot.profile.as_str()
                        ));
                    }
                    ProfileCompareMode::None => {}
                }
            }
        }
    }

    outputs
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use ftui_render::cell::{Cell, CellContent, GraphemeId};

    #[test]
    fn buffer_to_text_empty() {
        let buf = Buffer::new(5, 2);
        let text = buffer_to_text(&buf);
        assert_eq!(text, "     \n     ");
    }

    #[test]
    fn buffer_to_text_simple() {
        let mut buf = Buffer::new(5, 1);
        buf.set(0, 0, Cell::from_char('H'));
        buf.set(1, 0, Cell::from_char('i'));
        let text = buffer_to_text(&buf);
        assert_eq!(text, "Hi   ");
    }

    #[test]
    fn buffer_to_text_multiline() {
        let mut buf = Buffer::new(3, 2);
        buf.set(0, 0, Cell::from_char('A'));
        buf.set(1, 0, Cell::from_char('B'));
        buf.set(0, 1, Cell::from_char('C'));
        let text = buffer_to_text(&buf);
        assert_eq!(text, "AB \nC  ");
    }

    #[test]
    fn buffer_to_text_wide_char() {
        let mut buf = Buffer::new(4, 1);
        // '中' is width 2 — head at x=0, continuation at x=1
        buf.set(0, 0, Cell::from_char(''));
        buf.set(2, 0, Cell::from_char('!'));
        let text = buffer_to_text(&buf);
        // '中' occupies 1 char in text, continuation skipped, '!' at col 2, space at col 3
        assert_eq!(text, "中! ");
    }

    #[test]
    fn buffer_to_text_grapheme_width_correct_placeholder() {
        // Simulate a width-2 grapheme (e.g., emoji like "⚙️") stored in pool
        let gid = GraphemeId::new(1, 0, 2); // slot 1, generation 0, width 2
        let content = CellContent::from_grapheme(gid);
        let mut buf = Buffer::new(6, 1);
        // Buffer::set automatically writes CONTINUATION at x=1 for width-2 content
        buf.set(0, 0, Cell::new(content));
        buf.set(2, 0, Cell::from_char('A'));
        buf.set(3, 0, Cell::from_char('B'));
        let text = buffer_to_text(&buf);
        // Grapheme should produce "??" (2 chars for width 2), then "AB", then 2 spaces
        assert_eq!(text, "??AB  ");
    }

    #[test]
    fn buffer_to_text_with_pool_resolves_grapheme() {
        let mut pool = GraphemePool::new();
        let gid = pool.intern("\u{fe0f}", 2);
        let content = CellContent::from_grapheme(gid);
        let mut buf = Buffer::new(6, 1);
        // Buffer::set automatically writes CONTINUATION at x=1 for width-2 content
        buf.set(0, 0, Cell::new(content));
        buf.set(2, 0, Cell::from_char('A'));
        let text = buffer_to_text_with_pool(&buf, Some(&pool));
        // Pool resolves to actual emoji text, then "A", then 3 spaces
        assert_eq!(text, "\u{fe0f}A   ");
    }

    #[test]
    fn buffer_to_text_with_pool_none_falls_back() {
        let gid = GraphemeId::new(1, 0, 2);
        let content = CellContent::from_grapheme(gid);
        let mut buf = Buffer::new(4, 1);
        // Buffer::set automatically writes CONTINUATION at x=1 for width-2 content
        buf.set(0, 0, Cell::new(content));
        buf.set(2, 0, Cell::from_char('!'));
        let text = buffer_to_text_with_pool(&buf, None);
        // No pool → falls back to "??" placeholder (width 2)
        assert_eq!(text, "??! ");
    }

    #[test]
    fn buffer_to_ansi_grapheme_width_correct_placeholder() {
        let gid = GraphemeId::new(1, 0, 2);
        let content = CellContent::from_grapheme(gid);
        let mut buf = Buffer::new(4, 1);
        // Buffer::set automatically writes CONTINUATION at x=1 for width-2 content
        buf.set(0, 0, Cell::new(content));
        buf.set(2, 0, Cell::from_char('X'));
        let ansi = buffer_to_ansi(&buf);
        // No style → no escapes. Grapheme produces "??", then "X", then space
        assert_eq!(ansi, "??X ");
    }

    #[test]
    fn buffer_to_ansi_no_style() {
        let mut buf = Buffer::new(3, 1);
        buf.set(0, 0, Cell::from_char('X'));
        let ansi = buffer_to_ansi(&buf);
        // No style changes from default → no escape codes
        assert_eq!(ansi, "X  ");
    }

    #[test]
    fn buffer_to_ansi_with_style() {
        let mut buf = Buffer::new(3, 1);
        let styled = Cell::from_char('R').with_fg(PackedRgba::rgb(255, 0, 0));
        buf.set(0, 0, styled);
        let ansi = buffer_to_ansi(&buf);
        // Should contain SGR for red foreground
        assert!(ansi.contains("\x1b[38;2;255;0;0m"));
        assert!(ansi.contains('R'));
        // Should end with reset
        assert!(ansi.contains("\x1b[0m"));
    }

    #[test]
    fn diff_text_identical() {
        let diff = diff_text("hello\nworld", "hello\nworld");
        assert!(diff.is_empty());
    }

    #[test]
    fn diff_text_single_line_change() {
        let diff = diff_text("hello\nworld", "hello\nearth");
        assert!(diff.contains("-world"));
        assert!(diff.contains("+earth"));
        assert!(diff.contains(" hello"));
    }

    #[test]
    fn diff_text_added_lines() {
        let diff = diff_text("A", "A\nB");
        assert!(diff.contains("+B"));
    }

    #[test]
    fn diff_text_removed_lines() {
        let diff = diff_text("A\nB", "A");
        assert!(diff.contains("-B"));
    }

    #[test]
    fn normalize_exact() {
        let text = "  hello  \n  world  ";
        assert_eq!(normalize(text, MatchMode::Exact), text);
    }

    #[test]
    fn normalize_trim_trailing() {
        let text = "hello  \n  world  ";
        assert_eq!(normalize(text, MatchMode::TrimTrailing), "hello\n  world");
    }

    #[test]
    fn normalize_fuzzy() {
        let text = "  hello   world  \n  foo   bar  ";
        assert_eq!(normalize(text, MatchMode::Fuzzy), "hello world\nfoo bar");
    }

    #[test]
    fn snapshot_path_construction() {
        let p = snapshot_path(Path::new("/crates/my-crate"), "widget_test");
        assert_eq!(
            p,
            PathBuf::from("/crates/my-crate/tests/snapshots/widget_test.snap")
        );
    }

    #[test]
    fn bless_creates_snapshot() {
        let dir = std::env::temp_dir().join("ftui_harness_test_bless");
        let _ = std::fs::remove_dir_all(&dir);

        let mut buf = Buffer::new(3, 1);
        buf.set(0, 0, Cell::from_char('X'));

        // Simulate BLESS=1 by writing directly
        let path = snapshot_path(&dir, "bless_test");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let text = buffer_to_text(&buf);
        std::fs::write(&path, &text).unwrap();

        // Verify file was created with correct content
        let stored = std::fs::read_to_string(&path).unwrap();
        assert_eq!(stored, "X  ");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn snapshot_match_succeeds() {
        let dir = std::env::temp_dir().join("ftui_harness_test_match");
        let _ = std::fs::remove_dir_all(&dir);

        let mut buf = Buffer::new(5, 1);
        buf.set(0, 0, Cell::from_char('O'));
        buf.set(1, 0, Cell::from_char('K'));

        // Write snapshot
        let path = snapshot_path(&dir, "match_test");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "OK   ").unwrap();

        // Assert should pass
        assert_buffer_snapshot("match_test", &buf, dir.to_str().unwrap(), MatchMode::Exact);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn snapshot_trim_trailing_mode() {
        let dir = std::env::temp_dir().join("ftui_harness_test_trim");
        let _ = std::fs::remove_dir_all(&dir);

        let mut buf = Buffer::new(5, 1);
        buf.set(0, 0, Cell::from_char('A'));

        // Stored snapshot has no trailing spaces
        let path = snapshot_path(&dir, "trim_test");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "A").unwrap();

        // Should match because TrimTrailing strips trailing spaces
        assert_buffer_snapshot(
            "trim_test",
            &buf,
            dir.to_str().unwrap(),
            MatchMode::TrimTrailing,
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[should_panic(expected = "Snapshot mismatch")]
    fn snapshot_mismatch_panics() {
        let dir = std::env::temp_dir().join("ftui_harness_test_mismatch");
        let _ = std::fs::remove_dir_all(&dir);

        let mut buf = Buffer::new(3, 1);
        buf.set(0, 0, Cell::from_char('X'));

        // Write mismatching snapshot
        let path = snapshot_path(&dir, "mismatch_test");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "Y  ").unwrap();

        assert_buffer_snapshot(
            "mismatch_test",
            &buf,
            dir.to_str().unwrap(),
            MatchMode::Exact,
        );
    }

    #[test]
    #[should_panic(expected = "No snapshot found")]
    fn missing_snapshot_panics() {
        let dir = std::env::temp_dir().join("ftui_harness_test_missing");
        let _ = std::fs::remove_dir_all(&dir);

        let buf = Buffer::new(3, 1);
        assert_buffer_snapshot("nonexistent", &buf, dir.to_str().unwrap(), MatchMode::Exact);
    }

    #[test]
    fn profile_matrix_collects_outputs() {
        let profiles = [TerminalProfile::Modern, TerminalProfile::Dumb];
        let outputs = profile_matrix_text_with_options(
            &profiles,
            ProfileCompareMode::Report,
            MatchMode::Exact,
            &mut |profile, _caps| format!("profile:{}", profile.as_str()),
        );
        assert_eq!(outputs.len(), 2);
        assert!(outputs.iter().all(|o| o.checksum.starts_with("blake3:")));
    }

    #[test]
    fn profile_matrix_strict_allows_identical_output() {
        let profiles = [TerminalProfile::Modern, TerminalProfile::Dumb];
        let outputs = profile_matrix_text_with_options(
            &profiles,
            ProfileCompareMode::Strict,
            MatchMode::Exact,
            &mut |_profile, _caps| "same".to_string(),
        );
        assert_eq!(outputs.len(), 2);
    }
}