heatsync-tui 0.2.0

heat-sorted live multichat in the terminal — twitch, kick + youtube (read-only), real emotes, vim keys
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
//! headless subcommands — the archive corpus as pipeable unix commands.
//! `heatsync log <channel> <date>` · `search <query>` · `hot`. plain stdout,
//! grep/fzf-friendly. this is the moat chatterino structurally can't match.

use std::io::{BufRead, IsTerminal, Write};
use std::time::{Duration, Instant};

use heatsync_core::Platform;

use crate::config;
use crate::hsauth;
use crate::http;
use crate::net::{self, ChatEvent};

/// split a `kick:name` / `twitch:name` / `name` token into (platform, name).
fn split_channel(tok: &str) -> (Platform, &str) {
    if let Some(rest) = tok.strip_prefix("kick:") {
        (Platform::Kick, rest)
    } else if let Some(rest) = tok.strip_prefix("twitch:") {
        (Platform::Twitch, rest)
    } else {
        (Platform::Twitch, tok)
    }
}

/// `heatsync log <channel> <YYYY-MM-DD>`
pub fn log(args: &[String]) -> std::io::Result<()> {
    let (channel, date) = match args {
        [c, d, ..] => (c.as_str(), d.as_str()),
        _ => {
            eprintln!("usage: heatsync log <channel> <YYYY-MM-DD>");
            std::process::exit(2);
        }
    };
    let (_plat, name) = split_channel(channel);
    let from = format!("{date}T00:00:00Z");
    let to = format!("{date}T23:59:59Z");
    match http::channel_log(name, &from, &to, 100) {
        Some(page) if !page.results.is_empty() => {
            for m in &page.results {
                let who = m.display_name.as_deref().unwrap_or(&m.username);
                println!("{}  {}: {}", short_ts(&m.timestamp), who, m.message);
            }
        }
        Some(_) => eprintln!("no logs for {name} on {date}"),
        None => {
            eprintln!("request failed");
            std::process::exit(1);
        }
    }
    Ok(())
}

/// `heatsync search <query> [channel]`
pub fn search(args: &[String]) -> std::io::Result<()> {
    let q = match args.first() {
        Some(q) => q.as_str(),
        None => {
            eprintln!("usage: heatsync search <query> [channel]");
            std::process::exit(2);
        }
    };
    let channel = args.get(1).map(|s| split_channel(s).1);
    match http::search(q, channel, 50) {
        Some(page) if !page.results.is_empty() => {
            for m in &page.results {
                let who = m.display_name.as_deref().unwrap_or(&m.username);
                println!(
                    "{}  [{}/{}] {}: {}",
                    short_ts(&m.timestamp),
                    m.platform,
                    m.channel,
                    who,
                    m.message
                );
            }
        }
        Some(_) => eprintln!("no matches for {q:?}"),
        None => {
            eprintln!("request failed");
            std::process::exit(1);
        }
    }
    Ok(())
}

/// `heatsync hot [hours]` — hottest posts, with real heat scores.
pub fn hot(args: &[String]) -> std::io::Result<()> {
    // Default 720h bounds the server-side scan only — the heat floor (12h
    // decay) decides what's hot, so a narrow default would just hide live heat.
    let hours: u32 = args.first().and_then(|s| s.parse().ok()).unwrap_or(720);
    match http::hot(25, hours) {
        Some(page) if !page.messages.is_empty() => {
            for m in &page.messages {
                let who = m.display_name.as_deref().unwrap_or(&m.username);
                let subj = m.subject.as_deref().unwrap_or("");
                println!(
                    "{:>6.0}  (peak {:>6.0})  {}: {} {}",
                    m.heat, m.max_heat, who, m.content, subj
                );
            }
        }
        Some(_) => eprintln!("nothing hot in the last {hours}h"),
        None => {
            eprintln!("request failed");
            std::process::exit(1);
        }
    }
    Ok(())
}

