starling-devex 0.1.13

Starling: a local dev orchestrator with a central daemon, shared named-URL proxy, and a k9s-style TUI (a Rust port of Tilt + portless)
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
//! k9s-style terminal dashboard for Starling.
//!
//! Connects to the daemon, polls the aggregated state across all `starling up`
//! instances, and renders a navigable resource table with a live log pane.
//!
//! Keys:
//!   j/k, ↑/↓   move selection
//!   /          filter (Enter apply, Esc clear)
//!   Enter      detail view for the selected resource (Esc to exit)
//!   t          trigger the selected resource
//!   R          restart the selected resource's serve_cmd
//!   p          change the selected resource's preferred backend port
//!   PgUp/PgDn  scroll logs (G / End jumps back to follow)
//!   r          refresh now
//!   q          quit

use std::io;
use std::time::{Duration, Instant};

use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use crossterm::execute;
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Cell, Paragraph, Row, Table, TableState};
use ratatui::{Frame, Terminal};

use crate::daemon::client::DaemonClient;
use crate::daemon::protocol::{DashboardState, Request, Response};

/// A small, cohesive color palette (Tokyo Night-ish) used across the dashboard.
mod theme {
    use ratatui::style::Color;
    pub const ACCENT: Color = Color::Rgb(122, 162, 247); // soft blue
    pub const HEADER_BG: Color = Color::Rgb(36, 40, 59);
    pub const SEL_BG: Color = Color::Rgb(54, 60, 96);
    pub const MUTED: Color = Color::Rgb(132, 137, 165);
    pub const URL: Color = Color::Rgb(125, 207, 255);
    pub const OK: Color = Color::Rgb(158, 206, 106);
    pub const ERR: Color = Color::Rgb(247, 118, 142);
    pub const WARN: Color = Color::Rgb(224, 175, 104);
    pub const INFO: Color = Color::Rgb(125, 207, 255);
}

/// Braille spinner frames used for `in_progress` status.
const SPINNER: [&str; 10] = ["", "", "", "", "", "", "", "", "", ""];

/// Symbol + color for a status value. `frame` advances the in-progress spinner.
fn status_symbol(s: &str, frame: usize) -> (&'static str, Style) {
    match s {
        "ok" => ("", Style::default().fg(theme::OK)),
        "error" => ("", Style::default().fg(theme::ERR)),
        "in_progress" => (SPINNER[frame % SPINNER.len()], Style::default().fg(theme::WARN)),
        "pending" => ("", Style::default().fg(theme::INFO)),
        "not_applicable" | "none" | "" => ("·", Style::default().fg(Color::DarkGray)),
        _ => ("", Style::default()),
    }
}

/// Human-friendly label for a raw status string.
fn pretty_status(s: &str) -> String {
    match s {
        "not_applicable" | "none" | "" => "".into(),
        "in_progress" => "building".into(),
        other => other.replace('_', " "),
    }
}

/// A status cell: colored symbol followed by its prettified label.
fn status_cell(s: &str, frame: usize) -> Line<'static> {
    let (sym, style) = status_symbol(s, frame);
    Line::from(vec![
        Span::styled(sym, style),
        Span::raw(" "),
        Span::styled(pretty_status(s), style),
    ])
}

/// Build a styled footer line from `(key, label)` pairs: keys in accent, labels muted.
fn key_hints(pairs: &[(&str, &str)]) -> Line<'static> {
    let mut spans = vec![Span::raw(" ")];
    for (k, label) in pairs {
        spans.push(Span::styled(
            (*k).to_string(),
            Style::default().fg(theme::ACCENT).add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled(format!(" {label}   "), Style::default().fg(theme::MUTED)));
    }
    Line::from(spans)
}

/// One displayed row: a resource belonging to an instance.
#[derive(Clone)]
struct RowItem {
    instance_id: String,
    instance_name: String,
    name: String,
    kind: String,
    update: String,
    runtime: String,
    pod: String,
    url: String,
    route_port: Option<u16>,
}

#[derive(PartialEq)]
enum Mode {
    Normal,
    Filter,
    Detail,
    /// Full-screen logs for the selected resource.
    Logs,
    /// Typing a log-line filter (regex) while in full-screen logs.
    LogsFilter,
    /// Typing a new preferred backend port for the selected resource.
    PortEdit,
}

