shunt-proxy 0.1.90

A local proxy that pools multiple Claude accounts behind a single endpoint, routing requests to maximise rate limits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
/// Live fullscreen TUI monitor for shunt.
///
/// Connects to the running proxy's /status endpoint and refreshes every second.
/// Press 'q' or Esc to exit, 'u' to pick an account to pin, '?' for help.
use anyhow::Result;
use crossterm::{
    event::{self, Event, KeyCode, KeyModifiers},
    execute,
    terminal,
};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    symbols,
    text::{Line, Span},
    widgets::{Axis, Block, Borders, Cell, Chart, Clear, Dataset, GraphType, Paragraph, Row, Table},
    Frame, Terminal,
};
use serde::Deserialize;
use std::{
    io::stdout,
    time::{Duration, Instant},
};

use crate::term::fmt_duration_ms;

// ---------------------------------------------------------------------------
// Status API response types (mirrors proxy.rs /status handler)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize, Default)]
struct StatusResponse {
    #[serde(default)]
    started_ms: Option<u64>,
    #[serde(default)]
    accounts: Vec<AccountStatus>,
    #[serde(default)]
    pinned_account: Option<String>,
    #[serde(default)]
    last_used_account: Option<String>,
    #[serde(default)]
    recent_requests: Vec<ReqLog>,
    #[serde(default)]
    savings: Option<SavingsInfo>,
}

#[derive(Debug, Deserialize, Default, Clone)]
struct SavingsInfo {
    #[serde(default)]
    today_input: u64,
    #[serde(default)]
    today_output: u64,
    #[serde(default)]
    today_cost_usd: f64,
    #[serde(default)]
    week_cost_usd: f64,
    #[serde(default)]
    all_time_cost_usd: f64,
}

#[derive(Debug, Deserialize)]
struct AccountStatus {
    name: String,
    #[serde(default)]
    email: Option<String>,
    #[serde(default)]
    provider: String,
    available: bool,
    #[serde(default)]
    disabled: bool,
    #[serde(default)]
    auth_failed: bool,
    #[serde(default)]
    utilization_5h: f64,
    #[serde(default)]
    reset_5h: Option<u64>,
    #[serde(default)]
    utilization_7d: f64,
    #[serde(default)]
    reset_7d: Option<u64>,
    #[serde(default)]
    cooldown_until_ms: u64,
}

#[derive(Debug, Deserialize, Clone)]
struct ReqLog {
    ts_ms: u64,
    account: String,
    model: String,
    #[allow(dead_code)]
    status: u16,
    input_tokens: u64,
    output_tokens: u64,
    duration_ms: u64,
}

// ---------------------------------------------------------------------------
// Colours
// ---------------------------------------------------------------------------

const GREEN:    Color = Color::Indexed(154); // #afd700 bright lime-green
const DK_GREEN: Color = Color::Indexed(28);  // #008700 dark green
const BRAND:    Color = Color::Indexed(154); // #afd700 bright lime-green
const DIM:      Color = Color::Indexed(240); // #585858 gray
const YELLOW:   Color = Color::Indexed(220); // #ffd700 yellow
const RED:      Color = Color::Indexed(196); // #ff0000 red
const WHITE:    Color = Color::Indexed(253); // #dadada light gray
const CYAN:     Color = Color::Indexed(154); // #afd700 use green to stay on-theme

/// Per-account chart colours — distinct enough to tell apart at a glance.
const ACCOUNT_COLORS: &[Color] = &[
    Color::Indexed(154), // lime green  (brand)
    Color::Indexed(220), // bright yellow
    Color::Indexed(39),  // dodger blue
    Color::Indexed(213), // hot pink
    Color::Indexed(51),  // aqua
    Color::Indexed(208), // orange
    Color::Indexed(141), // medium purple
    Color::Indexed(85),  // sea green
];

fn style_brand()   -> Style { Style::default().fg(BRAND).add_modifier(Modifier::BOLD) }
fn style_green()   -> Style { Style::default().fg(GREEN) }
fn style_dkgreen() -> Style { Style::default().fg(DK_GREEN) }
fn style_dim()     -> Style { Style::default().fg(DIM) }
fn style_yellow()  -> Style { Style::default().fg(YELLOW) }
fn style_red()     -> Style { Style::default().fg(RED) }
fn style_white()   -> Style { Style::default().fg(WHITE) }
fn style_cyan()    -> Style { Style::default().fg(CYAN) }
#[allow(dead_code)]
fn style_bold()    -> Style { Style::default().add_modifier(Modifier::BOLD) }

