darpan 0.2.2

Linux developer service monitoring utility with auto-detection, real-time health checks, and interactive TUI for databases, APIs, Docker containers, and more
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
// Complete TUI implementation with proper layout and log viewing
// This will replace the current tui.rs

use crate::core::engine::CoreEngine;
use crate::health::NetworkMonitor;
use crate::logs::{export, LogBuffer, LogStreamManager};
use crate::models::LogEntry;
use anyhow::Result;
use chrono::Local;
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, Paragraph, Row, Table, TableState, Wrap},
    Frame, Terminal,
};
use std::collections::VecDeque;
use std::io;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tracing::info;

pub struct TuiInterface {
    terminal: Terminal<CrosstermBackend<io::Stdout>>,
    table_state: TableState,
    last_refresh: Instant,
    log_messages: VecDeque<String>,
    view_mode: ViewMode,
    log_stream_manager: LogStreamManager,
    service_log_buffer: LogBuffer,
    log_receiver: Option<mpsc::UnboundedReceiver<LogEntry>>,
    log_paused: bool,
    log_scroll_offset: usize,
    export_message: Option<String>,
    search_mode: bool,
    search_query: String,
    log_level_filter: Option<crate::models::LogLevel>,
}

#[derive(PartialEq, Clone)]
enum ViewMode {
    Dashboard,
    ServiceDetails,
    ServiceLogs,
}

impl TuiInterface {
    pub fn new() -> Result<Self> {
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
        let backend = CrosstermBackend::new(stdout);
        let terminal = Terminal::new(backend)?;

        Ok(Self {
            terminal,
            table_state: TableState::default(),
            last_refresh: Instant::now(),
            log_messages: VecDeque::with_capacity(100),
            view_mode: ViewMode::Dashboard,
            log_stream_manager: LogStreamManager::new(),
            service_log_buffer: LogBuffer::new(100),
            log_receiver: None,
            log_paused: false,
            log_scroll_offset: 0,
            export_message: None,
            search_mode: false,
            search_query: String::new(),
            log_level_filter: None,
        })
    }