pub async fn run(proxy_port: u16, tld: &str, tls: bool) {
    let client = DaemonClient::new();
    if let Err(e) = client.ensure_running(proxy_port, tld, tls).await {
        eprintln!("starling: {e}");
        return;
    }
    if let Err(e) = run_ui(client).await {
        eprintln!("starling tui error: {e}");
    }
}

async fn run_ui(client: DaemonClient) -> io::Result<()> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let res = event_loop(&mut terminal, &client).await;

    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;
    res
}

struct App {
    state: DashboardState,
    rows: Vec<RowItem>,
    table: TableState,
    logs: Vec<String>,
    mode: Mode,
    filter: String,
    /// Regex/substring filter applied to log lines (full-screen + log pane).
    log_filter: String,
    /// Lines scrolled up from the bottom; 0 = follow tail.
    log_scroll: usize,
    /// Port being edited in the footer.
    port_input: String,
    status_msg: String,
    /// When `status_msg` was set; it fades from the footer after a few seconds.
    status_at: Option<Instant>,
    /// Reference instant for time-based animation (the in-progress spinner).
    start: Instant,
}

impl App {
    fn selected(&self) -> Option<&RowItem> {
        self.table.selected().and_then(|i| self.rows.get(i))
    }

    /// Show a transient status message in the footer.
    fn note(&mut self, msg: String) {
        self.status_msg = msg;
        self.status_at = Some(Instant::now());
    }

    /// The current status message, if it hasn't yet faded out.
    fn active_status(&self) -> Option<&str> {
        match self.status_at {
            Some(t) if t.elapsed() < Duration::from_secs(4) => Some(self.status_msg.as_str()),
            _ => None,
        }
    }

    /// Current spinner frame, derived from elapsed time so it animates smoothly.
    fn spinner_frame(&self) -> usize {
        (self.start.elapsed().as_millis() / 90) as usize
    }

    /// Log lines for the selected resource, filtered by `log_filter`.
    fn filtered_logs(&self) -> Vec<String> {
        filter_log_lines(&self.logs, &self.log_filter)
    }
}

/// Make a line of externally-sourced text safe to put into ratatui's cell
/// buffer.
///
/// Process logs routinely carry ANSI/VT escape sequences (colors, cursor
/// moves) and other control bytes. ratatui copies a string's bytes verbatim
/// into its grid and has no notion of escape sequences, so an unescaped `\x1b`
/// is written straight to the terminal — bleeding colors and jumping the
/// cursor across the whole UI. This strips those sequences and control
/// characters while preserving every printable character, **including emoji**,
/// so text still renders (just without the corruption).
fn sanitize(line: &str) -> String {
    let mut out = String::with_capacity(line.len());
    let mut chars = line.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            // ESC introduces an escape sequence; consume and drop it.
            '\u{1b}' => match chars.peek() {
                // CSI: ESC [ <params/intermediates> <final 0x40..=0x7e>
                Some('[') => {
                    chars.next();
                    while let Some(&n) = chars.peek() {
                        chars.next();
                        if ('\u{40}'..='\u{7e}').contains(&n) {
                            break;
                        }
                    }
                }
                // OSC: ESC ] ... terminated by BEL or ST (ESC \).
                Some(']') => {
                    chars.next();
                    while let Some(&n) = chars.peek() {
                        if n == '\u{7}' {
                            chars.next();
                            break;
                        }
                        if n == '\u{1b}' {
                            chars.next();
                            if chars.peek() == Some(&'\\') {
                                chars.next();
                            }
                            break;
                        }
                        chars.next();
                    }
                }
                // Any other two-character escape (ESC X): drop both.
                Some(_) => {
                    chars.next();
                }
                None => {}
            },
            '\t' => out.push_str("    "),
            // Drop carriage returns and every other control char (C0/C1, DEL,
            // and any stray newline within a line). Emoji and printable text
            // are left untouched.
            c if c.is_control() => {}
            c => out.push(c),
        }
    }
    out
}