// ---------------------------------------------------------------------------
// Interactive chart state
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq)]
enum TimeWindow {
    OneMin,
    FiveMin,
    FifteenMin,
    SixtyMin,
}

impl TimeWindow {
    fn ms(self) -> u64 {
        match self {
            Self::OneMin      => 60_000,
            Self::FiveMin     => 300_000,
            Self::FifteenMin  => 900_000,
            Self::SixtyMin    => 3_600_000,
        }
    }

    fn label(self) -> &'static str {
        match self {
            Self::OneMin      => "1m",
            Self::FiveMin     => "5m",
            Self::FifteenMin  => "15m",
            Self::SixtyMin    => "1h",
        }
    }

    fn next(self) -> Self {
        match self {
            Self::OneMin      => Self::FiveMin,
            Self::FiveMin     => Self::FifteenMin,
            Self::FifteenMin  => Self::SixtyMin,
            Self::SixtyMin    => Self::OneMin,
        }
    }

    fn prev(self) -> Self {
        match self {
            Self::OneMin      => Self::SixtyMin,
            Self::FiveMin     => Self::OneMin,
            Self::FifteenMin  => Self::FiveMin,
            Self::SixtyMin    => Self::FifteenMin,
        }
    }

    /// Number of equal-width buckets to divide the window into.
    fn bucket_count(self) -> usize { 60 }

    /// Width of each bucket in milliseconds.
    fn bucket_ms(self) -> u64 { self.ms() / self.bucket_count() as u64 }
}


// ---------------------------------------------------------------------------
// Error classification
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
enum FetchError {
    /// TCP connection refused — proxy is not running.
    NotRunning,
    /// Got a response but something else went wrong.
    Other(String),
}


// ---------------------------------------------------------------------------
// Picker overlay state
// ---------------------------------------------------------------------------

struct Picker {
    items: Vec<String>, // account names + "auto"
    cursor: usize,
}