/// `heatsync-tui login [kick]` — log in with heatsync. prints a code, opens the
/// approve page, waits for the click, keeps one revocable token at 0600.
pub fn login(kick: bool) -> std::io::Result<bool> {
    let base = match hsauth::base_url() {
        Ok(b) => b,
        Err(e) => {
            eprintln!("{e}");
            std::process::exit(1);
        }
    };
    let t = hsauth::UreqTransport;
    let pair = match hsauth::pair_start(&t, &base) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{e}");
            std::process::exit(1);
        }
    };
    println!("log in to heatsync\n");
    println!("  1. open   {}", pair.url);
    println!("  2. log in there (twitch or kick) if it asks");
    println!("  3. type   {}   and press approve\n", pair.user_code);
    open_browser(&pair.url);
    println!("waiting for you… (ctrl-c to cancel)");

    let mut interval = pair.interval;
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(pair.expires_in);
    let session = loop {
        std::thread::sleep(std::time::Duration::from_secs(interval));
        if std::time::Instant::now() > deadline {
            eprintln!("that code expired — run the login again");
            std::process::exit(1);
        }
        match hsauth::poll_once(&t, &base, &pair.device_code) {
            hsauth::Poll::Pending => {}
            hsauth::Poll::SlowDown => interval = (interval + 2).min(30),
            hsauth::Poll::Approved(s) => break s,
            hsauth::Poll::Failed(e) => {
                eprintln!("{e}");
                std::process::exit(1);
            }
        }
    };
    if let Err(e) = hsauth::save_session(&session) {
        eprintln!("logged in, but could not save the login: {e}");
        std::process::exit(1);
    }
    let client = hsauth::Client::new(&session, std::sync::Arc::new(hsauth::UreqTransport));
    let tty = std::io::stdin().is_terminal() && std::io::stdout().is_terminal();
    let stdin = std::io::stdin();
    Ok(finish_login(
        &client,
        &base,
        kick,
        tty,
        &mut stdin.lock(),
        &mut open_browser,
    ))
}

/// what to show after a saved login. true = the caller should open the chat ui
/// (interactive terminals only; scripts get the printout and a clean exit).
fn finish_login(
    client: &hsauth::Client,
    base: &str,
    kick: bool,
    tty: bool,
    input: &mut dyn BufRead,
    open: &mut dyn FnMut(&str),
) -> bool {
    let me = client.me();
    if !tty {
        println!("logged in ✓\n");
    }
    match &me {
        Ok(me) => {
            if !tty {
                print_me(me, base, kick, false);
            }
            offer_scopes(&missing_scopes(me, base), tty, input, open);
            if tty && kick {
                print_kick(me, base, true);
            }
            if tty {
                println!("logged in as {} — opening chat…", account_name(me));
            }
        }
        Err(e) => {
            println!("{e}");
            if tty {
                println!("logged in — opening chat…");
            }
        }
    }
    tty
}

fn account_name(me: &serde_json::Value) -> String {
    let s = |v: &serde_json::Value| v.as_str().map(str::to_string);
    s(&me["user"]["display_name"])
        .or_else(|| s(&me["user"]["username"]))
        .unwrap_or_else(|| "?".into())
}

/// the twitch permission packs this terminal still needs: (what, link).
fn missing_scopes(me: &serde_json::Value, base: &str) -> Vec<(&'static str, String)> {
    let tw = &me["twitch"];
    let mut v = vec![];
    if tw["linked"].as_bool() != Some(true) {
        return v;
    }
    if tw["can_send"].as_bool() == Some(false) {
        v.push(("chat", format!("{base}/api/auth/login?scopes=chatsend")));
    }
    if tw["can_mod"].as_bool() == Some(false) {
        v.push(("mod", format!("{base}/api/auth/login?scopes=mod")));
    }
    v
}

/// say what twitch still needs, and (on a terminal) offer to open it. default no.
/// the server takes one permission pack per link, so two needs are two links.
fn offer_scopes(
    need: &[(&str, String)],
    tty: bool,
    input: &mut dyn BufRead,
    open: &mut dyn FnMut(&str),
) {
    if need.is_empty() {
        return;
    }
    let what: Vec<&str> = need.iter().map(|n| n.0).collect();
    println!("twitch needs one more ok for {}:", what.join(" + "));
    for (_, url) in need {
        println!("  {url}");
    }
    if !tty {
        return;
    }
    print!(
        "open {}? [y/N] ",
        if need.len() > 1 { "them" } else { "it" }
    );
    let _ = std::io::stdout().flush();
    let mut ans = String::new();
    if input.read_line(&mut ans).is_ok() && matches!(ans.trim(), "y" | "Y" | "yes") {
        for (_, url) in need {
            open(url);
        }
    }
}