/// Filter log lines by `pattern` (a regex; falls back to case-insensitive
/// substring if the regex doesn't compile). Empty pattern = all lines.
fn filter_log_lines(logs: &[String], pattern: &str) -> Vec<String> {
    if pattern.is_empty() {
        return logs.to_vec();
    }
    match regex::RegexBuilder::new(pattern).case_insensitive(true).build() {
        Ok(re) => logs.iter().filter(|l| re.is_match(l)).cloned().collect(),
        Err(_) => {
            let needle = pattern.to_ascii_lowercase();
            logs.iter()
                .filter(|l| l.to_ascii_lowercase().contains(&needle))
                .cloned()
                .collect()
        }
    }
}

async fn event_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    client: &DaemonClient,
) -> io::Result<()> {
    let mut app = App {
        state: DashboardState::default(),
        rows: vec![],
        table: TableState::default().with_selected(Some(0)),
        logs: vec![],
        mode: Mode::Normal,
        filter: String::new(),
        log_filter: String::new(),
        log_scroll: 0,
        port_input: String::new(),
        status_msg: String::new(),
        status_at: None,
        start: Instant::now(),
    };
    let mut last_refresh = Instant::now() - Duration::from_secs(1);

    loop {
        if last_refresh.elapsed() >= Duration::from_millis(500) {
            if let Ok(Response::State(s)) = client.call(&Request::GetState).await {
                app.state = s;
            }
            app.rows = filtered(&app.state, &app.filter);
            let sel = app
                .table
                .selected()
                .unwrap_or(0)
                .min(app.rows.len().saturating_sub(1));
            app.table.select(if app.rows.is_empty() { None } else { Some(sel) });
            app.logs = match app.selected() {
                Some(r) => fetch_logs(client, &r.instance_id, &r.name).await,
                None => vec![],
            };
            last_refresh = Instant::now();
        }

        terminal.draw(|f| draw(f, &mut app))?;

        // Poll at ~10fps so the in-progress spinner animates while idle.
        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key) = event::read()? {
                if key.kind != KeyEventKind::Press {
                    continue;
                }
                let ctrl_c = key.modifiers.contains(KeyModifiers::CONTROL)
                    && key.code == KeyCode::Char('c');
                if ctrl_c {
                    break;
                }

                match app.mode {
                    Mode::Filter => {
                        match key.code {
                            KeyCode::Enter => app.mode = Mode::Normal,
                            KeyCode::Esc => {
                                app.filter.clear();
                                app.mode = Mode::Normal;
                            }
                            KeyCode::Backspace => {
                                app.filter.pop();
                            }
                            KeyCode::Char(c) => app.filter.push(c),
                            _ => {}
                        }
                        // Re-filter and refetch logs on the next tick so the
                        // table reacts to each keystroke instead of lagging.
                        last_refresh = Instant::now() - Duration::from_secs(1);
                    }
                    // Typing a log-line filter inside the full-screen log view.
                    Mode::LogsFilter => match key.code {
                        KeyCode::Enter => app.mode = Mode::Logs,
                        KeyCode::Esc => {
                            app.log_filter.clear();
                            app.mode = Mode::Logs;
                        }
                        KeyCode::Backspace => {
                            app.log_filter.pop();
                        }
                        KeyCode::Char(c) => {
                            app.log_filter.push(c);
                            app.log_scroll = 0;
                        }
                        _ => {}
                    },
                    Mode::PortEdit => match key.code {
                        KeyCode::Enter => match parse_port(&app.port_input) {
                            Some(port) => {
                                if let Some(r) = app.selected().cloned() {
                                    let resp = client
                                        .call(&Request::SetPort {
                                            instance: r.instance_id.clone(),
                                            resource: r.name.clone(),
                                            port,
                                        })
                                        .await;
                                    let msg = match resp {
                                        Ok(Response::Ok) => {
                                            format!("changing {} to port {port}", r.name)
                                        }
                                        Ok(Response::Error(e)) => {
                                            format!("couldn't change port: {e}")
                                        }
                                        Ok(other) => format!("unexpected daemon response: {other:?}"),
                                        Err(e) => format!("couldn't change port: {e}"),
                                    };
                                    app.note(msg);
                                }
                                app.mode = Mode::Normal;
                            }
                            None => {
                                app.note("port must be 1-65535".to_string());
                            }
                        },
                        KeyCode::Esc => {
                            app.port_input.clear();
                            app.mode = Mode::Normal;
                        }
                        KeyCode::Backspace => {
                            app.port_input.pop();
                        }
                        KeyCode::Char(c) if c.is_ascii_digit() => {
                            app.port_input.push(c);
                        }
                        _ => {}
                    },
                    // Full-screen logs for the selected resource.
                    Mode::Logs => match key.code {
                        KeyCode::Char('q') | KeyCode::Esc | KeyCode::Char('l') => {
                            app.mode = Mode::Normal;
                        }
                        KeyCode::Char('/') => app.mode = Mode::LogsFilter,
                        KeyCode::PageUp | KeyCode::Char('k') | KeyCode::Up => app.log_scroll += 5,
                        KeyCode::PageDown | KeyCode::Char('j') | KeyCode::Down => {
                            app.log_scroll = app.log_scroll.saturating_sub(5)
                        }
                        KeyCode::Char('G') | KeyCode::End => app.log_scroll = 0,
                        KeyCode::Char('o') => {
                            if let Some(r) = app.selected() {
                                if !r.url.is_empty() {
                                    let _ = open_url(&r.url);
                                }
                            }
                        }
                        _ => {}
                    },
                    Mode::Normal | Mode::Detail => match key.code {
                        KeyCode::Char('q') => break,
                        KeyCode::Esc if app.mode == Mode::Detail => app.mode = Mode::Normal,
                        KeyCode::Esc => break,
                        KeyCode::Char('j') | KeyCode::Down => {
                            move_sel(&mut app, 1);
                            last_refresh = Instant::now() - Duration::from_secs(1);
                        }
                        KeyCode::Char('k') | KeyCode::Up => {
                            move_sel(&mut app, -1);
                            last_refresh = Instant::now() - Duration::from_secs(1);
                        }
                        KeyCode::Enter => {
                            app.mode = if app.mode == Mode::Detail {
                                Mode::Normal
                            } else {
                                Mode::Detail
                            };
                        }
                        KeyCode::Char('l') => {
                            app.log_scroll = 0;
                            app.mode = Mode::Logs;
                        }
                        KeyCode::Char('/') => {
                            app.mode = Mode::Filter;
                        }
                        KeyCode::Char('r') => {
                            last_refresh = Instant::now() - Duration::from_secs(1);
                        }
                        KeyCode::PageUp => app.log_scroll += 5,
                        KeyCode::PageDown => app.log_scroll = app.log_scroll.saturating_sub(5),
                        KeyCode::Char('G') | KeyCode::End => app.log_scroll = 0,
                        KeyCode::Char('t') => {
                            if let Some(r) = app.selected() {
                                let _ = client
                                    .call(&Request::Trigger {
                                        instance: r.instance_id.clone(),
                                        resource: r.name.clone(),
                                    })
                                    .await;
                                let name = r.name.clone();
                                app.note(format!("triggered {name}"));
                            }
                        }
                        KeyCode::Char('R') => {
                            if let Some(r) = app.selected() {
                                let _ = client
                                    .call(&Request::Restart {
                                        instance: r.instance_id.clone(),
                                        resource: r.name.clone(),
                                    })
                                    .await;
                                let name = r.name.clone();
                                app.note(format!("restarting {name}"));
                            }
                        }
                        KeyCode::Char('p') => {
                            if let Some(r) = app.selected() {
                                app.port_input = r
                                    .route_port
                                    .map(|p| p.to_string())
                                    .unwrap_or_default();
                                app.mode = Mode::PortEdit;
                            }
                        }
                        KeyCode::Char('o') => {
                            match app.selected() {
                                Some(r) if !r.url.is_empty() => {
                                    let url = r.url.clone();
                                    let msg = match open_url(&url) {
                                        Ok(()) => format!("opening {url}"),
                                        Err(e) => format!("couldn't open {url}: {e}"),
                                    };
                                    app.note(msg);
                                }
                                Some(r) => {
                                    let name = r.name.clone();
                                    app.note(format!("{name} has no URL"));
                                }
                                None => {}
                            }
                        }
                        _ => {}
                    },
                }
            }
        }
    }
    Ok(())
}