impl Picker {
    fn new(accounts: &[AccountStatus], pinned: Option<&str>) -> Self {
        let mut items: Vec<String> = accounts.iter().map(|a| a.name.clone()).collect();
        items.push("auto".to_owned());
        let cursor = pinned
            .and_then(|p| items.iter().position(|i| i == p))
            .unwrap_or(items.len() - 1);
        Self { items, cursor }
    }
    fn up(&mut self) {
        self.cursor = if self.cursor == 0 { self.items.len() - 1 } else { self.cursor - 1 };
    }
    fn down(&mut self) {
        self.cursor = (self.cursor + 1) % self.items.len();
    }
    fn selected(&self) -> &str { &self.items[self.cursor] }
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

pub async fn run_monitor(base_url: &str) -> Result<()> {
    let status_url = format!("{}/status", base_url.trim_end_matches('/'));
    let use_url    = format!("{}/use",    base_url.trim_end_matches('/'));

    // Install a panic hook that restores the terminal before printing the panic message,
    // so the terminal isn't left in raw/alternate-screen mode on crash.
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let _ = terminal::disable_raw_mode();
        let _ = crossterm::execute!(
            std::io::stdout(),
            terminal::LeaveAlternateScreen,
            crossterm::cursor::Show
        );
        original_hook(info);
    }));

    // Setup terminal
    terminal::enable_raw_mode()?;
    let mut out = stdout();
    execute!(out, terminal::EnterAlternateScreen, crossterm::cursor::Hide)?;
    let backend = CrosstermBackend::new(out);
    let mut terminal = Terminal::new(backend)?;

    let mut state: Option<StatusResponse> = None;
    let mut fetch_err: Option<FetchError> = None;
    let mut last_fetch = Instant::now() - Duration::from_secs(10);
    let mut scroll: usize = 0;
    let mut picker: Option<Picker> = None;
    let mut show_help = false;
    let mut refresh_ms: u64 = 1_000;
    // Interactive chart state
    let mut chart_window = TimeWindow::FiveMin;
    // Spinner frame counter for "not running" state
    let start_time = Instant::now();

    loop {
        // Fetch status at the configured interval
        if last_fetch.elapsed() >= Duration::from_millis(refresh_ms) {
            match fetch_status(&status_url).await {
                Ok(s)  => { state = Some(s); fetch_err = None; }
                Err(e) => { fetch_err = Some(e); state = None; }
            }
            last_fetch = Instant::now();
        }

        terminal.draw(|f| {
            draw(f, &state, &fetch_err, scroll, base_url, &picker, show_help,
                 refresh_ms, start_time, chart_window)
        })?;

        // Poll for key events (non-blocking, 200ms timeout)
        if event::poll(Duration::from_millis(200))? {
            if let Event::Key(key) = event::read()? {
                // Help overlay intercepts all keys
                if show_help {
                    show_help = false;
                    continue;
                }

                // Picker overlay active — intercept keys
                if let Some(ref mut p) = picker {
                    match key.code {
                        KeyCode::Esc | KeyCode::Char('q') => { picker = None; }
                        KeyCode::Up   | KeyCode::Char('k') => p.up(),
                        KeyCode::Down | KeyCode::Char('j') => p.down(),
                        KeyCode::Enter => {
                            let chosen = p.selected().to_owned();
                            picker = None;
                            // POST /use — best-effort, ignore errors
                            let _ = reqwest::Client::new()
                                .post(&use_url)
                                .json(&serde_json::json!({ "account": chosen }))
                                .timeout(Duration::from_secs(3))
                                .send()
                                .await;
                            // Force immediate refresh
                            last_fetch = Instant::now() - Duration::from_secs(10);
                        }
                        _ => {}
                    }
                    continue;
                }

                // Normal keys
                match (key.code, key.modifiers) {
                    (KeyCode::Char('q'), _)
                    | (KeyCode::Esc, _)
                    | (KeyCode::Char('c'), KeyModifiers::CONTROL) => break,
                    (KeyCode::Down, _) | (KeyCode::Char('j'), _) => {
                        scroll = scroll.saturating_add(1);
                    }
                    (KeyCode::Up, _) | (KeyCode::Char('k'), _) => {
                        scroll = scroll.saturating_sub(1);
                    }
                    (KeyCode::Char('r'), _) => {
                        last_fetch = Instant::now() - Duration::from_secs(10);
                    }
                    (KeyCode::Char('u'), _) => {
                        if let Some(ref s) = state {
                            picker = Some(Picker::new(&s.accounts, s.pinned_account.as_deref()));
                        }
                    }
                    (KeyCode::Char('?'), _) => {
                        show_help = true;
                    }
                    // +/= increase refresh rate (halve interval, min 200ms)
                    (KeyCode::Char('+'), _) | (KeyCode::Char('='), _) => {
                        refresh_ms = (refresh_ms / 2).max(200);
                    }
                    // - decrease refresh rate (double interval, max 10s)
                    (KeyCode::Char('-'), _) => {
                        refresh_ms = (refresh_ms * 2).min(10_000);
                    }
                    // t / ] — cycle time window forward
                    (KeyCode::Char('t'), _) | (KeyCode::Char(']'), _) => {
                        chart_window = chart_window.next();
                    }
                    // [ — cycle time window backward
                    (KeyCode::Char('['), _) => {
                        chart_window = chart_window.prev();
                    }
                    _ => {}
                }
            }
        }
    }

    // Restore terminal
    execute!(terminal.backend_mut(), terminal::LeaveAlternateScreen, crossterm::cursor::Show)?;
    terminal::disable_raw_mode()?;
    Ok(())
}

async fn fetch_status(url: &str) -> Result<StatusResponse, FetchError> {
    let resp = reqwest::Client::new()
        .get(url)
        .timeout(Duration::from_secs(3))
        .send()
        .await
        .map_err(|e| {
            if e.is_connect() || e.is_timeout() {
                FetchError::NotRunning
            } else {
                FetchError::Other(e.to_string())
            }
        })?
        .error_for_status()
        .map_err(|e| FetchError::Other(e.to_string()))?;

    resp.json::<StatusResponse>()
        .await
        .map_err(|e| FetchError::Other(format!("bad response: {e}")))
}

// ---------------------------------------------------------------------------
// Drawing
// ---------------------------------------------------------------------------

const SPINNER: &[&str] = &["", "", "", "", "", "", "", "", "", ""];