/// best effort: only if a launcher exists. the url is already printed.
fn open_browser(url: &str) {
    let launcher = if cfg!(target_os = "macos") {
        "open"
    } else {
        "xdg-open"
    };
    let _ = std::process::Command::new(launcher)
        .arg(url)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn();
}

/// who is logged in and what each platform lets them do. never the token.
fn print_me(me: &serde_json::Value, base: &str, want_kick: bool, link_hints: bool) {
    let s = |v: &serde_json::Value| v.as_str().map(str::to_string);
    println!("  account   {}", account_name(me));
    let scopes: Vec<String> = me["scopes"]
        .as_array()
        .map(|a| a.iter().filter_map(s).collect())
        .unwrap_or_default();
    println!("  this login can: {}", scopes.join(", "));
    if !scopes.iter().any(|x| x == "mod") {
        println!("            no mod tools — run `heatsync-tui login` again and tick mod");
    }
    if !scopes.iter().any(|x| x == "account") {
        println!("            no whispers, dms or mention hits — run `heatsync-tui login` again and tick account");
    }
    if let Some(e) = s(&me["expires_at"]) {
        println!("  renews itself; valid until {e}");
    }
    let tw = &me["twitch"];
    if tw["linked"].as_bool() == Some(true) {
        println!("  twitch    {}", s(&tw["login"]).unwrap_or_default());
        if link_hints && tw["can_mod"].as_bool() == Some(false) {
            println!("            to mod: open {base}/api/auth/login?scopes=mod");
        }
        if link_hints && tw["can_send"].as_bool() == Some(false) {
            println!("            to chat: open {base}/api/auth/login?scopes=chatsend");
        }
    } else {
        println!("  twitch    not linked — open {base}/api/auth/login");
    }
    print_kick(me, base, want_kick);
}

fn print_kick(me: &serde_json::Value, base: &str, want_kick: bool) {
    let s = |v: &serde_json::Value| v.as_str().map(str::to_string);
    let k = &me["kick"];
    if k["linked"].as_bool() == Some(true) {
        println!("  kick      {}", s(&k["login"]).unwrap_or_default());
    } else if want_kick {
        println!("  kick      not linked yet — open {base}/api/auth/kick/login, then you can chat on kick from here");
    } else {
        println!("  kick      not linked (heatsync-tui login kick shows how)");
    }
}

/// `heatsync-tui logout` — kill the login on the server, then delete the file.
pub fn logout() -> std::io::Result<()> {
    let Some(s) = hsauth::load_session() else {
        println!("not logged in");
        return Ok(());
    };
    let client = hsauth::Client::new(&s, std::sync::Arc::new(hsauth::UreqTransport));
    let revoked = client.revoke();
    let removed = hsauth::delete_session();
    match (revoked, removed) {
        (true, true) => println!("logged out ✓"),
        (false, true) => println!(
            "logged out here. heatsync couldn't be reached, so also run: heatsync.org/cli → \"log all out\""
        ),
        (_, false) => {
            eprintln!("could not delete the saved login");
            std::process::exit(1);
        }
    }
    Ok(())
}

const ADMIN_EXPIRED: &str =
    "admin glance: admin token expired (~/.config/heatsync/token) — skip or refresh it";