/// Open a URL in the default browser (platform-specific opener).
fn open_url(url: &str) -> io::Result<()> {
    #[cfg(target_os = "macos")]
    let mut cmd = std::process::Command::new("open");
    #[cfg(target_os = "windows")]
    let mut cmd = {
        let mut c = std::process::Command::new("cmd");
        c.args(["/C", "start", ""]);
        c
    };
    #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
    let mut cmd = std::process::Command::new("xdg-open");

    cmd.arg(url)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map(|_| ())
}

fn move_sel(app: &mut App, delta: i32) {
    if app.rows.is_empty() {
        return;
    }
    let cur = app.table.selected().unwrap_or(0) as i32;
    let next = (cur + delta).rem_euclid(app.rows.len() as i32);
    app.table.select(Some(next as usize));
    app.log_scroll = 0;
}

fn filtered(state: &DashboardState, filter: &str) -> Vec<RowItem> {
    let f = filter.to_ascii_lowercase();
    let mut rows = vec![];
    for inst in &state.instances {
        for r in &inst.resources {
            let item = RowItem {
                instance_id: inst.id.clone(),
                instance_name: inst.name.clone(),
                name: r.name.clone(),
                kind: r.kind.clone(),
                update: r.update_status.clone(),
                runtime: r.runtime_status.clone(),
                pod: r.pod.clone().unwrap_or_default(),
                url: r.url.clone().unwrap_or_default(),
                route_port: route_port_for_url(state, &inst.id, r.url.as_deref()),
            };
            if f.is_empty()
                || item.name.to_ascii_lowercase().contains(&f)
                || item.instance_name.to_ascii_lowercase().contains(&f)
            {
                rows.push(item);
            }
        }
    }
    rows
}