#[allow(clippy::too_many_arguments)]
fn draw(
    f: &mut Frame,
    state: &Option<StatusResponse>,
    error: &Option<FetchError>,
    scroll: usize,
    base_url: &str,
    picker: &Option<Picker>,
    show_help: bool,
    refresh_ms: u64,
    start_time: Instant,
    chart_window: TimeWindow,
) {
    let area = f.area();

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),
            Constraint::Min(0),
            Constraint::Length(1),
        ])
        .split(area);

    draw_header(f, chunks[0], state);

    match state {
        None => draw_connecting(f, chunks[1], error, base_url, start_time),
        Some(s) => draw_body(f, chunks[1], s, scroll, chart_window),
    }

    draw_footer(f, chunks[2], picker.is_some(), refresh_ms);

    if let Some(p) = picker {
        draw_picker(f, p, area);
    }

    if show_help {
        draw_help_overlay(f, area);
    }
}

fn draw_header(f: &mut Frame, area: Rect, state: &Option<StatusResponse>) {
    let uptime_span = state
        .as_ref()
        .and_then(|s| s.started_ms)
        .map(|ms| {
            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64;
            let elapsed = now_ms.saturating_sub(ms);
            format!("  up {}", fmt_duration_ms(elapsed))
        });

    let savings_span: Option<String> = state.as_ref().and_then(|s| {
        let sv = s.savings.as_ref()?;
        let today_tok = sv.today_input + sv.today_output;
        if today_tok == 0 && sv.all_time_cost_usd == 0.0 { return None; }
        let tok_str   = crate::term::fmt_tokens(today_tok);
        let cost_str  = crate::pricing::fmt_cost(sv.today_cost_usd);
        let week_str  = crate::pricing::fmt_cost(sv.week_cost_usd);
        Some(format!("  ·  today: {tok_str}  {cost_str}  ·  week: {week_str}"))
    });

    let mut spans = vec![
        Span::styled("", style_brand()),
        Span::styled("shunt", style_brand()),
        Span::styled("  monitor", style_dim()),
        Span::styled("  ·  live", Style::default().fg(GREEN)),
    ];
    if let Some(ref u) = uptime_span {
        spans.push(Span::styled(u.as_str(), style_dim()));
    }
    if let Some(ref sv) = savings_span {
        spans.push(Span::styled(sv.as_str(), style_dim()));
    }

    let title = Line::from(spans);
    let block = Block::default()
        .borders(Borders::BOTTOM)
        .border_style(style_dkgreen());
    let p = Paragraph::new(title).block(block).alignment(Alignment::Left);
    f.render_widget(p, area);
}

fn sep() -> Span<'static> { Span::styled("  ·  ", Style::default().fg(DIM)) }

fn draw_footer(f: &mut Frame, area: Rect, picker_open: bool, refresh_ms: u64) {
    let hint = if picker_open {
        Line::from(vec![
            Span::styled(" ↑↓ navigate", style_dim()),
            sep(),
            Span::styled("enter", style_green()),
            Span::styled(" pin", style_dim()),
            sep(),
            Span::styled("esc", style_green()),
            Span::styled(" cancel", style_dim()),
        ])
    } else {
        let rate_str = if refresh_ms < 1_000 {
            format!("{}ms", refresh_ms)
        } else {
            format!("{}s", refresh_ms / 1_000)
        };
        Line::from(vec![
            Span::styled(" q", style_green()),
            Span::styled(" quit", style_dim()),
            sep(),
            Span::styled("r", style_green()),
            Span::styled(" refresh", style_dim()),
            sep(),
            Span::styled("u", style_green()),
            Span::styled(" pin", style_dim()),
            sep(),
            Span::styled("t", style_green()),
            Span::styled(" time", style_dim()),
            sep(),
            Span::styled("+/-", style_green()),
            Span::styled(format!(" speed  {rate_str}"), style_dim()),
            sep(),
            Span::styled("?", style_green()),
            Span::styled(" help", style_dim()),
        ])
    };
    f.render_widget(Paragraph::new(hint), area);
}

fn is_remote_url(base_url: &str) -> bool {
    !base_url.contains("127.0.0.1") && !base_url.contains("localhost")
}