    pub async fn run(&mut self, engine: &mut CoreEngine) -> Result<()> {
        // Initial refresh
        self.add_log("Starting Darpan...".to_string());
        engine.refresh().await?;
        self.add_log(format!("Detected {} services", engine.get_registry().count()));
        self.table_state.select(Some(0));

        loop {
            // Auto-refresh every 5 seconds (except in log view)
            if self.view_mode != ViewMode::ServiceLogs && self.last_refresh.elapsed() > Duration::from_secs(5) {
                self.add_log("Refreshing health checks...".to_string());
                engine.check_health().await?;
                self.last_refresh = Instant::now();
                
                let registry = engine.get_registry();
                let healthy = registry.all_services().iter().filter(|s| s.is_healthy()).count();
                let total = registry.count();
                self.add_log(format!("Health check: {}/{} healthy", healthy, total));
            }

            // Process incoming log entries
            if let Some(ref mut rx) = self.log_receiver {
                while let Ok(entry) = rx.try_recv() {
                    if !self.log_paused {
                        self.service_log_buffer.push(entry);
                        // Auto-scroll to bottom when not paused
                        self.log_scroll_offset = 0;
                    }
                }
            }

            let view_mode = self.view_mode.clone();
            let table_state = self.table_state.clone();
            let log_messages = self.log_messages.clone();
            let last_refresh = self.last_refresh;
            let service_log_buffer = &self.service_log_buffer;
            let log_paused = self.log_paused;
            let log_scroll_offset = self.log_scroll_offset;
            let export_message = self.export_message.clone();
            let search_mode = self.search_mode;
            let search_query = self.search_query.clone();
            let log_level_filter = self.log_level_filter;
            
            self.terminal.draw(|f| {
                let size = f.size();
                match view_mode {
                    ViewMode::ServiceLogs => {
                        Self::render_service_logs_static(f, engine, size, &table_state, service_log_buffer, log_paused, log_scroll_offset, export_message.as_deref(), search_mode, &search_query, log_level_filter);
                    }
                    ViewMode::ServiceDetails => {
                        Self::render_service_details_static(f, engine, size, &table_state, &log_messages);
                    }
                    ViewMode::Dashboard => {
                        Self::render_dashboard_static(f, engine, size, &table_state, &log_messages, last_refresh);
                    }
                }
            })?;
            
            // Clear export message after showing it
            if self.export_message.is_some() {
                tokio::time::sleep(Duration::from_secs(3)).await;
                self.export_message = None;
            }

            // Handle events
            if event::poll(Duration::from_millis(100))? {
                if let Event::Key(key) = event::read()? {
                    // Special handling for search mode
                    if self.search_mode && self.view_mode == ViewMode::ServiceLogs {
                        match key.code {
                            KeyCode::Enter => {
                                // Exit search mode and apply search
                                self.search_mode = false;
                            }
                            KeyCode::Esc => {
                                // Cancel search
                                self.search_mode = false;
                                self.search_query.clear();
                            }
                            KeyCode::Backspace => {
                                self.search_query.pop();
                            }
                            KeyCode::Char(c) => {
                                self.search_query.push(c);
                            }
                            _ => {}
                        }
                        continue;
                    }

                    match key.code {
                        KeyCode::Char('q') => {
                            match self.view_mode {
                                ViewMode::ServiceLogs => {
                                    // Stop log streaming
                                    self.log_receiver = None;
                                    self.service_log_buffer.clear();
                                    self.log_paused = false;
                                    self.log_scroll_offset = 0;
                                    self.view_mode = ViewMode::ServiceDetails;
                                }
                                ViewMode::ServiceDetails => {
                                    self.view_mode = ViewMode::Dashboard;
                                }
                                ViewMode::Dashboard => {
                                    break;
                                }
                            }
                        }
                        KeyCode::Esc => {
                            match self.view_mode {
                                ViewMode::ServiceLogs => {
                                    self.log_receiver = None;
                                    self.service_log_buffer.clear();
                                    self.log_paused = false;
                                    self.log_scroll_offset = 0;
                                    self.view_mode = ViewMode::ServiceDetails;
                                }
                                ViewMode::ServiceDetails => {
                                    self.view_mode = ViewMode::Dashboard;
                                }
                                ViewMode::Dashboard => {
                                    break;
                                }
                            }
                        }
                        KeyCode::Char('r') => {
                            if self.view_mode != ViewMode::ServiceLogs {
                                self.add_log("Manual refresh requested".to_string());
                                engine.refresh().await?;
                                self.last_refresh = Instant::now();
                                self.add_log("Refresh complete".to_string());
                            }
                        }
                        KeyCode::Char('l') | KeyCode::Char('L') => {
                            // Enter log view
                            if self.view_mode == ViewMode::Dashboard || self.view_mode == ViewMode::ServiceDetails {
                                if let Some(selected) = self.table_state.selected() {
                                    let services = engine.get_registry().all_services();
                                    if let Some(service) = services.get(selected) {
                                        self.add_log(format!("Starting log stream for: {}", service.name));
                                        
                                        // Start log streaming
                                        match self.log_stream_manager.start_streaming(service).await {
                                            Ok(rx) => {
                                                self.log_receiver = Some(rx);
                                                self.service_log_buffer.clear();
                                                self.log_paused = false;
                                                self.log_scroll_offset = 0;
                                                self.view_mode = ViewMode::ServiceLogs;
                                            }
                                            Err(e) => {
                                                self.add_log(format!("Failed to start log streaming: {}", e));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        KeyCode::Char(' ') => {
                            // Toggle pause in log view
                            if self.view_mode == ViewMode::ServiceLogs {
                                self.log_paused = !self.log_paused;
                            }
                        }
                        KeyCode::Char('e') | KeyCode::Char('E') => {
                            // Export logs
                            if self.view_mode == ViewMode::ServiceLogs {
                                if let Some(selected) = self.table_state.selected() {
                                    let services = engine.get_registry().all_services();
                                    if let Some(service) = services.get(selected) {
                                        match export::export_logs(service, &self.service_log_buffer).await {
                                            Ok(path) => {
                                                self.export_message = Some(format!("Exported to: {:?}", path));
                                                info!("Logs exported to: {:?}", path);
                                            }
                                            Err(e) => {
                                                self.export_message = Some(format!("Export failed: {}", e));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        KeyCode::Down | KeyCode::Char('j') => {
                            if self.view_mode == ViewMode::ServiceLogs {
                                // Scroll down in logs
                                if self.log_scroll_offset > 0 {
                                    self.log_scroll_offset -= 1;
                                }
                            } else {
                                self.next(engine.get_registry().count());
                            }
                        }
                        KeyCode::Up | KeyCode::Char('k') => {
                            if self.view_mode == ViewMode::ServiceLogs {
                                // Scroll up in logs
                                if self.log_scroll_offset < self.service_log_buffer.len().saturating_sub(1) {
                                    self.log_scroll_offset += 1;
                                }
                            } else {
                                self.previous();
                            }
                        }
                        KeyCode::Enter => {
                            if self.view_mode == ViewMode::Dashboard {
                                self.view_mode = ViewMode::ServiceDetails;
                                if let Some(selected) = self.table_state.selected() {
                                    let services = engine.get_registry().all_services();
                                    if let Some(service) = services.get(selected) {
                                        self.add_log(format!("Viewing details: {}", service.name));
                                    }
                                }
                            }
                        }
                        KeyCode::Char('/') => {
                            // Enter search mode in log view
                            if self.view_mode == ViewMode::ServiceLogs {
                                self.search_mode = true;
                                self.search_query.clear();
                            }
                        }
                        KeyCode::Char('1') => {
                            // Filter by ERROR level
                            if self.view_mode == ViewMode::ServiceLogs {
                                self.log_level_filter = Some(crate::models::LogLevel::Error);
                            }
                        }
                        KeyCode::Char('2') => {
                            // Filter by WARN level
                            if self.view_mode == ViewMode::ServiceLogs {
                                self.log_level_filter = Some(crate::models::LogLevel::Warn);
                            }
                        }
                        KeyCode::Char('3') => {
                            // Filter by INFO level
                            if self.view_mode == ViewMode::ServiceLogs {
                                self.log_level_filter = Some(crate::models::LogLevel::Info);
                            }
                        }
                        KeyCode::Char('4') => {
                            // Filter by DEBUG level
                            if self.view_mode == ViewMode::ServiceLogs {
                                self.log_level_filter = Some(crate::models::LogLevel::Debug);
                            }
                        }
                        KeyCode::Char('0') => {
                            // Clear filter
                            if self.view_mode == ViewMode::ServiceLogs {
                                self.log_level_filter = None;
                            }
                        }
                        _ => {}
                    }
                }
            }
        }

        Ok(())
    }

    fn add_log(&mut self, message: String) {
        let timestamp = Local::now().format("%H:%M:%S");
        self.log_messages.push_back(format!("[{}] {}", timestamp, message));
        if self.log_messages.len() > 100 {
            self.log_messages.pop_front();
        }
    }

    fn render_dashboard_static(f: &mut Frame, engine: &CoreEngine, size: Rect, table_state: &TableState, log_messages: &VecDeque<String>, last_refresh: Instant) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3),      // Header
                Constraint::Percentage(45), // Services table
                Constraint::Percentage(25), // Details panel  
                Constraint::Percentage(25), // Logs
                Constraint::Length(2),      // Footer
            ])
            .split(size);

        // Header
        let project_name = engine
            .project_path()
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown");

        let header_text = vec![
            Line::from(vec![
                Span::styled(" ╭───╮ ", Style::default().fg(Color::Yellow)),
                Span::styled("DARPAN", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)),
                Span::styled(" - ", Style::default().fg(Color::White)),
                Span::styled(project_name, Style::default().fg(Color::Green)),
                Span::styled(" | ", Style::default().fg(Color::DarkGray)),
                Span::styled("Live Monitor", Style::default().fg(Color::Magenta)),
                Span::styled(" | ", Style::default().fg(Color::DarkGray)),
                Span::styled("chiraglabs", Style::default().fg(Color::Blue).add_modifier(Modifier::ITALIC)),
            ]),
            Line::from(vec![
                Span::styled(" │︵⌄︵│ ", Style::default().fg(Color::Yellow)),
                Span::styled("Linux Service Monitor", Style::default().fg(Color::DarkGray)),
            ]),
        ];

        let header = Paragraph::new(header_text)
            .alignment(Alignment::Center)
            .block(Block::default().borders(Borders::ALL));

        f.render_widget(header, chunks[0]);

        // Services table
        let registry = engine.get_registry();
        let services = registry.all_services();

        let rows: Vec<Row> = services
            .iter()
            .map(|service| {
                let health = service.health_status.as_ref();
                let status_symbol = health.map(|h| h.status.symbol()).unwrap_or("?");

                let status_color = health
                    .map(|h| match h.status {
                        crate::models::HealthStatus::Healthy => Color::Green,
                        crate::models::HealthStatus::Degraded => Color::Yellow,
                        crate::models::HealthStatus::Unhealthy => Color::Red,
                        crate::models::HealthStatus::NotRunning => Color::Red,
                        crate::models::HealthStatus::Unknown => Color::Gray,
                    })
                    .unwrap_or(Color::Gray);

                let service_type_str = match &service.service_type {
                    crate::models::ServiceType::HttpServer => "HTTP",
                    crate::models::ServiceType::Database { .. } => "Database",
                    crate::models::ServiceType::MessageQueue { .. } => "Queue",
                    crate::models::ServiceType::Cache { .. } => "Cache",
                    crate::models::ServiceType::Search { .. } => "Search",
                    crate::models::ServiceType::DockerContainer => "Docker",
                    crate::models::ServiceType::Custom => "Custom",
                };

                let response = health
                    .map(|h| {
                        if h.response_time_ms > 0 {
                            format!("{}ms", h.response_time_ms)
                        } else {
                            "N/A".to_string()
                        }
                    })
                    .unwrap_or_else(|| "N/A".to_string());

                Row::new(vec![
                    Span::styled(status_symbol, Style::default().fg(status_color)),
                    Span::raw(&service.name),
                    Span::raw(service_type_str),
                    Span::raw(format!("{}:{}", service.host, service.port)),
                    Span::raw(response),
                ])
            })
            .collect();

        let table = Table::new(
            rows,
            [
                Constraint::Length(3),
                Constraint::Min(20),
                Constraint::Length(10),
                Constraint::Length(18),
                Constraint::Length(8),
            ],
        )
        .header(
            Row::new(vec!["", "NAME", "TYPE", "HOST:PORT", "RESP"])
                .style(Style::default().add_modifier(Modifier::BOLD))
                .bottom_margin(1),
        )
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" Services ({}) - Press Enter for details ", services.len())),
        )
        .highlight_style(Style::default().bg(Color::DarkGray).add_modifier(Modifier::BOLD))
        .highlight_symbol(">> ");

        let mut ts = table_state.clone();
        f.render_stateful_widget(table, chunks[1], &mut ts);

        // Details panel
        let selected = table_state.selected().unwrap_or(0);
        let details_text = if let Some(service) = services.get(selected) {
            let mut lines = vec![
                Line::from(vec![
                    Span::styled("Service: ", Style::default().add_modifier(Modifier::BOLD)),
                    Span::raw(&service.name),
                ]),
            ];

            if let Some(health) = &service.health_status {
                let (status_text, color) = match health.status {
                    crate::models::HealthStatus::Healthy => ("HEALTHY", Color::Green),
                    crate::models::HealthStatus::Degraded => ("DEGRADED", Color::Yellow),
                    crate::models::HealthStatus::Unhealthy => ("UNHEALTHY", Color::Red),
                    crate::models::HealthStatus::NotRunning => ("DOWN", Color::Red),
                    crate::models::HealthStatus::Unknown => ("UNKNOWN", Color::Gray),
                };

                lines.push(Line::from(vec![
                    Span::styled("Status: ", Style::default().add_modifier(Modifier::BOLD)),
                    Span::styled(status_text, Style::default().fg(color)),
                ]));

                if let Some(details) = &health.details {
                    lines.push(Line::from(vec![
                        Span::styled("Info: ", Style::default().add_modifier(Modifier::BOLD)),
                        Span::styled(details, Style::default().fg(Color::Yellow)),
                    ]));
                }
            }

            lines
        } else {
            vec![Line::from("No service selected")]
        };

        let details = Paragraph::new(details_text)
            .block(Block::default().borders(Borders::ALL).title(" Quick Info "))
            .wrap(Wrap { trim: true });

        f.render_widget(details, chunks[2]);

        // Logs panel
        let log_items: Vec<ListItem> = log_messages
            .iter()
            .rev()
            .take(chunks[3].height.saturating_sub(2) as usize)
            .rev()
            .map(|log| ListItem::new(log.as_str()))
            .collect();

        let logs = List::new(log_items)
            .block(Block::default().borders(Borders::ALL).title(" Live Logs "));

        f.render_widget(logs, chunks[3]);

        // Footer
        let seconds_ago = last_refresh.elapsed().as_secs();
        let footer = Paragraph::new(format!(
            " q: quit | r: refresh | ↑↓/jk: navigate | Enter: details | L: logs | Updated: {}s ago ",
            seconds_ago
        ))
        .style(Style::default().fg(Color::Gray));

        f.render_widget(footer, chunks[4]);
    }

    fn render_service_details_static(f: &mut Frame, engine: &CoreEngine, size: Rect, table_state: &TableState, log_messages: &VecDeque<String>) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3),      // Header
                Constraint::Percentage(70), // Service details
                Constraint::Percentage(25), // Logs
                Constraint::Length(2),      // Footer
            ])
            .split(size);

        // Header
        let header_text = vec![
            Line::from(vec![
                Span::styled(" ╭───╮ ", Style::default().fg(Color::Yellow)),
                Span::styled("Service Details", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)),
                Span::styled(" | ", Style::default().fg(Color::DarkGray)),
                Span::styled("chiraglabs", Style::default().fg(Color::Blue).add_modifier(Modifier::ITALIC)),
            ]),
        ];