fn route_port_for_url(state: &DashboardState, instance: &str, url: Option<&str>) -> Option<u16> {
    let host = hostname_from_url(url?)?;
    state
        .routes
        .iter()
        .find(|r| r.instance == instance && r.hostname == host)
        .map(|r| r.port)
}

fn hostname_from_url(url: &str) -> Option<String> {
    let after_scheme = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);
    let authority = after_scheme.split('/').next().unwrap_or(after_scheme);
    if authority.is_empty() {
        return None;
    }
    Some(authority.split(':').next().unwrap_or(authority).to_string())
}

fn parse_port(input: &str) -> Option<u16> {
    let port = input.parse::<u16>().ok()?;
    (port != 0).then_some(port)
}

async fn fetch_logs(client: &DaemonClient, instance: &str, resource: &str) -> Vec<String> {
    match client
        .call(&Request::GetLogs {
            instance: instance.to_string(),
            resource: resource.to_string(),
        })
        .await
    {
        // Sanitize on the way in so escape sequences and control bytes from
        // the underlying process can never reach ratatui's buffer.
        Ok(Response::Logs(l)) => l.iter().map(|line| sanitize(line)).collect(),
        _ => vec![],
    }
}

/// Render the tail of `logs` into a pane of inner height `h`, honoring scroll.
fn log_lines(logs: &[String], h: usize, scroll: usize) -> Vec<Line<'static>> {
    if logs.is_empty() {
        return vec![];
    }
    let max_scroll = logs.len().saturating_sub(h);
    let scroll = scroll.min(max_scroll);
    let end = logs.len() - scroll;
    let start = end.saturating_sub(h);
    logs[start..end].iter().map(|l| Line::raw(l.clone())).collect()
}

