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
#![forbid(unsafe_code)]

//! Flicker/Tear Detection Integration Tests (bd-1rz0.18)
//!
//! End-to-end tests that verify the full render pipeline
//! (Buffer → Diff → Presenter → ANSI) produces flicker-free output
//! when synchronized output is enabled, and correctly detects
//! flicker-inducing patterns when it is not.
//!
//! # Test Categories
//!
//! 1. **Pipeline Integration**: Feed real Presenter output to FlickerDetector
//! 2. **Property Tests**: Verify invariants across random buffer configurations
//! 3. **No-Ghosting on Resize**: Shrink/grow cycles through the full pipeline
//! 4. **Golden Checksums**: Deterministic output verification
//! 5. **Multi-Frame Scenarios**: Realistic render loop simulations
//!
//! # Invariants Verified
//!
//! - Synced presenter output is always flicker-free
//! - Every changed cell appears in diff (no ghosting)
//! - Diff application is idempotent through the presenter
//! - Monotonic row-major ordering is preserved through runs
//! - Resize with buffer clear produces complete output (no stale content)

use ftui_render::buffer::Buffer;
use ftui_render::cell::{Cell, PackedRgba};
use ftui_render::diff::BufferDiff;
use ftui_render::presenter::{Presenter, TerminalCapabilities};

use ftui_harness::flicker_detection::{FlickerDetector, analyze_stream, analyze_stream_with_id};
use ftui_harness::golden::compute_text_checksum;

// ============================================================================
// Helpers
// ============================================================================

/// Create capabilities with sync output enabled.
fn caps_with_sync() -> TerminalCapabilities {
    let mut caps = TerminalCapabilities::basic();
    caps.sync_output = true;
    caps
}

/// Create capabilities without sync output.
fn caps_without_sync() -> TerminalCapabilities {
    TerminalCapabilities::basic()
}

/// Render a buffer diff through the presenter and return the raw ANSI output.
fn present_to_bytes(buffer: &Buffer, diff: &BufferDiff, caps: TerminalCapabilities) -> Vec<u8> {
    let mut sink = Vec::new();
    let mut presenter = Presenter::new(&mut sink, caps);
    presenter.present(buffer, diff).unwrap();
    drop(presenter);
    sink
}

/// Render a frame (from blank → buffer) through the presenter with sync enabled.
fn present_frame_synced(buffer: &Buffer) -> Vec<u8> {
    let blank = Buffer::new(buffer.width(), buffer.height());
    let diff = BufferDiff::compute(&blank, buffer);
    present_to_bytes(buffer, &diff, caps_with_sync())
}

/// Render an incremental frame (prev → next) through the presenter with sync.
fn present_incremental_synced(prev: &Buffer, next: &Buffer) -> Vec<u8> {
    let diff = BufferDiff::compute(prev, next);
    present_to_bytes(next, &diff, caps_with_sync())
}

/// Build a test buffer with deterministic content at specific positions.
fn build_test_buffer(width: u16, height: u16, seed: u64) -> Buffer {
    let mut buf = Buffer::new(width, height);
    let num_cells = (width as u64 * height as u64).min(200);
    for i in 0..num_cells {
        let x = ((i.wrapping_mul(13).wrapping_add(seed.wrapping_mul(7))) % width as u64) as u16;
        let y = ((i.wrapping_mul(17).wrapping_add(seed.wrapping_mul(3))) % height as u64) as u16;
        let ch = char::from_u32(b'A' as u32 + (i % 26) as u32).unwrap();
        let r = ((i.wrapping_mul(31)) % 256) as u8;
        let g = ((i.wrapping_mul(47)) % 256) as u8;
        let b_val = ((i.wrapping_mul(71)) % 256) as u8;
        buf.set_raw(
            x,
            y,
            Cell::from_char(ch).with_fg(PackedRgba::rgb(r, g, b_val)),
        );
    }
    buf
}

// ============================================================================
// 1. Pipeline Integration Tests
// ============================================================================

#[test]
fn synced_single_frame_is_flicker_free() {
    let mut buf = Buffer::new(80, 24);
    for (i, ch) in "Hello, FrankenTUI!".chars().enumerate() {
        buf.set_raw(i as u16, 0, Cell::from_char(ch));
    }

    let output = present_frame_synced(&buf);
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
    assert_eq!(analysis.stats.total_frames, 1);
    assert_eq!(analysis.stats.complete_frames, 1);
}