        let header = Paragraph::new(header_text)
            .alignment(Alignment::Center)
            .block(Block::default().borders(Borders::ALL));

        f.render_widget(header, chunks[0]);

        // Service details
        let selected = table_state.selected().unwrap_or(0);
        let services = engine.get_registry().all_services();

        let details_text = if let Some(service) = services.get(selected) {
            let mut lines = vec![
                Line::from(vec![
                    Span::styled("Service Name: ", Style::default().add_modifier(Modifier::BOLD).fg(Color::Cyan)),
                    Span::raw(&service.name),
                ]),
                Line::from(""),
            ];

            if let Some(health) = &service.health_status {
                let (status_text, color) = match health.status {
                    crate::models::HealthStatus::Healthy => ("✓ HEALTHY", Color::Green),
                    crate::models::HealthStatus::Degraded => ("⚠ DEGRADED", Color::Yellow),
                    crate::models::HealthStatus::Unhealthy => ("✗ UNHEALTHY", Color::Red),
                    crate::models::HealthStatus::NotRunning => ("✗ DOWN", Color::Red),
                    crate::models::HealthStatus::Unknown => ("? UNKNOWN", Color::Gray),
                };

                lines.push(Line::from(vec![
                    Span::styled("Status: ", Style::default().add_modifier(Modifier::BOLD)),
                    Span::styled(status_text, Style::default().fg(color).add_modifier(Modifier::BOLD)),
                ]));
                lines.push(Line::from(""));

                lines.push(Line::from(vec![
                    Span::styled("Location: ", Style::default().add_modifier(Modifier::BOLD)),
                    Span::raw(format!("{}:{}", service.host, service.port)),
                ]));

                if let Some(pid) = service.pid {
                    lines.push(Line::from(vec![
                        Span::styled("Process ID: ", Style::default().add_modifier(Modifier::BOLD)),
                        Span::raw(format!("{}", pid)),
                    ]));
                }

                if let Some(cmd) = &service.command_line {
                    lines.push(Line::from(vec![
                        Span::styled("Command: ", Style::default().add_modifier(Modifier::BOLD)),
                        Span::raw(cmd),
                    ]));
                }

                lines.push(Line::from(""));

                if health.response_time_ms > 0 {
                    lines.push(Line::from(vec![
                        Span::styled("Response Time: ", Style::default().add_modifier(Modifier::BOLD)),
                        Span::raw(format!("{}ms", health.response_time_ms)),
                    ]));
                }

                if let Some(details) = &health.details {
                    lines.push(Line::from(""));
                    lines.push(Line::from(vec![
                        Span::styled("Details: ", Style::default().add_modifier(Modifier::BOLD).fg(Color::Yellow)),
                    ]));
                    lines.push(Line::from(Span::styled(details, Style::default().fg(Color::Yellow))));
                }

                if let Some(suggestion) = &health.suggestion {
                    lines.push(Line::from(""));
                    lines.push(Line::from(vec![
                        Span::styled("Suggestion: ", Style::default().add_modifier(Modifier::BOLD).fg(Color::Green)),
                    ]));
                    lines.push(Line::from(Span::styled(suggestion, Style::default().fg(Color::Cyan))));
                }

                lines.push(Line::from(""));
                lines.push(Line::from(vec![
                    Span::styled("Last Checked: ", Style::default().add_modifier(Modifier::BOLD)),
                    Span::raw(health.last_checked.format("%H:%M:%S").to_string()),
                ]));

                // Network activity monitoring
                lines.push(Line::from(""));
                lines.push(Line::from(vec![
                    Span::styled("═══ Network Activity ═══", Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)),
                ]));

                // Check if port is listening
                if NetworkMonitor::is_port_listening(service.port) {
                    lines.push(Line::from(vec![
                        Span::styled("Port Status: ", Style::default().add_modifier(Modifier::BOLD)),
                        Span::styled("LISTENING ", Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)),
                        Span::styled("", Style::default().fg(Color::Green)),
                    ]));
                } else {
                    lines.push(Line::from(vec![
                        Span::styled("Port Status: ", Style::default().add_modifier(Modifier::BOLD)),
                        Span::styled("NOT LISTENING ", Style::default().fg(Color::Red)),
                        Span::styled("", Style::default().fg(Color::Red)),
                    ]));
                }