fn draw(f: &mut Frame, app: &mut App) {
    if app.mode == Mode::Detail {
        draw_detail(f, app);
        return;
    }
    if app.mode == Mode::Logs || app.mode == Mode::LogsFilter {
        draw_logs_fullscreen(f, app);
        return;
    }

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

    f.render_widget(title_bar(app), chunks[0]);

    let frame = app.spinner_frame();
    let header = Row::new(
        ["INSTANCE", "RESOURCE", "TYPE", "UPDATE", "RUNTIME", "PORT", "POD", "URL"]
            .iter()
            .map(|h| {
                Cell::from(*h).style(
                    Style::default()
                        .fg(theme::ACCENT)
                        .add_modifier(Modifier::BOLD),
                )
            }),
    )
    .height(1)
    .bottom_margin(1);
    let table_rows: Vec<Row> = app
        .rows
        .iter()
        .map(|r| {
            Row::new(vec![
                Cell::from(Span::styled(r.instance_name.clone(), Style::default().fg(theme::MUTED))),
                Cell::from(Span::styled(
                    r.name.clone(),
                    Style::default().add_modifier(Modifier::BOLD),
                )),
                Cell::from(r.kind.clone()),
                Cell::from(status_cell(&r.update, frame)),
                Cell::from(status_cell(&r.runtime, frame)),
                Cell::from(r.route_port.map(|p| p.to_string()).unwrap_or_default()),
                Cell::from(r.pod.clone()),
                Cell::from(Span::styled(r.url.clone(), Style::default().fg(theme::URL))),
            ])
        })
        .collect();
    let widths = [
        Constraint::Length(14),
        Constraint::Length(18),
        Constraint::Length(6),
        Constraint::Length(13),
        Constraint::Length(13),
        Constraint::Length(7),
        Constraint::Length(20),
        Constraint::Min(20),
    ];
    let table = Table::new(table_rows, widths)
        .header(header)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme::MUTED))
                .title(Span::styled(
                    " Resources ",
                    Style::default().fg(theme::ACCENT).add_modifier(Modifier::BOLD),
                )),
        )
        .highlight_style(
            Style::default().bg(theme::SEL_BG).add_modifier(Modifier::BOLD),
        )
        .highlight_symbol(Span::styled("", Style::default().fg(theme::ACCENT)));
    f.render_stateful_widget(table, chunks[1], &mut app.table);

    let sel_name = app
        .selected()
        .map(|r| format!("{} / {}", r.instance_name, r.name))
        .unwrap_or_else(|| "".into());
    let h = chunks[2].height.saturating_sub(2) as usize;
    let follow = if app.log_scroll == 0 { "" } else { " · scrolled" };
    let logs = app.filtered_logs();
    let filt = if app.log_filter.is_empty() {
        String::new()
    } else {
        format!(" /{}", app.log_filter)
    };
    f.render_widget(
        Paragraph::new(log_body(&logs, h, app.log_scroll)).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme::MUTED))
                .title(Span::styled(
                    format!(" Logs · {sel_name}{filt}{follow} "),
                    Style::default().fg(theme::ACCENT),
                )),
        ),
        chunks[2],
    );

    let footer: Line = if app.mode == Mode::Filter {
        prompt_line("filter", &app.filter, "Enter apply · Esc clear")
    } else if app.mode == Mode::PortEdit {
        prompt_line("port", &app.port_input, "Enter apply · Esc cancel")
    } else if app.rows.is_empty() {
        Line::from(vec![
            Span::styled(
                " No resources. ",
                Style::default().fg(theme::WARN).add_modifier(Modifier::BOLD),
            ),
            Span::styled("Run `starling up` in a project.", Style::default().fg(theme::MUTED)),
        ])
    } else if let Some(msg) = app.active_status() {
        Line::from(vec![
            Span::raw(" "),
            Span::styled("", Style::default().fg(theme::ACCENT)),
            Span::styled(msg.to_string(), Style::default().fg(Color::White)),
        ])
    } else {
        key_hints(&[
            ("j/k", "move"),
            ("", "detail"),
            ("l", "logs"),
            ("o", "open"),
            ("t", "trigger"),
            ("R", "restart"),
            ("p", "port"),
            ("/", "filter"),
            ("q", "quit"),
        ])
    };
    f.render_widget(Paragraph::new(footer), chunks[3]);
}

/// The top status bar: an accent badge plus muted instance/proxy details.
fn title_bar(app: &App) -> Paragraph<'static> {
    let line = Line::from(vec![
        Span::styled(
            " ✦ Starling ",
            Style::default()
                .fg(Color::Rgb(20, 22, 34))
                .bg(theme::ACCENT)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(
                "  {} instances · {} resources · proxy :{} · .{} ",
                app.state.instances.len(),
                app.rows.len(),
                app.state.proxy_port,
                app.state.tld,
            ),
            Style::default().fg(theme::MUTED).bg(theme::HEADER_BG),
        ),
    ]);
    Paragraph::new(line).style(Style::default().bg(theme::HEADER_BG))
}

/// A footer input prompt with a blinking-style cursor block.
fn prompt_line(label: &str, value: &str, hint: &str) -> Line<'static> {
    Line::from(vec![
        Span::raw(" "),
        Span::styled(format!("{label} "), Style::default().fg(theme::ACCENT).add_modifier(Modifier::BOLD)),
        Span::styled(format!("{value}\u{2588}"), Style::default().fg(Color::White)),
        Span::styled(format!("   {hint} "), Style::default().fg(theme::MUTED)),
    ])
}