fn draw_connecting(
    f: &mut Frame,
    area: Rect,
    error: &Option<FetchError>,
    base_url: &str,
    start_time: Instant,
) {
    let remote = is_remote_url(base_url);

    let lines: Vec<Line> = match error {
        Some(FetchError::NotRunning) if remote => vec![
            Line::from(vec![
                Span::styled("", style_red()),
                Span::styled("Lost connection to host", style_white()),
            ]),
            Line::from(vec![
                Span::styled(format!("  {base_url}"), style_dim()),
            ]),
            Line::from(vec![]),
            Line::from(vec![
                Span::styled("  Is the host still running shunt?", style_dim()),
            ]),
            Line::from(vec![
                Span::styled("  Run ", style_dim()),
                Span::styled("shunt connect <new-code>", style_cyan()),
                Span::styled(" to reconnect.", style_dim()),
            ]),
        ],
        Some(FetchError::NotRunning) => {
            let frame = (start_time.elapsed().as_millis() / 120) as usize % SPINNER.len();
            vec![Line::from(vec![
                Span::styled(SPINNER[frame], style_dim()),
                Span::styled("  waiting for proxy  ·  run shunt start", style_dim()),
            ])]
        }
        Some(FetchError::Other(msg)) => vec![Line::from(vec![
            Span::styled("", style_red()),
            Span::styled(format!("cannot reach {base_url}  ·  {msg}"), style_dim()),
        ])],
        None => vec![Line::from(Span::styled("connecting…", style_dim()))],
    };

    let p = Paragraph::new(lines)
        .alignment(Alignment::Center)
        .block(Block::default());
    f.render_widget(p, area);
}

fn draw_body(
    f: &mut Frame,
    area: Rect,
    s: &StatusResponse,
    scroll: usize,
    chart_window: TimeWindow,
) {
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(45), Constraint::Percentage(55)])
        .split(area);

    draw_accounts(f, chunks[0], s);
    draw_right_panel(f, chunks[1], s, scroll, chart_window);
}

// ---------------------------------------------------------------------------
// Right panel: request log (top) + history chart (bottom)
// ---------------------------------------------------------------------------

fn draw_right_panel(
    f: &mut Frame,
    area: Rect,
    s: &StatusResponse,
    scroll: usize,
    chart_window: TimeWindow,
) {
    let halves = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Percentage(48), Constraint::Percentage(52)])
        .split(area);

    draw_request_log(f, halves[0], s, scroll);
    draw_history_chart(f, halves[1], s, chart_window);
}

fn draw_accounts(f: &mut Frame, area: Rect, s: &StatusResponse) {
    let block = Block::default()
        .title(Line::from(vec![
            Span::styled(" accounts", style_dim()),
        ]))
        .borders(Borders::RIGHT)
        .border_style(style_dkgreen());

    let inner = block.inner(area);
    f.render_widget(block, area);

    if s.accounts.is_empty() {
        let p = Paragraph::new(Line::from(Span::styled("  no accounts configured", style_dim())));
        f.render_widget(p, inner);
        return;
    }

    let pinned = s.pinned_account.as_deref().unwrap_or("");
    let last   = s.last_used_account.as_deref().unwrap_or("");

    let mut lines: Vec<Line> = Vec::new();

    for acc in &s.accounts {
        let routing_tag = if acc.name == pinned {
            Span::styled("  pinned", style_yellow())
        } else if acc.name == last {
            Span::styled("  active", style_green())
        } else {
            Span::raw("")
        };

        let (status_sym, status_style) = if acc.disabled || acc.auth_failed {
            ("", style_red())
        } else if !acc.available {
            ("", style_yellow())
        } else {
            ("", style_green())
        };

        let provider_tag: Span<'static> = match acc.provider.as_str() {
            "anthropic" | "" => Span::raw(""),
            "openai"    => Span::styled("  [chatgpt]".to_string(), Style::default().fg(YELLOW)),
            other       => Span::styled(format!("  [{other}]"), Style::default().fg(CYAN)),
        };
        lines.push(Line::from(vec![
            Span::styled(format!(" {status_sym} "), status_style),
            Span::styled(acc.name.clone(), Style::default().fg(GREEN).add_modifier(Modifier::BOLD)),
            routing_tag,
            provider_tag,
        ]));

        if let Some(email) = &acc.email {
            lines.push(Line::from(vec![
                Span::styled("   ", style_dim()),
                Span::styled(email.as_str(), style_dim()),
            ]));
        }

        // Cooldown countdown (only when actively cooling)
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;
        if acc.cooldown_until_ms > now_ms {
            let remaining_ms = acc.cooldown_until_ms - now_ms;
            lines.push(Line::from(vec![
                Span::styled("   ⏸ cooldown  ", style_yellow()),
                Span::styled(
                    format!("resumes in {}", fmt_duration_ms(remaining_ms)),
                    style_yellow(),
                ),
            ]));
        }

        // Rate-limit bars — only Anthropic reports utilization windows.
        if acc.provider == "anthropic" || acc.provider.is_empty() {
            lines.push(util_bar_line("5h", acc.utilization_5h, acc.reset_5h));
            lines.push(util_bar_line("7d", acc.utilization_7d, acc.reset_7d));
        }

        lines.push(Line::raw(""));
    }

    f.render_widget(Paragraph::new(lines), inner);
}