                // Get active connections
                if let Some(conn_count) = NetworkMonitor::get_active_connections(service) {
                    let conn_style = if conn_count > 0 {
                        Style::default().fg(Color::Green)
                    } else {
                        Style::default().fg(Color::Yellow)
                    };
                    lines.push(Line::from(vec![
                        Span::styled("Active Connections: ", Style::default().add_modifier(Modifier::BOLD)),
                        Span::styled(conn_count.to_string(), conn_style.add_modifier(Modifier::BOLD)),
                        if conn_count > 0 {
                            Span::styled(" (traffic detected)", Style::default().fg(Color::Green))
                        } else {
                            Span::styled(" (idle)", Style::default().fg(Color::DarkGray))
                        },
                    ]));
                }

                // Get process network stats if we have a PID
                if let Some(pid) = service.pid {
                    if let Some(stats) = NetworkMonitor::get_process_stats(pid) {
                        lines.push(Line::from(vec![
                            Span::styled("Process Connections: ", Style::default().add_modifier(Modifier::BOLD)),
                            Span::raw(format!("{} established, {} listening", 
                                stats.established_connections, 
                                stats.listening_sockets)),
                        ]));
                    }
                }
            }

            lines
        } else {
            vec![Line::from("No service selected")]
        };

        let details = Paragraph::new(details_text)
            .block(Block::default().borders(Borders::ALL).title(" Detailed Information "))
            .wrap(Wrap { trim: true });

        f.render_widget(details, chunks[1]);

        // Internal logs panel (Darpan activity)
        let log_items: Vec<ListItem> = log_messages
            .iter()
            .rev()
            .take(chunks[2].height.saturating_sub(2) as usize)
            .rev()
            .map(|log| ListItem::new(log.as_str()))
            .collect();

        let logs = List::new(log_items)
            .block(Block::default()
                .borders(Borders::ALL)
                .title(" Activity Monitor (Darpan internal) ")
                .title_style(Style::default().fg(Color::DarkGray))
                .border_style(Style::default().fg(Color::DarkGray)));

        f.render_widget(logs, chunks[2]);

        // Footer with emphasized service logs hint
        let footer = Paragraph::new(vec![
            Line::from(vec![
                Span::styled(" q/Esc: ", Style::default().fg(Color::Yellow)),
                Span::raw("back | "),
                Span::styled("L: ", Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)),
                Span::styled("VIEW SERVICE LOGS ", Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)),
                Span::raw("| "),
                Span::styled("r: ", Style::default().fg(Color::Yellow)),
                Span::raw("refresh"),
            ]),
        ])
            .style(Style::default());

        f.render_widget(footer, chunks[3]);
    }

    fn render_service_logs_static(
        f: &mut Frame,
        engine: &CoreEngine,
        size: Rect,
        table_state: &TableState,
        log_buffer: &LogBuffer,
        is_paused: bool,
        scroll_offset: usize,
        export_message: Option<&str>,
        search_mode: bool,
        search_query: &str,
        log_level_filter: Option<crate::models::LogLevel>,
    ) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3),      // Header
                Constraint::Length(2),      // Status bar
                Constraint::Min(10),        // Logs
                Constraint::Length(3),      // Controls + export message
            ])
            .split(size);

        // Header
        let selected = table_state.selected().unwrap_or(0);
        let services = engine.get_registry().all_services();
        let service_name = services.get(selected).map(|s| s.name.as_str()).unwrap_or("Unknown");

        let header_text = vec![
            Line::from(vec![
                Span::styled(" ╭───╮ ", Style::default().fg(Color::Yellow)),
                Span::styled("SERVICE LOGS: ", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)),
                Span::styled(service_name, Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)),
                Span::styled(" | ", Style::default().fg(Color::DarkGray)),
                Span::styled("chiraglabs", Style::default().fg(Color::Blue).add_modifier(Modifier::ITALIC)),
            ]),
        ];

        let header = Paragraph::new(header_text)
            .alignment(Alignment::Center)
            .block(Block::default().borders(Borders::ALL));

        f.render_widget(header, chunks[0]);

        // Status bar
        let log_source = if let Some(service) = services.get(selected) {
            if service.container_id.is_some() {
                "Docker"
            } else if service.systemd_unit.is_some() {
                "Systemd"
            } else if service.log_file_path.is_some() {
                "File"
            } else if service.pid.is_some() {
                "Process"
            } else {
                "Unknown"
            }
        } else {
            "Unknown"
        };

        let status_text = if is_paused {
            format!(
                " Source: {} | Lines: {} | ⏸ PAUSED (Space to resume) ",
                log_source,
                log_buffer.len()
            )
        } else {
            format!(
                " Source: {} | Lines: {} | ● LIVE (Space to pause) ",
                log_source,
                log_buffer.len()
            )
        };

        let status = Paragraph::new(status_text)
            .style(Style::default().fg(if is_paused { Color::Yellow } else { Color::Green }))
            .block(Block::default().borders(Borders::ALL));

        f.render_widget(status, chunks[1]);

        // Logs - with filtering and search
        let filtered_entries: Vec<&LogEntry> = log_buffer
            .entries()
            .iter()
            .filter(|entry| {
                // Apply log level filter
                if let Some(filter_level) = log_level_filter {
                    if entry.level != filter_level {
                        return false;
                    }
                }
                
                // Apply search filter
                if !search_query.is_empty() {
                    if !entry.message.to_lowercase().contains(&search_query.to_lowercase()) {
                        return false;
                    }
                }
                
                true
            })
            .collect();
        
        let log_entries: Vec<ListItem> = filtered_entries
            .iter()
            .rev()
            .skip(scroll_offset)
            .take(chunks[2].height.saturating_sub(2) as usize)
            .rev()
            .map(|entry| {
                let timestamp_str = entry.timestamp.format("%H:%M:%S%.3f").to_string();
                let level_str = entry.level.as_str();
                let level_color = entry.level.color();

                // Highlight search matches
                let message_spans = if !search_query.is_empty() {
                    highlight_search(&entry.message, search_query)
                } else {
                    vec![Span::raw(&entry.message)]
                };

                let mut line_spans = vec![
                    Span::styled(
                        format!("[{}] ", timestamp_str),
                        Style::default().fg(Color::DarkGray),
                    ),
                    Span::styled(
                        format!("{} ", level_str),
                        Style::default().fg(level_color).add_modifier(Modifier::BOLD),
                    ),
                ];
                line_spans.extend(message_spans);

                ListItem::new(Line::from(line_spans))
            })
            .collect();

        let logs_block = Block::default()
            .borders(Borders::ALL)
            .title(if is_paused {
                " Logs (Paused - use ↑↓ to scroll) "
            } else {
                " Logs (Live) "
            });

        let logs = List::new(log_entries).block(logs_block);

        f.render_widget(logs, chunks[2]);

        // Footer with controls, search/filter status, and export message
        let mut footer_lines = vec![];
        
        // Search/Filter status line
        if search_mode {
            footer_lines.push(Line::from(vec![
                Span::styled("🔍 Search: ", Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)),
                Span::styled(search_query, Style::default().fg(Color::White)),
                Span::styled(" (Enter to apply, Esc to cancel)", Style::default().fg(Color::DarkGray)),
            ]));
        } else if !search_query.is_empty() || log_level_filter.is_some() {
            let mut status_spans = vec![Span::styled("Active: ", Style::default().add_modifier(Modifier::BOLD))];
            
            if !search_query.is_empty() {
                status_spans.push(Span::styled(
                    format!("Search: '{}' ", search_query),
                    Style::default().fg(Color::Yellow),
                ));
            }
            
            if let Some(level) = log_level_filter {
                status_spans.push(Span::styled(
                    format!("Filter: {} ", level.as_str()),
                    Style::default().fg(level.color()),
                ));
            }
            
            status_spans.push(Span::styled("(0 to clear)", Style::default().fg(Color::DarkGray)));
            footer_lines.push(Line::from(status_spans));
        }
        
        // Controls line
        footer_lines.push(Line::from(vec![
            Span::styled("↑↓", Style::default().fg(Color::Cyan)),
            Span::raw(" Scroll | "),
            Span::styled("Space", Style::default().fg(Color::Yellow)),
            Span::raw(" Pause | "),
            Span::styled("/", Style::default().fg(Color::Magenta)),
            Span::raw(" Search | "),
            Span::styled("1-4", Style::default().fg(Color::Green)),
            Span::raw(" Filter Level | "),
            Span::styled("E", Style::default().fg(Color::Cyan)),
            Span::raw(" Export | "),
            Span::styled("q", Style::default().fg(Color::Red)),
            Span::raw(" Back"),
        ]));

        if let Some(msg) = export_message {
            footer_lines.push(Line::from(vec![
                Span::styled("📁 ", Style::default().fg(Color::Green)),
                Span::styled(msg, Style::default().fg(Color::Green).add_modifier(Modifier::ITALIC)),
            ]));
        }

        let footer = Paragraph::new(footer_lines)
            .style(Style::default().fg(Color::Gray))
            .block(Block::default().borders(Borders::ALL));

        f.render_widget(footer, chunks[3]);
    }

    fn next(&mut self, max: usize) {
        let i = match self.table_state.selected() {
            Some(i) => {
                if i >= max.saturating_sub(1) {
                    max.saturating_sub(1)
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.table_state.select(Some(i));
    }

    fn previous(&mut self) {
        let i = match self.table_state.selected() {
            Some(i) => {
                if i == 0 {
                    0
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.table_state.select(Some(i));
    }
}

/// Helper function to highlight search matches in text
fn highlight_search<'a>(text: &'a str, query: &str) -> Vec<Span<'a>> {
    if query.is_empty() {
        return vec![Span::raw(text)];
    }
    
    let lower_text = text.to_lowercase();
    let lower_query = query.to_lowercase();
    let mut spans = vec![];
    let mut last_end = 0;
    
    for (idx, _) in lower_text.match_indices(&lower_query) {
        // Add text before match
        if idx > last_end {
            spans.push(Span::raw(&text[last_end..idx]));
        }
        
        // Add highlighted match
        spans.push(Span::styled(
            &text[idx..idx + query.len()],
            Style::default().fg(Color::Black).bg(Color::Yellow).add_modifier(Modifier::BOLD),
        ));
        
        last_end = idx + query.len();
    }
    
    // Add remaining text
    if last_end < text.len() {
        spans.push(Span::raw(&text[last_end..]));
    }
    
    spans
}

impl Drop for TuiInterface {
    fn drop(&mut self) {
        // Restore terminal
        let _ = disable_raw_mode();
        let _ = execute!(
            self.terminal.backend_mut(),
            LeaveAlternateScreen,
            DisableMouseCapture
        );
        let _ = self.terminal.show_cursor();
    }
}