/// `heatsync-tui status` — who is logged in and what they can do. if an admin
/// token is configured it also prints mellen's admin glance (mod queue, reports,
/// NCMEC backlog, capacity); no vanity concurrent-user count on purpose.
pub fn status() -> std::io::Result<()> {
    let base = hsauth::base_url().unwrap_or_else(|e| {
        eprintln!("{e}");
        std::process::exit(1);
    });
    match hsauth::load_session() {
        None => println!("not logged in — run: heatsync-tui login"),
        Some(s) => {
            let client = hsauth::Client::new(&s, std::sync::Arc::new(hsauth::UreqTransport));
            println!("logged in to {}", s.base);
            match client.me() {
                Ok(me) => print_me(&me, &base, false, true),
                Err(e) => {
                    if hsauth::is_logged_out(&e) {
                        hsauth::delete_session();
                    }
                    println!("  {e}");
                    std::process::exit(1);
                }
            }
        }
    }
    let auth = config::load_auth();
    let Some(token) = auth.admin_token else {
        return Ok(());
    };
    println!();
    let health = http::admin_health(&token);
    if health.is_none() && http::admin_token_rejected(http::BASE, &token) {
        println!("{ADMIN_EXPIRED}");
        return Ok(());
    }
    let mut ok = true;
    let mod_queue = http::admin_mod_queue_total(&token);
    let reports = http::admin_pending_reports(&token);
    let ncmec = http::admin_ncmec_backlog(&token);

    println!("heatsync — prod status");
    match &health {
        Some(h) => {
            println!(
                "  postgres: {}   redis: {}",
                h.postgres_status, h.redis_status
            );
            println!(
                "  cpu {:>5.1}%   ram {:>5.1}%   disk {:>5.1}%   errors/min {:.1}",
                h.cpu_usage, h.ram_usage, h.disk_usage, h.error_rate
            );
            println!(
                "  ws conns: {}   msgs/min: {:.0}",
                h.ws_connections, h.messages_per_minute
            );
        }
        None => {
            println!("  health: unreachable (auth expired? check ~/.config/heatsync/token)");
            ok = false;
        }
    }
    match mod_queue {
        Some(n) => println!("  mod queue:    {n:>4}  pending"),
        None => {
            println!("  mod queue:    ?     (request failed)");
            ok = false;
        }
    }
    match reports {
        Some(n) => println!("  reports:      {n:>4}  pending"),
        None => {
            println!("  reports:      ?     (request failed)");
            ok = false;
        }
    }
    match ncmec {
        Some(n) if n > 0 => println!("  ncmec:        {n:>4}  STUCK — needs a look"),
        Some(_) => println!("  ncmec:           0  clear"),
        None => {
            println!("  ncmec:        ?     (request failed)");
            ok = false;
        }
    }
    if !ok {
        std::process::exit(1);
    }
    Ok(())
}

/// `heatsync probe [channels…]` — connect to the live relay, print raw lines
/// for 8s, report the count. an end-to-end WS smoke test (and a debug tap).
pub fn probe(args: &[String]) -> std::io::Result<()> {
    let subs = if args.is_empty() {
        vec![(Platform::Twitch, "xqc".to_string())]
    } else {
        args.iter()
            .map(|a| {
                let (p, n) = split_channel(a);
                (p, n.to_string())
            })
            .collect()
    };
    eprintln!("probing {} channel(s) for 8s…", subs.len());
    let (rx, _out) = net::spawn(subs, None, false);
    let deadline = Instant::now() + Duration::from_secs(8);
    let mut n = 0u32;
    while let Some(rem) = deadline.checked_duration_since(Instant::now()) {
        match rx.recv_timeout(rem) {
            Ok(ChatEvent::Line(l)) => {
                println!(
                    "[{}/{}] {}: {}",
                    plat_tag(l.platform),
                    l.channel,
                    l.user,
                    l.content
                );
                n += 1;
            }
            Ok(ChatEvent::Connected) => eprintln!("· connected"),
            Ok(ChatEvent::Disconnected) => eprintln!("· disconnected"),
            Ok(_) => {}
            Err(_) => break,
        }
    }
    eprintln!("{n} lines in 8s");
    Ok(())
}

fn plat_tag(p: Platform) -> &'static str {
    p.tag()
}

/// trim an ISO timestamp to `HH:MM:SS` for terminal density.
fn short_ts(ts: &str) -> &str {
    ts.split('T')
        .nth(1)
        .map(|t| &t[..t.len().min(8)])
        .unwrap_or(ts)
}