/// Log lines for a pane, or a muted placeholder when there is no output yet.
fn log_body(logs: &[String], h: usize, scroll: usize) -> Vec<Line<'static>> {
    if logs.is_empty() {
        return vec![Line::from(Span::styled(
            "  — no log output yet —",
            Style::default().fg(theme::MUTED).add_modifier(Modifier::ITALIC),
        ))];
    }
    log_lines(logs, h, scroll)
}

fn draw_detail(f: &mut Frame, app: &mut App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),
            Constraint::Length(10),
            Constraint::Min(4),
            Constraint::Length(1),
        ])
        .split(f.area());

    let r = app.selected().cloned().unwrap_or(RowItem {
        instance_id: String::new(),
        instance_name: "".into(),
        name: "".into(),
        kind: String::new(),
        update: String::new(),
        runtime: String::new(),
        pod: String::new(),
        url: String::new(),
        route_port: None,
    });

    let frame = app.spinner_frame();
    let banner = Line::from(vec![
        Span::styled(
            " ✦ Detail ",
            Style::default()
                .fg(Color::Rgb(20, 22, 34))
                .bg(theme::ACCENT)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("  {} / {} ", r.instance_name, r.name),
            Style::default().fg(theme::MUTED).bg(theme::HEADER_BG),
        ),
    ]);
    f.render_widget(
        Paragraph::new(banner).style(Style::default().bg(theme::HEADER_BG)),
        chunks[0],
    );

    let field = |k: &'static str| Span::styled(k, Style::default().fg(theme::MUTED));
    let info = vec![
        Line::from(vec![field("instance  "), Span::raw(r.instance_name.clone())]),
        Line::from(vec![field("resource  "), Span::styled(r.name.clone(), bold())]),
        Line::from(vec![field("type      "), Span::raw(r.kind.clone())]),
        Line::from({
            let mut v = vec![field("update    ")];
            v.extend(status_cell(&r.update, frame).spans);
            v
        }),
        Line::from({
            let mut v = vec![field("runtime   ")];
            v.extend(status_cell(&r.runtime, frame).spans);
            v
        }),
        Line::from(vec![field("port      "), Span::raw(r.route_port.map(|p| p.to_string()).unwrap_or_default())]),
        Line::from(vec![field("pod       "), Span::raw(r.pod.clone())]),
        Line::from(vec![field("url       "), Span::styled(r.url.clone(), Style::default().fg(theme::URL).add_modifier(Modifier::UNDERLINED))]),
    ];
    f.render_widget(
        Paragraph::new(info).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme::MUTED))
                .title(Span::styled(" Status ", Style::default().fg(theme::ACCENT).add_modifier(Modifier::BOLD))),
        ),
        chunks[1],
    );

    let h = chunks[2].height.saturating_sub(2) as usize;
    f.render_widget(
        Paragraph::new(log_body(&app.logs, h, app.log_scroll)).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme::MUTED))
                .title(Span::styled(" Logs ", Style::default().fg(theme::ACCENT))),
        ),
        chunks[2],
    );

    f.render_widget(
        Paragraph::new(key_hints(&[
            ("Esc/↵", "back"),
            ("l", "full logs"),
            ("o", "open"),
            ("t", "trigger"),
            ("R", "restart"),
            ("p", "port"),
            ("PgUp/Dn", "scroll"),
            ("q", "quit"),
        ])),
        chunks[3],
    );
}

fn bold() -> Style {
    Style::default().add_modifier(Modifier::BOLD)
}

#[cfg(test)]
mod tests {
    use super::{filter_log_lines, hostname_from_url, parse_port, route_port_for_url, sanitize};
    use crate::daemon::protocol::{DashboardState, RouteInfo};