fn util_bar_line(label: &'static str, util: f64, reset: Option<u64>) -> Line<'static> {
    let util = util.clamp(0.0, 1.0);
    let bar_w = 20usize;
    let filled = (util * bar_w as f64).round() as usize;
    let bar_color = if util >= 0.9 { RED } else if util >= 0.6 { YELLOW } else { GREEN };
    let bar = format!("{}{}", "".repeat(filled), "".repeat(bar_w.saturating_sub(filled)));
    let pct = format!("{:.0}%", util * 100.0);

    let reset_str = reset.map(|reset_secs| {
        let now_secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        if reset_secs > now_secs {
            let diff_ms = (reset_secs - now_secs) * 1000;
            format!("  resets {}", fmt_duration_ms(diff_ms))
        } else {
            String::new()
        }
    }).unwrap_or_default();

    Line::from(vec![
        Span::styled(format!("   {label} "), style_dim()),
        Span::styled(bar, Style::default().fg(bar_color)),
        Span::styled(format!(" {pct}"), Style::default().fg(bar_color)),
        Span::styled(reset_str, style_dim()),
    ])
}

// ---------------------------------------------------------------------------
// History chart
// ---------------------------------------------------------------------------

fn draw_history_chart(
    f: &mut Frame,
    area: Rect,
    s: &StatusResponse,
    window: TimeWindow,
) {
    // Build a title row that doubles as the time-window selector.
    // Highlight the active window in green, others dimmed.
    let all_windows = [
        TimeWindow::OneMin,
        TimeWindow::FiveMin,
        TimeWindow::FifteenMin,
        TimeWindow::SixtyMin,
    ];
    let mut title_spans: Vec<Span> = vec![Span::styled(" history ", style_dim())];
    for w in all_windows {
        if w == window {
            title_spans.push(Span::styled(
                format!("[{}]", w.label()),
                Style::default().fg(GREEN).add_modifier(Modifier::BOLD),
            ));
        } else {
            title_spans.push(Span::styled(format!(" {} ", w.label()), style_dim()));
        }
    }

    let block = Block::default()
        .title(Line::from(title_spans))
        .borders(Borders::NONE)
        .border_style(style_dkgreen());

    let inner = block.inner(area);
    f.render_widget(block, area);

    // Need at least a few rows and columns to render a meaningful chart.
    if inner.height < 4 || inner.width < 12 {
        return;
    }

    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64;

    let n_buckets = window.bucket_count();
    let bucket_ms = window.bucket_ms();
    let window_ms = window.ms();
    let window_secs = window_ms as f64 / 1000.0;
    let bucket_secs = bucket_ms as f64 / 1000.0;

    // Build per-account bucket data.
    let account_names: Vec<&str> = s.accounts.iter().map(|a| a.name.as_str()).collect();
    let n_accounts = account_names.len();

    // account_buckets[acc_idx][bucket_idx] = value
    let mut account_buckets: Vec<Vec<f64>> = vec![vec![0.0; n_buckets]; n_accounts.max(1)];

    for req in &s.recent_requests {
        let age_ms = now_ms.saturating_sub(req.ts_ms);
        if age_ms >= window_ms {
            continue;
        }
        let acc_idx = account_names.iter().position(|&n| n == req.account);
        if let Some(idx) = acc_idx {
            // bucket 0 = oldest, bucket n-1 = newest
            let b = (n_buckets - 1).saturating_sub((age_ms / bucket_ms) as usize);
            account_buckets[idx][b] += 1.0;
        }
    }

    // Convert buckets to (x, y) points (x = seconds from window start).
    let all_points: Vec<Vec<(f64, f64)>> = account_buckets
        .iter()
        .map(|buckets| {
            buckets
                .iter()
                .enumerate()
                .map(|(b, &v)| (b as f64 * bucket_secs, v))
                .collect()
        })
        .collect();

    // Find the maximum value across all accounts for y-axis scaling.
    let max_val = all_points
        .iter()
        .flat_map(|pts| pts.iter().map(|(_, v)| *v))
        .fold(0.0_f64, f64::max)
        .max(1.0);

    // Only include accounts that have at least one non-zero bucket.
    let active_datasets: Vec<(usize, &str, &[(f64, f64)])> = all_points
        .iter()
        .enumerate()
        .filter(|(_, pts)| pts.iter().any(|(_, v)| *v > 0.0))
        .map(|(i, pts)| (i, account_names.get(i).copied().unwrap_or("?"), pts.as_slice()))
        .collect();

    if active_datasets.is_empty() {
        let msg = Line::from(Span::styled(
            format!("  no requests in the last {}", window.label()),
            style_dim(),
        ));
        f.render_widget(Paragraph::new(msg), inner);
        return;
    }

    let datasets: Vec<Dataset> = active_datasets
        .iter()
        .map(|(acc_idx, name, pts)| {
            let color = ACCOUNT_COLORS[acc_idx % ACCOUNT_COLORS.len()];
            Dataset::default()
                .name(*name)
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(color))
                .data(pts)
        })
        .collect();

    // X-axis labels: left = "-<window>", mid = "-<half>", right = "now"
    let half_label = fmt_secs_label(window_secs / 2.0);
    let x_labels = vec![
        Span::styled(format!("-{}", window.label()), style_dim()),
        Span::styled(format!("-{half_label}"), style_dim()),
        Span::styled("now", style_green()),
    ];

    // Y-axis labels: 0 at bottom, max at top
    let y_top_label = format!("{:.0}", max_val);
    let y_mid_label = format!("{:.0}", max_val / 2.0);
    let y_labels = vec![
        Span::styled("0", style_dim()),
        Span::styled(y_mid_label, style_dim()),
        Span::styled(y_top_label, style_dim()),
    ];

    let chart = Chart::new(datasets)
        .x_axis(
            Axis::default()
                .bounds([0.0, window_secs])
                .labels(x_labels)
                .style(style_dkgreen()),
        )
        .y_axis(
            Axis::default()
                .bounds([0.0, max_val])
                .labels(y_labels)
                .style(style_dkgreen()),
        );

    f.render_widget(chart, inner);
}