/// `heatsync render-test <base-url> [overlay-url…]` — VERIFICATION harness (not a
/// user command). composites a stack via the real pipeline and dumps the result:
/// the composited RGBA frame(s) as PNG, and the actual sixel bytes the terminal
/// would receive. decode those (sixel2png) to prove rendering end-to-end without
/// needing to eyeball a live terminal. run with `env -u TMUX` for raw (unwrapped)
/// sixel.
pub fn render_test(args: &[String]) -> std::io::Result<()> {
    use ratatui_image::picker::ProtocolType;

    if args.is_empty() {
        eprintln!("usage: heatsync render-test <base-url> [overlay-url …]");
        return Ok(());
    }
    let key = args.join("\n");
    let Some(frames) = crate::emote::render::composite_frames(&key, 32) else {
        eprintln!("render-test: composite failed (fetch/decode)");
        return Ok(());
    };
    let (w, h) = (frames[0].0.width(), frames[0].0.height());
    eprintln!(
        "render-test: {} layer(s) → {} composited frame(s), {w}x{h}px",
        args.len(),
        frames.len()
    );
    if frames.len() > 1 {
        let total: u32 = frames.iter().map(|f| f.1.max(20)).sum();
        let fps = frames.len() as f64 * 1000.0 / total.max(1) as f64;
        eprintln!(
            "  authored: {:.0}ms loop at {fps:.1}fps (a 100ms redraw cadence would \
             show {:.0} of these {} frames)",
            total,
            (total as f64 / 100.0).floor(),
            frames.len()
        );
    }
    let idxs = if frames.len() > 1 {
        vec![0usize, frames.len() / 2]
    } else {
        vec![0usize]
    };
    for i in &idxs {
        let p = format!("/tmp/emote_composite_{i}.png");
        if frames[*i].0.save(&p).is_ok() {
            eprintln!("  composite frame {i} → {p}");
        }
    }
    // run the REAL sizing + palette + encode path for an 8x16 cell terminal and
    // report the two things that were broken: the cell footprint, and how much
    // the sixel payload churns between consecutive frames. that churn IS the
    // flashing — a shared palette should leave only real motion changing.
    let (cw, ch) = (8u16, 16u16);
    let mut picker = ratatui_image::picker::Picker::from_fontsize((cw, ch));
    picker.set_protocol_type(ProtocolType::Sixel);
    let block_h = crate::emote::render::EMOTE_H as u32 * ch as u32;
    let w_cells = crate::emote::render::width_cells(w as f32 / h as f32, cw, ch);
    eprintln!(
        "  footprint on an {cw}x{ch} cell: {w_cells}x{} cells = {}x{block_h}px (source {w}x{h})",
        crate::emote::render::EMOTE_H,
        w_cells as u32 * cw as u32,
    );

    let take = frames.len().min(24);
    let mut canvases: Vec<image::RgbaImage> = frames[..take]
        .iter()
        .map(|(f, _)| crate::emote::render::fit_center(f, w_cells as u32 * cw as u32, block_h))
        .collect();
    for c in &mut canvases {
        crate::emote::render::flatten_onto_black(c);
    }
    let raw = encode_all(&picker, &canvases, w_cells);
    crate::emote::render::stabilize_palette(&mut canvases);
    let stable = encode_all(&picker, &canvases, w_cells);

    if let Some(first) = stable.first() {
        std::fs::write("/tmp/emote.six", first)?;
        let wrapped = first.contains("tmux;");
        eprintln!(
            "  sixel bytes → /tmp/emote.six ({} bytes){}",
            first.len(),
            if wrapped {
                " [tmux-wrapped — rerun with `env -u TMUX`]"
            } else {
                ""
            }
        );
    }
    if take > 1 {
        let px = (w_cells as u32 * cw as u32, block_h);
        eprintln!("  pixels changing between consecutive frames (lower = less shimmer):");
        eprintln!(
            "    per-frame palette (before): {:.1}%",
            pixel_churn(&raw, px) * 100.0
        );
        eprintln!(
            "    shared palette   (after):  {:.1}%",
            pixel_churn(&stable, px) * 100.0
        );
        eprintln!(
            "    source frames actually differ by: {:.1}% (the real motion)",
            source_churn(&canvases_src(
                &frames[..take],
                w_cells as u32 * cw as u32,
                block_h
            )) * 100.0
        );
    }
    Ok(())
}

fn canvases_src(frames: &[(image::RgbaImage, u32)], tw: u32, th: u32) -> Vec<image::RgbaImage> {
    frames
        .iter()
        .map(|(f, _)| {
            let mut c = crate::emote::render::fit_center(f, tw, th);
            crate::emote::render::flatten_onto_black(&mut c);
            c
        })
        .collect()
}

/// mean fraction of pixels differing between consecutive source frames — the
/// floor. anything a decoded sixel churns ABOVE this is encoder shimmer.
fn source_churn(frames: &[image::RgbaImage]) -> f64 {
    if frames.len() < 2 {
        return 0.0;
    }
    let mut total = 0.0;
    for w in frames.windows(2) {
        let n = w[0].pixels().len().max(1);
        let diff = w[0]
            .pixels()
            .zip(w[1].pixels())
            .filter(|(a, b)| a != b)
            .count();
        total += diff as f64 / n as f64;
    }
    total / (frames.len() - 1) as f64
}