    #[test]
    fn sanitize_strips_escapes_and_control_but_keeps_emoji() {
        // ANSI SGR color codes are removed, visible text kept.
        assert_eq!(sanitize("\u{1b}[32mready\u{1b}[0m"), "ready");
        // Cursor-move CSI sequences are removed.
        assert_eq!(sanitize("a\u{1b}[2Kb"), "ab");
        // OSC sequences (e.g. window title) terminated by BEL are removed.
        assert_eq!(sanitize("\u{1b}]0;title\u{7}done"), "done");
        // Carriage returns and other control bytes are dropped; tabs expand.
        assert_eq!(sanitize("a\rb\tc\u{0}"), "ab    c");
        // Emoji and other printable Unicode survive intact.
        assert_eq!(sanitize("\u{1b}[33m\u{2728} built \u{1f680}"), "\u{2728} built \u{1f680}");
        // A lone trailing ESC doesn't panic and is dropped.
        assert_eq!(sanitize("hi\u{1b}"), "hi");
    }

    #[test]
    fn log_filter_regex_substring_and_empty() {
        let logs = vec![
            "GET /healthz 200".to_string(),
            "ERROR: connection refused".to_string(),
            "GET /users 500".to_string(),
        ];
        // empty => all lines
        assert_eq!(filter_log_lines(&logs, "").len(), 3);
        // case-insensitive substring / regex
        assert_eq!(filter_log_lines(&logs, "error"), vec!["ERROR: connection refused"]);
        // regex: lines with a 5xx status
        assert_eq!(filter_log_lines(&logs, r"\b5\d\d\b"), vec!["GET /users 500"]);
        // invalid regex falls back to substring (no panic)
        assert_eq!(filter_log_lines(&logs, "GET [").len(), 0);
    }

    #[test]
    fn parses_valid_backend_ports() {
        assert_eq!(parse_port("1"), Some(1));
        assert_eq!(parse_port("65535"), Some(65535));
        assert_eq!(parse_port("0"), None);
        assert_eq!(parse_port("65536"), None);
        assert_eq!(parse_port("abc"), None);
    }

    #[test]
    fn extracts_hostname_from_named_url() {
        assert_eq!(
            hostname_from_url("http://web-app.localhost:1360/path"),
            Some("web-app.localhost".to_string())
        );
        assert_eq!(
            hostname_from_url("https://api.localhost"),
            Some("api.localhost".to_string())
        );
        assert_eq!(hostname_from_url(""), None);
    }

    #[test]
    fn finds_backend_port_for_selected_route() {
        let state = DashboardState {
            routes: vec![RouteInfo {
                hostname: "web.localhost".to_string(),
                port: 8080,
                instance: "inst".to_string(),
            }],
            ..Default::default()
        };

        assert_eq!(
            route_port_for_url(&state, "inst", Some("http://web.localhost:1360")),
            Some(8080)
        );
        assert_eq!(
            route_port_for_url(&state, "other", Some("http://web.localhost:1360")),
            None
        );
    }
}

/// Full-screen log view for the selected resource, with a regex filter.
fn draw_logs_fullscreen(f: &mut Frame, app: &mut App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // title
            Constraint::Min(3),    // logs
            Constraint::Length(1), // footer
        ])
        .split(f.area());

    let sel = app
        .selected()
        .map(|r| format!("{} / {}", r.instance_name, r.name))
        .unwrap_or_else(|| "".into());
    let logs = app.filtered_logs();
    let matched = if app.log_filter.is_empty() {
        format!("{} lines", logs.len())
    } else {
        format!("{} matching /{}", logs.len(), app.log_filter)
    };
    let banner = Line::from(vec![
        Span::styled(
            " ✦ Logs ",
            Style::default()
                .fg(Color::Rgb(20, 22, 34))
                .bg(theme::ACCENT)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("  {sel} · {matched} "),
            Style::default().fg(theme::MUTED).bg(theme::HEADER_BG),
        ),
    ]);
    f.render_widget(
        Paragraph::new(banner).style(Style::default().bg(theme::HEADER_BG)),
        chunks[0],
    );

    let h = chunks[1].height.saturating_sub(2) as usize;
    f.render_widget(
        Paragraph::new(log_body(&logs, h, app.log_scroll)).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme::MUTED)),
        ),
        chunks[1],
    );

    let footer: Line = if app.mode == Mode::LogsFilter {
        prompt_line("filter", &app.log_filter, "Enter apply · Esc clear")
    } else {
        key_hints(&[
            ("/", "filter"),
            ("PgUp/Dn", "scroll"),
            ("G", "tail"),
            ("o", "open"),
            ("l/Esc", "back"),
            ("q", "quit"),
        ])
    };
    f.render_widget(Paragraph::new(footer), chunks[2]);
}