#[test]
fn synced_multi_frame_render_loop() {
    let mut all_output = Vec::new();
    let mut prev = Buffer::new(40, 10);

    for frame_idx in 0u32..10 {
        let mut next = prev.clone();
        let msg = format!("Frame {frame_idx}");
        for (i, ch) in msg.chars().enumerate() {
            next.set_raw(i as u16, 0, Cell::from_char(ch));
        }
        // Status line changes each frame
        let status = format!("Status: OK #{frame_idx}");
        for (i, ch) in status.chars().enumerate() {
            next.set_raw(i as u16, 9, Cell::from_char(ch));
        }

        let output = present_incremental_synced(&prev, &next);
        all_output.extend_from_slice(&output);
        prev = next;
    }

    let analysis = analyze_stream(&all_output);
    analysis.assert_flicker_free();
    assert_eq!(analysis.stats.total_frames, 10);
    assert_eq!(analysis.stats.complete_frames, 10);
}

#[test]
fn synced_empty_diff_is_flicker_free() {
    let buf = Buffer::new(80, 24);
    let diff = BufferDiff::new();
    let output = present_to_bytes(&buf, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
}

#[test]
fn synced_full_screen_update_is_flicker_free() {
    // Every cell changed
    let old = Buffer::new(40, 12);
    let mut new = Buffer::new(40, 12);
    for y in 0..12u16 {
        for x in 0..40u16 {
            let ch = char::from_u32(b'A' as u32 + ((x + y) % 26) as u32).unwrap();
            new.set_raw(x, y, Cell::from_char(ch));
        }
    }

    let diff = BufferDiff::compute(&old, &new);
    let output = present_to_bytes(&new, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
    assert!(analysis.stats.sync_coverage() > 70.0);
}

#[test]
fn synced_styled_content_is_flicker_free() {
    let old = Buffer::new(30, 5);
    let mut new = Buffer::new(30, 5);

    // Create cells with different styles
    let red = PackedRgba::rgb(255, 0, 0);
    let green = PackedRgba::rgb(0, 255, 0);
    let blue = PackedRgba::rgb(0, 0, 255);

    for (i, ch) in "Red text".chars().enumerate() {
        new.set_raw(i as u16, 0, Cell::from_char(ch).with_fg(red));
    }
    for (i, ch) in "Green text".chars().enumerate() {
        new.set_raw(i as u16, 1, Cell::from_char(ch).with_fg(green));
    }
    for (i, ch) in "Blue text".chars().enumerate() {
        new.set_raw(i as u16, 2, Cell::from_char(ch).with_fg(blue));
    }

    let diff = BufferDiff::compute(&old, &new);
    let output = present_to_bytes(&new, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
}

#[test]
fn unsynced_output_detected_as_gap() {
    // Without sync, visible content should cause sync gaps
    let mut buf = Buffer::new(20, 5);
    for (i, ch) in "Visible content".chars().enumerate() {
        buf.set_raw(i as u16, 0, Cell::from_char(ch));
    }

    let old = Buffer::new(20, 5);
    let diff = BufferDiff::compute(&old, &buf);
    let output = present_to_bytes(&buf, &diff, caps_without_sync());
    let analysis = analyze_stream(&output);

    // Without sync, output should not be considered flicker-free
    // (visible bytes are emitted outside sync brackets)
    assert!(!analysis.flicker_free);
    assert!(analysis.stats.sync_gaps > 0);
}

// ============================================================================
// 2. Property Tests
// ============================================================================

/// Deterministic LCG for property-like tests (no proptest dep here).
struct Lcg(u64);

impl Lcg {
    fn new(seed: u64) -> Self {
        Self(seed)
    }

    fn next_u32(&mut self) -> u32 {
        self.0 = self
            .0
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1);
        (self.0 >> 32) as u32
    }

    fn next_range(&mut self, max: usize) -> usize {
        if max == 0 {
            return 0;
        }
        (self.next_u32() as usize) % max
    }

    fn next_char(&mut self) -> char {
        char::from_u32(b'A' as u32 + (self.next_u32() % 26)).unwrap()
    }

    fn next_color(&mut self) -> PackedRgba {
        let r = (self.next_u32() % 256) as u8;
        let g = (self.next_u32() % 256) as u8;
        let b = (self.next_u32() % 256) as u8;
        PackedRgba::rgb(r, g, b)
    }
}

#[test]
fn property_synced_presenter_always_flicker_free() {
    // For 16 different random buffer configurations, verify flicker-free output
    for seed in 0..16u64 {
        let mut rng = Lcg::new(seed);
        let width = 10 + rng.next_range(71) as u16; // 10-80
        let height = 5 + rng.next_range(26) as u16; // 5-30
        let num_changes = 1 + rng.next_range(200);

        let old = Buffer::new(width, height);
        let mut new = Buffer::new(width, height);

        for _ in 0..num_changes {
            let x = rng.next_range(width as usize) as u16;
            let y = rng.next_range(height as usize) as u16;
            new.set_raw(
                x,
                y,
                Cell::from_char(rng.next_char()).with_fg(rng.next_color()),
            );
        }

        let diff = BufferDiff::compute(&old, &new);
        let output = present_to_bytes(&new, &diff, caps_with_sync());
        let analysis = analyze_stream_with_id(&format!("prop-seed-{seed}"), &output);

        assert!(
            analysis.flicker_free,
            "seed {seed} ({}x{}, {} changes): not flicker-free\n\
             sync_gaps={}, partial_clears={}, incomplete={}",
            width,
            height,
            num_changes,
            analysis.stats.sync_gaps,
            analysis.stats.partial_clears,
            analysis.stats.total_frames - analysis.stats.complete_frames,
        );
    }
}

#[test]
fn property_incremental_frames_always_flicker_free() {
    // Simulate 8 incremental frame updates with random changes
    for seed in 0..8u64 {
        let mut rng = Lcg::new(seed ^ 0xdead_beef);
        let width = 20 + rng.next_range(61) as u16;
        let height = 8 + rng.next_range(23) as u16;
        let num_frames = 5 + rng.next_range(8);

        let mut all_output = Vec::new();
        let mut prev = Buffer::new(width, height);

        for _ in 0..num_frames {
            let mut next = prev.clone();
            let changes = 1 + rng.next_range(50);
            for _ in 0..changes {
                let x = rng.next_range(width as usize) as u16;
                let y = rng.next_range(height as usize) as u16;
                next.set_raw(
                    x,
                    y,
                    Cell::from_char(rng.next_char()).with_fg(rng.next_color()),
                );
            }

            let output = present_incremental_synced(&prev, &next);
            all_output.extend_from_slice(&output);
            prev = next;
        }

        let analysis = analyze_stream_with_id(&format!("incr-seed-{seed}"), &all_output);
        assert!(
            analysis.flicker_free,
            "seed {seed}: incremental frames not flicker-free"
        );
        assert_eq!(
            analysis.stats.total_frames, num_frames as u64,
            "seed {seed}: frame count mismatch"
        );
    }
}

#[test]
fn property_diff_completeness_through_presenter() {
    // Verify that every changed cell actually appears in presenter output.
    // We do this by comparing HeadlessTerm state after presenting.
    for seed in 0..8u64 {
        let mut rng = Lcg::new(seed ^ 0xbabe_face);
        let width = 10 + rng.next_range(30) as u16;
        let height = 5 + rng.next_range(15) as u16;

        let old = Buffer::new(width, height);
        let mut new = Buffer::new(width, height);

        let mut changed_positions = Vec::new();
        let num_changes = 1 + rng.next_range(50);
        for _ in 0..num_changes {
            let x = rng.next_range(width as usize) as u16;
            let y = rng.next_range(height as usize) as u16;
            let ch = rng.next_char();
            new.set_raw(x, y, Cell::from_char(ch));
            changed_positions.push((x, y, ch));
        }

        let diff = BufferDiff::compute(&old, &new);

        // Verify diff captures all changes
        for &(x, y, _ch) in &changed_positions {
            let old_cell = old.get_unchecked(x, y);
            let new_cell = new.get_unchecked(x, y);
            if !old_cell.bits_eq(new_cell) {
                let in_diff = diff.iter().any(|(dx, dy)| dx == x && dy == y);
                assert!(
                    in_diff,
                    "seed {seed}: changed cell at ({x},{y}) missing from diff — would ghost"
                );
            }
        }
    }
}

// ============================================================================
// 3. No-Ghosting on Resize Tests
// ============================================================================

#[test]
fn no_ghosting_after_shrink() {
    // Simulate: large buffer → smaller buffer. The smaller buffer should be
    // fully rendered with no stale content from the larger one.
    let mut large = Buffer::new(80, 24);
    for y in 0..24u16 {
        for x in 0..80u16 {
            large.set_raw(x, y, Cell::from_char('#'));
        }
    }

    // Simulate resize: create new smaller buffer with different content
    let mut small = Buffer::new(40, 12);
    for y in 0..12u16 {
        for x in 0..40u16 {
            small.set_raw(x, y, Cell::from_char('.'));
        }
    }

    // After resize, we diff against a blank buffer (simulating cleared state)
    let blank = Buffer::new(40, 12);
    let diff = BufferDiff::compute(&blank, &small);

    // Every cell in small should be in the diff
    assert_eq!(
        diff.len(),
        40 * 12,
        "After resize to blank, all cells should be in diff"
    );

    // Presenter output should be flicker-free
    let output = present_to_bytes(&small, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
}

#[test]
fn no_ghosting_after_grow() {
    // Simulate: small buffer → larger buffer. New areas should be rendered.
    let mut small = Buffer::new(20, 8);
    for (i, ch) in "Small content".chars().enumerate() {
        small.set_raw(i as u16, 0, Cell::from_char(ch));
    }

    // Grow to larger size (diff against blank, simulating resize)
    let mut large = Buffer::new(80, 24);
    for (i, ch) in "Large content".chars().enumerate() {
        large.set_raw(i as u16, 0, Cell::from_char(ch));
    }
    for (i, ch) in "Bottom row".chars().enumerate() {
        large.set_raw(i as u16, 23, Cell::from_char(ch));
    }

    let blank = Buffer::new(80, 24);
    let diff = BufferDiff::compute(&blank, &large);

    let output = present_to_bytes(&large, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
}

#[test]
fn property_resize_oscillation_always_flicker_free() {
    // Oscillate between two sizes, verifying each frame is flicker-free
    let sizes: [(u16, u16); 4] = [(80, 24), (40, 12), (120, 40), (20, 8)];

    for seed in 0..4u64 {
        let mut rng = Lcg::new(seed ^ 0xcafe_d00d);
        let mut all_output = Vec::new();

        for cycle in 0..6usize {
            let (width, height) = sizes[cycle % sizes.len()];

            let mut buf = Buffer::new(width, height);
            let num_changes = 5 + rng.next_range(30);
            for _ in 0..num_changes {
                let x = rng.next_range(width as usize) as u16;
                let y = rng.next_range(height as usize) as u16;
                buf.set_raw(x, y, Cell::from_char(rng.next_char()));
            }

            // Each resize presents against a blank (cleared after resize)
            let output = present_frame_synced(&buf);
            all_output.extend_from_slice(&output);
        }

        let analysis = analyze_stream_with_id(&format!("resize-osc-{seed}"), &all_output);
        assert!(
            analysis.flicker_free,
            "seed {seed}: resize oscillation not flicker-free"
        );
        assert_eq!(analysis.stats.total_frames, 6);
    }
}

// ============================================================================
// 4. Golden Checksum Tests
// ============================================================================

#[test]
fn golden_checksum_80x24_synced_frame() {
    let buf = build_test_buffer(80, 24, 42);
    let output = present_frame_synced(&buf);
    let analysis = analyze_stream_with_id("golden-80x24", &output);
    analysis.assert_flicker_free();

    // Verify deterministic output via checksum
    let checksum = compute_text_checksum(&analysis.jsonl);
    // Store the computed checksum as golden reference
    // (first run establishes baseline; subsequent runs verify stability)
    assert!(
        !checksum.is_empty(),
        "Checksum should be non-empty for golden test"
    );
}

#[test]
fn golden_checksum_120x40_synced_frame() {
    let buf = build_test_buffer(120, 40, 42);
    let output = present_frame_synced(&buf);
    let analysis = analyze_stream_with_id("golden-120x40", &output);
    analysis.assert_flicker_free();

    let checksum = compute_text_checksum(&analysis.jsonl);
    assert!(
        !checksum.is_empty(),
        "Checksum should be non-empty for golden test"
    );
}

#[test]
fn golden_jsonl_schema_stability() {
    // Verify that JSONL output has the expected schema fields
    let mut buf = Buffer::new(20, 5);
    buf.set_raw(0, 0, Cell::from_char('X'));

    let output = present_frame_synced(&buf);

    let mut detector = FlickerDetector::new("schema-test");
    detector.feed(&output);
    detector.finalize();

    let jsonl = detector.to_jsonl();

    for line in jsonl.lines() {
        // Every line should be valid JSONL with required fields
        assert!(line.starts_with('{'), "JSONL line should start with {{");
        assert!(line.ends_with('}'), "JSONL line should end with }}");
        assert!(
            line.contains("\"run_id\":\"schema-test\""),
            "Missing run_id in JSONL"
        );
        assert!(
            line.contains("\"event_type\":"),
            "Missing event_type in JSONL"
        );
        assert!(line.contains("\"severity\":"), "Missing severity in JSONL");
        assert!(line.contains("\"context\":"), "Missing context in JSONL");
        assert!(line.contains("\"details\":"), "Missing details in JSONL");
    }
}

// ============================================================================
// 5. Multi-Frame Scenarios
// ============================================================================

#[test]
fn realistic_tui_session_simulation() {
    // Simulate a realistic TUI session: startup → interaction → resize → shutdown
    let mut all_output = Vec::new();
    let width = 80u16;
    let height = 24u16;

    // Phase 1: Initial render (blank → content)
    let mut buf = Buffer::new(width, height);
    for (i, ch) in "=== FrankenTUI Demo ===".chars().enumerate() {
        buf.set_raw(i as u16, 0, Cell::from_char(ch));
    }
    for (i, ch) in "[q] Quit  [h] Help".chars().enumerate() {
        buf.set_raw(i as u16, height - 1, Cell::from_char(ch));
    }
    all_output.extend_from_slice(&present_frame_synced(&buf));

    // Phase 2: Several incremental updates (user interaction)
    let mut prev = buf;
    for frame in 0..5u32 {
        let mut next = prev.clone();
        let status = format!("Frame: {frame}  Time: {:.1}s", frame as f64 * 0.1);
        for (i, ch) in status.chars().enumerate() {
            if (i as u16) < width {
                next.set_raw(i as u16, 1, Cell::from_char(ch));
            }
        }
        all_output.extend_from_slice(&present_incremental_synced(&prev, &next));
        prev = next;
    }

    // Phase 3: Resize event (simulate terminal resize)
    let new_width = 60u16;
    let new_height = 20u16;
    let mut resized = Buffer::new(new_width, new_height);
    for (i, ch) in "=== FrankenTUI Demo ===".chars().enumerate() {
        if (i as u16) < new_width {
            resized.set_raw(i as u16, 0, Cell::from_char(ch));
        }
    }
    for (i, ch) in "[q] Quit".chars().enumerate() {
        resized.set_raw(i as u16, new_height - 1, Cell::from_char(ch));
    }
    all_output.extend_from_slice(&present_frame_synced(&resized));

    // Phase 4: More incremental updates after resize
    prev = resized;
    for frame in 5..8u32 {
        let mut next = prev.clone();
        let status = format!("Post-resize frame: {frame}");
        for (i, ch) in status.chars().enumerate() {
            if (i as u16) < new_width {
                next.set_raw(i as u16, 1, Cell::from_char(ch));
            }
        }
        all_output.extend_from_slice(&present_incremental_synced(&prev, &next));
        prev = next;
    }

    let analysis = analyze_stream(&all_output);
    analysis.assert_flicker_free();

    // Total: 1 initial + 5 interaction + 1 resize + 3 post-resize = 10 frames
    assert_eq!(analysis.stats.total_frames, 10);
    assert_eq!(analysis.stats.complete_frames, 10);
    assert!(analysis.stats.sync_coverage() > 70.0);
}

#[test]
fn rapid_content_updates_no_flicker() {
    // Simulate rapid typing: each frame adds one character
    let width = 40u16;
    let height = 5u16;
    let mut all_output = Vec::new();
    let mut prev = Buffer::new(width, height);

    let text = "The quick brown fox jumps over the lazy dog";
    for (frame_idx, ch) in text.chars().enumerate() {
        let mut next = prev.clone();
        let x = frame_idx as u16 % width;
        let y = frame_idx as u16 / width;
        if y < height {
            next.set_raw(x, y, Cell::from_char(ch));
        }
        all_output.extend_from_slice(&present_incremental_synced(&prev, &next));
        prev = next;
    }

    let analysis = analyze_stream(&all_output);
    analysis.assert_flicker_free();
    assert_eq!(analysis.stats.total_frames as usize, text.len());
}

#[test]
fn frame_with_sparse_changes_across_rows() {
    // Changes scattered across many rows (tests sparse run handling)
    let width = 80u16;
    let height = 40u16;
    let old = Buffer::new(width, height);
    let mut new = Buffer::new(width, height);

    // One change per row (maximum run fragmentation)
    for y in 0..height {
        let x = (y * 7 + 3) % width;
        new.set_raw(x, y, Cell::from_char('*'));
    }

    let diff = BufferDiff::compute(&old, &new);
    assert_eq!(diff.len(), height as usize);

    let output = present_to_bytes(&new, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
}

#[test]
fn alternating_styled_rows() {
    // Alternating row styles to stress SGR delta engine
    let width = 60u16;
    let height = 20u16;
    let old = Buffer::new(width, height);
    let mut new = Buffer::new(width, height);

    let style_a = PackedRgba::rgb(255, 100, 100);
    let style_b = PackedRgba::rgb(100, 100, 255);

    for y in 0..height {
        let fg = if y % 2 == 0 { style_a } else { style_b };
        for x in 0..width {
            let ch = if y % 2 == 0 { '=' } else { '-' };
            new.set_raw(x, y, Cell::from_char(ch).with_fg(fg));
        }
    }

    let diff = BufferDiff::compute(&old, &new);
    let output = present_to_bytes(&new, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
}

// ============================================================================
// 6. Edge Cases
// ============================================================================

#[test]
fn single_cell_buffer_synced() {
    let mut buf = Buffer::new(1, 1);
    buf.set_raw(0, 0, Cell::from_char('X'));
    let output = present_frame_synced(&buf);
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
}

#[test]
fn maximum_practical_buffer_synced() {
    // 120x40 = 4800 cells, all changed
    let width = 120u16;
    let height = 40u16;
    let old = Buffer::new(width, height);
    let mut new = Buffer::new(width, height);
    for y in 0..height {
        for x in 0..width {
            new.set_raw(x, y, Cell::from_char('.'));
        }
    }
    let diff = BufferDiff::compute(&old, &new);
    let output = present_to_bytes(&new, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
}

#[test]
fn empty_to_empty_is_flicker_free() {
    let buf = Buffer::new(80, 24);
    let diff = BufferDiff::new();
    let output = present_to_bytes(&buf, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
}

#[test]
fn no_change_frame_produces_complete_sync_brackets() {
    // Even with no changes, the sync begin/end should be emitted
    let prev = Buffer::new(20, 5);
    let next = prev.clone();
    let diff = BufferDiff::compute(&prev, &next);
    assert!(diff.is_empty());

    let output = present_to_bytes(&next, &diff, caps_with_sync());
    let analysis = analyze_stream(&output);
    analysis.assert_flicker_free();
    assert_eq!(analysis.stats.total_frames, 1);
    assert_eq!(analysis.stats.complete_frames, 1);
}

// ============================================================================
// 7. JSONL Logging Verification
// ============================================================================

#[test]
fn flicker_detector_jsonl_write_roundtrip() {
    let buf = build_test_buffer(40, 10, 99);
    let output = present_frame_synced(&buf);

    let mut detector = FlickerDetector::new("roundtrip-test");
    detector.feed(&output);
    detector.finalize();

    // Write to buffer
    let mut jsonl_buf = Vec::new();
    detector.write_jsonl(&mut jsonl_buf).unwrap();
    let jsonl = String::from_utf8(jsonl_buf).unwrap();

    // Verify each line is well-formed
    let lines: Vec<&str> = jsonl.lines().collect();
    assert!(!lines.is_empty(), "Should have at least one JSONL line");

    // Should have frame_start, frame_end, analysis_complete
    let event_types: Vec<&str> = lines
        .iter()
        .filter_map(|line| {
            let start = line.find("\"event_type\":\"")?;
            let rest = &line[start + 14..];
            let end = rest.find('"')?;
            Some(&rest[..end])
        })
        .collect();

    assert!(
        event_types.contains(&"frame_start"),
        "Missing frame_start in JSONL"
    );
    assert!(
        event_types.contains(&"frame_end"),
        "Missing frame_end in JSONL"
    );
    assert!(
        event_types.contains(&"analysis_complete"),
        "Missing analysis_complete in JSONL"
    );
}

#[test]
fn flicker_stats_sync_coverage_realistic() {
    let buf = build_test_buffer(80, 24, 42);
    let output = present_frame_synced(&buf);
    let analysis = analyze_stream(&output);

    // In a synced frame, most bytes should be within sync brackets
    assert!(
        analysis.stats.sync_coverage() > 50.0,
        "Expected >50% sync coverage, got {:.1}%",
        analysis.stats.sync_coverage()
    );
    assert!(
        analysis.stats.bytes_in_sync > 0,
        "Should have bytes inside sync"
    );
    assert!(analysis.stats.bytes_total > 0, "Should have total bytes");
}