/// decode each sixel back to pixels and report the mean fraction that changes
/// between consecutive frames. this is what the eye sees flicker.
fn pixel_churn(frames: &[String], (w, h): (u32, u32)) -> f64 {
    let decoded: Vec<Vec<u32>> = frames.iter().map(|s| sixel_decode(s, w, h)).collect();
    if decoded.len() < 2 {
        return 0.0;
    }
    let mut total = 0.0;
    for pair in decoded.windows(2) {
        let n = (w * h) as usize;
        let diff = pair[0].iter().zip(&pair[1]).filter(|(a, b)| a != b).count();
        total += diff as f64 / n.max(1) as f64;
    }
    total / (decoded.len() - 1) as f64
}

/// minimal sixel reader — enough of the grammar to rebuild the pixel grid an
/// emote encodes to (palette defs, color select, 6-pixel data bytes, RLE, `$`
/// carriage return, `-` newline). verification-only.
fn sixel_decode(data: &str, w: u32, h: u32) -> Vec<u32> {
    let mut out = vec![0u32; (w * h) as usize];
    let mut palette = std::collections::HashMap::new();
    let b: Vec<char> = data.chars().collect();
    let mut i = 0usize;
    // skip to the start of sixel data (after the `q` of the DCS header)
    while i < b.len() && b[i] != 'q' {
        i += 1;
    }
    i += 1;
    let (mut x, mut band, mut color) = (0u32, 0u32, 0u32);
    let num = |b: &[char], i: &mut usize| -> u32 {
        let mut n = 0u32;
        while *i < b.len() && b[*i].is_ascii_digit() {
            n = n
                .saturating_mul(10)
                .saturating_add(b[*i] as u32 - '0' as u32);
            *i += 1;
        }
        n
    };
    while i < b.len() {
        match b[i] {
            '#' => {
                i += 1;
                let idx = num(&b, &mut i);
                if i < b.len() && b[i] == ';' {
                    i += 1;
                    let _mode = num(&b, &mut i);
                    let mut c = [0u32; 3];
                    for slot in c.iter_mut() {
                        if i < b.len() && b[i] == ';' {
                            i += 1;
                        }
                        *slot = num(&b, &mut i);
                    }
                    palette.insert(idx, (c[0] << 16) | (c[1] << 8) | c[2] | 1 << 24);
                }
                color = idx;
            }
            '!' => {
                i += 1;
                let n = num(&b, &mut i);
                if i < b.len() {
                    let ch = b[i];
                    i += 1;
                    for _ in 0..n {
                        put(
                            &mut out,
                            w,
                            h,
                            x,
                            band,
                            ch,
                            *palette.get(&color).unwrap_or(&0),
                        );
                        x += 1;
                    }
                }
            }
            '$' => {
                x = 0;
                i += 1;
            }
            '-' => {
                x = 0;
                band += 1;
                i += 1;
            }
            '"' => {
                i += 1;
                while i < b.len() && (b[i].is_ascii_digit() || b[i] == ';') {
                    i += 1;
                }
            }
            c if ('?'..='~').contains(&c) => {
                put(
                    &mut out,
                    w,
                    h,
                    x,
                    band,
                    c,
                    *palette.get(&color).unwrap_or(&0),
                );
                x += 1;
                i += 1;
            }
            _ => i += 1,
        }
    }
    out
}

fn put(out: &mut [u32], w: u32, h: u32, x: u32, band: u32, ch: char, rgb: u32) {
    if x >= w {
        return;
    }
    let bits = (ch as u32).wrapping_sub('?' as u32);
    for bit in 0..6u32 {
        if bits & (1 << bit) != 0 {
            let y = band * 6 + bit;
            if y < h {
                out[(y * w + x) as usize] = rgb;
            }
        }
    }
}

fn encode_all(
    picker: &ratatui_image::picker::Picker,
    canvases: &[image::RgbaImage],
    w_cells: u16,
) -> Vec<String> {
    let size = ratatui::layout::Rect::new(0, 0, w_cells, crate::emote::render::EMOTE_H);
    canvases
        .iter()
        .filter_map(|c| {
            match picker.new_protocol(
                image::DynamicImage::ImageRgba8(c.clone()),
                size,
                ratatui_image::Resize::Fit(None),
            ) {
                Ok(ratatui_image::protocol::Protocol::Sixel(s)) => Some(s.data),
                _ => None,
            }
        })
        .collect()
}