/// Format a duration in seconds as a compact human string (for axis labels).
fn fmt_secs_label(secs: f64) -> String {
    if secs < 60.0 {
        format!("{:.0}s", secs)
    } else if secs < 3600.0 {
        format!("{:.0}m", secs / 60.0)
    } else {
        format!("{:.0}h", secs / 3600.0)
    }
}


// ---------------------------------------------------------------------------
// Request log (right panel — unchanged)
// ---------------------------------------------------------------------------

fn draw_request_log(f: &mut Frame, area: Rect, s: &StatusResponse, scroll: usize) {
    // Calculate requests per minute from last 60s
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64;
    let req_per_min = s.recent_requests.iter()
        .filter(|r| now_ms.saturating_sub(r.ts_ms) < 60_000)
        .count();
    let rate_str = if req_per_min > 0 {
        format!("  {req_per_min}/min")
    } else {
        String::new()
    };

    let block = Block::default()
        .title(Line::from(vec![
            Span::styled(" requests", style_dim()),
            Span::styled(rate_str, style_dim()),
        ]))
        .borders(Borders::BOTTOM)
        .border_style(style_dkgreen());

    let inner = block.inner(area);
    f.render_widget(block, area);

    if s.recent_requests.is_empty() {
        let p = Paragraph::new(Line::from(Span::styled("  no requests yet", style_dim())));
        f.render_widget(p, inner);
        return;
    }

    let header = Row::new(vec![
        Cell::from(Span::styled("time", style_dim())),
        Cell::from(Span::styled("account", style_dim())),
        Cell::from(Span::styled("model", style_dim())),
        Cell::from(Span::styled("dur", style_dim())),
    ]).height(1);

    let rows: Vec<Row> = s.recent_requests
        .iter()
        .skip(scroll)
        .map(|r| {
            let age_ms = now_ms.saturating_sub(r.ts_ms);
            let time_str = if age_ms < 60_000 {
                format!("{}s ago", age_ms / 1000)
            } else {
                format!("{} ago", fmt_duration_ms(age_ms))
            };
            let model_short = shorten_model(&r.model);
            Row::new(vec![
                Cell::from(Span::styled(time_str, style_dim())),
                Cell::from(Span::styled(&r.account, style_green())),
                Cell::from(Span::styled(model_short, style_cyan())),
                Cell::from(Span::styled(fmt_dur_short(r.duration_ms), style_dim())),
            ])
        })
        .collect();

    let widths = [
        Constraint::Length(8),
        Constraint::Length(12),
        Constraint::Min(16),
        Constraint::Length(7),
    ];

    let table = Table::new(rows, widths)
        .header(header)
        .row_highlight_style(style_green())
        .column_spacing(1);

    f.render_widget(table, inner);
}