/// `heatsync diag` — console/graphics diagnostic. no network, no TUI. prints
/// every input the emote-tier decision depends on, says which tier it would
/// pick and WHY the others were rejected, then (on a usable console) paints a
/// test rectangle straight to /dev/fb0 so scanout can be confirmed by eye.
pub fn diag(_args: &[String]) -> std::io::Result<()> {
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| "<unset>".into());
    println!(
        "TERM={}  TMUX={}  WAYLAND_DISPLAY={}  DISPLAY={}",
        env("TERM"),
        if std::env::var_os("TMUX").is_some() {
            "set"
        } else {
            "<unset>"
        },
        env("WAYLAND_DISPLAY"),
        env("DISPLAY")
    );

    let (cols, rows) = match crossterm::terminal::size() {
        Ok((c, r)) => {
            println!("crossterm size = {c}x{r} cells");
            (c, r)
        }
        Err(e) => {
            println!("crossterm size = ERR {e}");
            (0, 0)
        }
    };

    // glyph coverage: the kernel console font is 256/512 glyphs, so any of these
    // that show as blank/garbage explain missing UI chrome.
    println!("glyphs (blank = font can't map it): '\u{276f}' '\u{2588}' '\u{25cf}' '\u{25cb}' '\u{2500}' '\u{2502}' '\u{250c}'");

    println!("--- tier decision ---");
    let mut reasons: Vec<String> = Vec::new();
    if std::env::var_os("TMUX").is_some() {
        let client = std::process::Command::new("tmux")
            .args(["display", "-p", "#{client_termname}"])
            .output()
            .ok()
            .filter(|o| o.status.success())
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .unwrap_or_default();
        println!("tmux client_termname = {client:?}");
        if client != "linux" {
            reasons.push(format!("tmux client is {client:?}, not a kernel console"));
        }
    } else {
        if std::env::var("TERM").ok().as_deref() != Some("linux") {
            reasons.push("TERM != linux and not in tmux".into());
        }
        if std::env::var_os("WAYLAND_DISPLAY").is_some() {
            reasons.push("WAYLAND_DISPLAY set (fb0 is not the scanned-out surface)".into());
        }
        if std::env::var_os("DISPLAY").is_some() {
            reasons.push("DISPLAY set (fb0 is not the scanned-out surface)".into());
        }
    }
    if cols == 0 || rows == 0 {
        reasons.push("terminal size reported 0 — fb tier needs a real cell grid".into());
    }

    #[cfg(target_os = "linux")]
    {
        match framebuffer::Framebuffer::new("/dev/fb0") {
            Err(e) => reasons.push(format!("/dev/fb0 open failed: {e:?}")),
            Ok(fb) => {
                let v = fb.var_screen_info.clone();
                let f = fb.fix_screen_info.clone();
                println!(
                    "fb0: {}x{} bpp={} line_length={} smem_len={} xoff={} yoff={}",
                    v.xres,
                    v.yres,
                    v.bits_per_pixel,
                    f.line_length,
                    f.smem_len,
                    v.xoffset,
                    v.yoffset
                );
                println!(
                    "fb0 bitfields: r=({},{}) g=({},{}) b=({},{})",
                    v.red.offset,
                    v.red.length,
                    v.green.offset,
                    v.green.length,
                    v.blue.offset,
                    v.blue.length
                );
                println!("fb0 mmap len = {} bytes", fb.frame.len());
                if cols > 0 && rows > 0 {
                    println!(
                        "cell = {}x{} px",
                        (v.xres / cols as u32).max(1),
                        (v.yres / rows as u32).max(1)
                    );
                }
                if reasons.is_empty() {
                    paint_test(
                        fb,
                        v.xres,
                        v.yres,
                        f.line_length,
                        (v.bits_per_pixel / 8).max(1),
                    );
                }
            }
        }
    }

    if reasons.is_empty() {
        println!("=> framebuffer tier ACTIVE");
    } else {
        println!("=> framebuffer tier REJECTED:");
        for r in &reasons {
            println!("   - {r}");
        }
        println!("   (falls back to the terminal-graphics tier, else text)");
    }
    Ok(())
}

/// paint an orange 200x100 block at (100,100) straight to the framebuffer and
/// hold it, so "did anything reach the screen" is answered by looking.
#[cfg(target_os = "linux")]
fn paint_test(mut fb: framebuffer::Framebuffer, xres: u32, yres: u32, line_len: u32, bpp: u32) {
    let (w, h) = (200u32.min(xres), 100u32.min(yres));
    let buf = &mut fb.frame;
    for y in 100..(100 + h) {
        for x in 100..(100 + w) {
            let off = (y as usize) * line_len as usize + (x as usize) * bpp as usize;
            if off + bpp as usize > buf.len() {
                continue;
            }
            // heatsync orange #ff8700, written little-endian for xrgb8888.
            for (i, b) in [0x00u8, 0x87, 0xff, 0x00]
                .iter()
                .take(bpp as usize)
                .enumerate()
            {
                buf[off + i] = *b;
            }
        }
    }
    println!("painted an ORANGE block at px(100,100) size 200x100 — holding 5s");
    std::thread::sleep(std::time::Duration::from_secs(5));
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{json, Value};
    use std::io::Read;
    use std::sync::{Arc, Mutex};

    struct Fake(Mutex<Vec<Result<(u16, Value), String>>>);
    impl hsauth::Transport for Fake {
        fn call(
            &self,
            _: &str,
            _: &str,
            _: Option<&str>,
            _: Option<&Value>,
        ) -> Result<(u16, Value), String> {
            self.0.lock().unwrap().remove(0)
        }
    }

    fn client(me: Value) -> hsauth::Client {
        let s = hsauth::Session::new("hscli_X".into(), "https://h.test".into(), String::new());
        hsauth::Client::new(&s, Arc::new(Fake(Mutex::new(vec![Ok((200, me))]))))
    }

    fn me(can_send: bool, can_mod: bool) -> Value {
        json!({"user": {"display_name": "Mellen"}, "scopes": ["chat"],
               "twitch": {"linked": true, "login": "m", "can_send": can_send, "can_mod": can_mod},
               "kick": {"linked": false}})
    }

    fn run(me_v: Value, tty: bool, answer: &str) -> (bool, Vec<String>) {
        let mut opened = vec![];
        let go = finish_login(
            &client(me_v),
            "https://h.test",
            false,
            tty,
            &mut answer.as_bytes(),
            &mut |u| opened.push(u.to_string()),
        );
        (go, opened)
    }

    #[test]
    fn tty_goes_to_chat_scripts_exit() {
        assert!(run(me(true, true), true, "").0);
        assert!(!run(me(true, true), false, "").0);
    }

    #[test]
    fn scope_prompt_defaults_to_no_and_opens_both_on_yes() {
        let (_, o) = run(me(false, false), true, "\n");
        assert!(o.is_empty());
        let (_, o) = run(me(false, false), true, "y\n");
        assert_eq!(
            o,
            [
                "https://h.test/api/auth/login?scopes=chatsend",
                "https://h.test/api/auth/login?scopes=mod"
            ]
        );
    }

    #[test]
    fn no_prompt_without_a_tty_and_nothing_when_complete() {
        // a script never blocks on stdin, even if "y" is sitting there
        assert!(run(me(false, false), false, "y\n").1.is_empty());
        assert!(missing_scopes(&me(true, true), "b").is_empty());
        assert_eq!(missing_scopes(&me(true, false), "b").len(), 1);
    }

    /// one canned reply per connection, then gone.
    fn serve(status: &'static str) -> String {
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = l.local_addr().unwrap();
        std::thread::spawn(move || {
            if let Ok((mut c, _)) = l.accept() {
                let mut b = [0u8; 1024];
                let _ = c.read(&mut b);
                let _ = write!(
                    c,
                    "HTTP/1.1 {status}\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{{}}"
                );
            }
        });
        format!("http://{addr}")
    }

    #[test]
    fn only_a_clear_no_means_the_admin_token_expired() {
        assert!(http::admin_token_rejected(&serve("401 Unauthorized"), "t"));
        assert!(!http::admin_token_rejected(&serve("500 Oops"), "t"));
        assert!(!http::admin_token_rejected(&serve("200 OK"), "t"));
        assert!(!http::admin_token_rejected("http://127.0.0.1:1", "t"));
    }
}