// ---------------------------------------------------------------------------
// Picker overlay
// ---------------------------------------------------------------------------

fn draw_picker(f: &mut Frame, picker: &Picker, area: Rect) {
    let h = (picker.items.len() + 4) as u16;
    let w = 36u16;
    let x = area.x + area.width.saturating_sub(w) / 2;
    let y = area.y + area.height.saturating_sub(h) / 2;
    let popup_area = Rect { x, y, width: w.min(area.width), height: h.min(area.height) };

    f.render_widget(Clear, popup_area);

    let block = Block::default()
        .title(Line::from(vec![
            Span::styled(" pin account ", style_dim()),
        ]))
        .borders(Borders::ALL)
        .border_style(style_dkgreen());

    let inner = block.inner(popup_area);
    f.render_widget(block, popup_area);

    let rows: Vec<Row> = picker.items.iter().enumerate().map(|(i, item)| {
        let is_sel = i == picker.cursor;
        let label = if item == "auto" {
            format!("  {} auto routing", if is_sel { "" } else { " " })
        } else {
            format!("  {} {}", if is_sel { "" } else { " " }, item)
        };
        let style = if is_sel {
            Style::default().fg(GREEN).add_modifier(Modifier::BOLD)
        } else {
            style_dim()
        };
        Row::new(vec![Cell::from(Span::styled(label, style))])
    }).collect();

    let table = Table::new(rows, [Constraint::Min(0)]).column_spacing(0);
    f.render_widget(table, inner);
}

// ---------------------------------------------------------------------------
// Help overlay
// ---------------------------------------------------------------------------

fn draw_help_overlay(f: &mut Frame, area: Rect) {
    let lines: &[(&str, &str)] = &[
        ("q / Esc",  "quit"),
        ("r",        "force refresh"),
        ("u",        "pin account"),
        ("↑ / k",   "scroll log up"),
        ("↓ / j",   "scroll log down"),
        ("+  / =",  "faster refresh rate"),
        ("-",        "slower refresh rate"),
        ("t / ]",   "next time window"),
        ("[",        "prev time window"),
        ("?",        "toggle this help"),
        ("any key",  "close help"),
    ];

    let h = (lines.len() + 4) as u16;
    let w = 42u16;
    let x = area.x + area.width.saturating_sub(w) / 2;
    let y = area.y + area.height.saturating_sub(h) / 2;
    let popup_area = Rect { x, y, width: w.min(area.width), height: h.min(area.height) };

    f.render_widget(Clear, popup_area);

    let block = Block::default()
        .title(Line::from(vec![
            Span::styled(" shortcuts ", style_dim()),
        ]))
        .borders(Borders::ALL)
        .border_style(style_dkgreen());

    let inner = block.inner(popup_area);
    f.render_widget(block, popup_area);

    let rows: Vec<Row> = lines.iter().map(|(key, desc)| {
        Row::new(vec![
            Cell::from(Span::styled(format!("  {key}"), style_green())),
            Cell::from(Span::styled(format!("  {desc}"), style_dim())),
        ])
    }).collect();

    let table = Table::new(rows, [Constraint::Length(14), Constraint::Min(0)])
        .column_spacing(1);
    f.render_widget(table, inner);
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn shorten_model(model: &str) -> String {
    let s = model.trim_start_matches("claude-");
    let s = if let Some(idx) = s.rfind('-') {
        let suffix = &s[idx + 1..];
        if suffix.len() == 8 && suffix.chars().all(|c| c.is_ascii_digit()) {
            &s[..idx]
        } else {
            s
        }
    } else {
        s
    };
    s.to_owned()
}

fn fmt_dur_short(ms: u64) -> String {
    if ms < 1_000 { format!("{ms}ms") }
    else if ms < 60_000 { format!("{:.1}s", ms as f64 / 1_000.0) }
    else { format!("{}m", ms / 60_000) }
}