pitchfork-cli 2.6.0

Daemons with DX
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
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
use crate::Result;
use crate::daemon::Daemon;
use crate::daemon_id::DaemonId;
use crate::ipc::client::IpcClient;
use crate::pitchfork_toml::{
    CronRetrigger, PitchforkToml, PitchforkTomlAuto, PitchforkTomlCron, PitchforkTomlDaemon, Retry,
    namespace_from_path,
};
use crate::procs::{PROCS, ProcessStats};
use crate::settings::settings;
use fuzzy_matcher::FuzzyMatcher;
use fuzzy_matcher::skim::SkimMatcherV2;
use listeners::Listener;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fs;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;

/// Convert character index to byte index for UTF-8 strings
fn char_to_byte_index(s: &str, char_idx: usize) -> usize {
    s.char_indices()
        .nth(char_idx)
        .map(|(i, _)| i)
        .unwrap_or(s.len())
}

/// A snapshot of stats at a point in time
#[derive(Debug, Clone, Copy)]
pub struct StatsSnapshot {
    pub cpu_percent: f32,
    pub memory_bytes: u64,
    pub disk_read_bytes: u64,
    pub disk_write_bytes: u64,
}

impl From<&ProcessStats> for StatsSnapshot {
    fn from(stats: &ProcessStats) -> Self {
        Self {
            cpu_percent: stats.cpu_percent,
            memory_bytes: stats.memory_bytes,
            disk_read_bytes: stats.disk_read_bytes,
            disk_write_bytes: stats.disk_write_bytes,
        }
    }
}

/// Historical stats for a daemon
#[derive(Debug, Clone, Default)]
pub struct StatsHistory {
    pub samples: VecDeque<StatsSnapshot>,
}

impl StatsHistory {
    pub fn push(&mut self, snapshot: StatsSnapshot) {
        self.samples.push_back(snapshot);
        let max_history = settings().tui.stat_history.max(1) as usize;
        while self.samples.len() > max_history {
            self.samples.pop_front();
        }
    }

    pub fn cpu_values(&self) -> Vec<f32> {
        self.samples.iter().map(|s| s.cpu_percent).collect()
    }

    pub fn memory_values(&self) -> Vec<u64> {
        self.samples.iter().map(|s| s.memory_bytes).collect()
    }

    pub fn disk_read_values(&self) -> Vec<u64> {
        self.samples.iter().map(|s| s.disk_read_bytes).collect()
    }

    pub fn disk_write_values(&self) -> Vec<u64> {
        self.samples.iter().map(|s| s.disk_write_bytes).collect()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
    Dashboard,
    Logs,
    Network,
    Help,
    Confirm,
    Loading,
    Details,
    ConfigEditor,
    ConfigFileSelect,
}

/// Edit mode for the config editor
#[derive(Debug, Clone, PartialEq)]
pub enum EditMode {
    Create,
    Edit { original_id: String },
}

/// Form field value types
#[derive(Debug, Clone)]
pub enum FormFieldValue {
    Text(String),
    OptionalText(Option<String>),
    Number(u32),
    OptionalNumber(Option<u64>),
    OptionalPort(Option<u16>),
    #[allow(dead_code)]
    Boolean(bool),
    OptionalBoolean(Option<bool>),
    AutoBehavior(Vec<PitchforkTomlAuto>),
    Retrigger(CronRetrigger),
    StringList(Vec<String>),
}

/// A form field with metadata
#[derive(Debug, Clone)]
pub struct FormField {
    pub name: &'static str,
    pub label: &'static str,
    pub value: FormFieldValue,
    pub required: bool,
    #[allow(dead_code)]
    pub help_text: &'static str,
    pub error: Option<String>,
    pub editing: bool,
    pub cursor: usize,
}

impl FormField {
    fn text(name: &'static str, label: &'static str, help: &'static str, required: bool) -> Self {
        Self {
            name,
            label,
            value: FormFieldValue::Text(String::new()),
            required,
            help_text: help,
            error: None,
            editing: false,
            cursor: 0,
        }
    }

    fn optional_text(name: &'static str, label: &'static str, help: &'static str) -> Self {
        Self {
            name,
            label,
            value: FormFieldValue::OptionalText(None),
            required: false,
            help_text: help,
            error: None,
            editing: false,
            cursor: 0,
        }
    }

    fn number(name: &'static str, label: &'static str, help: &'static str, default: u32) -> Self {
        Self {
            name,
            label,
            value: FormFieldValue::Number(default),
            required: false,
            help_text: help,
            error: None,
            editing: false,
            cursor: 0,
        }
    }

    fn optional_number(name: &'static str, label: &'static str, help: &'static str) -> Self {
        Self {
            name,
            label,
            value: FormFieldValue::OptionalNumber(None),
            required: false,
            help_text: help,
            error: None,
            editing: false,
            cursor: 0,
        }
    }

    fn optional_port(name: &'static str, label: &'static str, help: &'static str) -> Self {
        Self {
            name,
            label,
            value: FormFieldValue::OptionalPort(None),
            required: false,
            help_text: help,
            error: None,
            editing: false,
            cursor: 0,
        }
    }

    fn optional_bool(name: &'static str, label: &'static str, help: &'static str) -> Self {
        Self {
            name,
            label,
            value: FormFieldValue::OptionalBoolean(None),
            required: false,
            help_text: help,
            error: None,
            editing: false,
            cursor: 0,
        }
    }

    fn auto_behavior(name: &'static str, label: &'static str, help: &'static str) -> Self {
        Self {
            name,
            label,
            value: FormFieldValue::AutoBehavior(vec![]),
            required: false,
            help_text: help,
            error: None,
            editing: false,
            cursor: 0,
        }
    }

    fn retrigger(name: &'static str, label: &'static str, help: &'static str) -> Self {
        Self {
            name,
            label,
            value: FormFieldValue::Retrigger(CronRetrigger::Finish),
            required: false,
            help_text: help,
            error: None,
            editing: false,
            cursor: 0,
        }
    }

    fn string_list(name: &'static str, label: &'static str, help: &'static str) -> Self {
        Self {
            name,
            label,
            value: FormFieldValue::StringList(vec![]),
            required: false,
            help_text: help,
            error: None,
            editing: false,
            cursor: 0,
        }
    }

    pub fn get_text(&self) -> String {
        match &self.value {
            FormFieldValue::Text(s) => s.clone(),
            FormFieldValue::OptionalText(Some(s)) => s.clone(),
            FormFieldValue::OptionalText(None) => String::new(),
            FormFieldValue::Number(n) => n.to_string(),
            FormFieldValue::OptionalNumber(Some(n)) => n.to_string(),
            FormFieldValue::OptionalNumber(None) => String::new(),
            FormFieldValue::OptionalPort(Some(p)) => p.to_string(),
            FormFieldValue::OptionalPort(None) => String::new(),
            FormFieldValue::StringList(v) => v.join(", "),
            _ => String::new(),
        }
    }

    pub fn set_text(&mut self, text: String) {
        match &mut self.value {
            FormFieldValue::Text(s) => *s = text,
            FormFieldValue::OptionalText(opt) => {
                *opt = if text.is_empty() { None } else { Some(text) };
            }
            FormFieldValue::Number(n) => {
                let trimmed = text.trim();
                if trimmed.is_empty() {
                    *n = 0;
                    self.error = None;
                } else {
                    match trimmed.parse() {
                        Ok(value) => {
                            *n = value;
                            self.error = None;
                        }
                        Err(_) => {
                            *n = 0;
                            self.error = Some("Invalid number".to_string());
                        }
                    }
                }
            }
            FormFieldValue::OptionalNumber(opt) => {
                *opt = text.parse().ok();
            }
            FormFieldValue::OptionalPort(opt) => {
                *opt = text.parse().ok();
            }
            FormFieldValue::StringList(v) => {
                *v = text
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
            }
            _ => {}
        }
    }

    pub fn is_text_editable(&self) -> bool {
        matches!(
            self.value,
            FormFieldValue::Text(_)
                | FormFieldValue::OptionalText(_)
                | FormFieldValue::Number(_)
                | FormFieldValue::OptionalNumber(_)
                | FormFieldValue::OptionalPort(_)
                | FormFieldValue::StringList(_)
        )
    }
}

/// State for the daemon config editor
#[derive(Debug, Clone)]
pub struct EditorState {
    pub mode: EditMode,
    pub daemon_id: String,
    pub daemon_id_editing: bool,
    pub daemon_id_cursor: usize,
    pub daemon_id_error: Option<String>,
    pub fields: Vec<FormField>,
    pub focused_field: usize,
    pub config_path: PathBuf,
    pub unsaved_changes: bool,
    #[allow(dead_code)]
    pub scroll_offset: usize,
    /// Preserved config field for ready_cmd (no form UI yet)
    preserved_ready_cmd: Option<String>,
}

impl EditorState {
    pub fn new_create(config_path: PathBuf) -> Self {
        Self {
            mode: EditMode::Create,
            daemon_id: String::new(),
            daemon_id_editing: true,
            daemon_id_cursor: 0,
            daemon_id_error: None,
            fields: Self::default_fields(),
            focused_field: 0,
            config_path,
            unsaved_changes: false,
            scroll_offset: 0,
            preserved_ready_cmd: None,
        }
    }

    pub fn new_edit(daemon_id: String, config: &PitchforkTomlDaemon, config_path: PathBuf) -> Self {
        Self {
            mode: EditMode::Edit {
                original_id: daemon_id.clone(),
            },
            daemon_id,
            daemon_id_editing: false,
            daemon_id_cursor: 0,
            daemon_id_error: None,
            fields: Self::fields_from_config(config),
            focused_field: 0,
            config_path,
            unsaved_changes: false,
            scroll_offset: 0,
            preserved_ready_cmd: config.ready_cmd.clone(),
        }
    }

    fn default_fields() -> Vec<FormField> {
        vec![
            FormField::text(
                "run",
                "Run Command",
                "Command to execute. Prepend 'exec' to avoid shell overhead.",
                true,
            ),
            FormField::optional_text(
                "dir",
                "Working Directory",
                "Working directory for the daemon. Relative to pitchfork.toml location.",
            ),
            FormField::string_list(
                "env",
                "Environment Variables",
                "Comma-separated KEY=VALUE pairs (e.g., NODE_ENV=dev, PORT=3000).",
            ),
            FormField::auto_behavior(
                "auto",
                "Auto Behavior",
                "Auto start/stop based on directory hooks.",
            ),
            FormField::number(
                "retry",
                "Retry Count",
                "Number of retry attempts on failure (0 = no retries).",
                0,
            ),
            FormField::optional_number(
                "ready_delay",
                "Ready Delay (ms)",
                "Milliseconds to wait before considering daemon ready.",
            ),
            FormField::optional_text(
                "ready_output",
                "Ready Output Pattern",
                "Regex pattern in stdout/stderr indicating readiness.",
            ),
            FormField::optional_text(
                "ready_http",
                "Ready HTTP URL",
                "HTTP URL to poll for readiness (expects 2xx).",
            ),
            FormField::optional_port(
                "ready_port",
                "Ready Port",
                "TCP port to check for readiness (1-65535).",
            ),
            FormField::optional_bool(
                "boot_start",
                "Start on Boot",
                "Automatically start this daemon on system boot.",
            ),
            FormField::string_list(
                "depends",
                "Dependencies",
                "Comma-separated daemon names that must start first.",
            ),
            FormField::string_list(
                "watch",
                "Watch Files",
                "Comma-separated glob patterns to watch for auto-restart.",
            ),
            FormField::optional_text(
                "cron_schedule",
                "Cron Schedule",
                "Cron expression (e.g., '*/5 * * * *' for every 5 minutes).",
            ),
            FormField::retrigger(
                "cron_retrigger",
                "Cron Retrigger",
                "Behavior when cron triggers while previous run is active.",
            ),
        ]
    }

    fn fields_from_config(config: &PitchforkTomlDaemon) -> Vec<FormField> {
        let mut fields = Self::default_fields();

        for field in &mut fields {
            match field.name {
                "run" => field.value = FormFieldValue::Text(config.run.clone()),
                "dir" => field.value = FormFieldValue::OptionalText(config.dir.clone()),
                "env" => {
                    field.value = FormFieldValue::StringList(
                        config
                            .env
                            .as_ref()
                            .map(|m| m.iter().map(|(k, v)| format!("{k}={v}")).collect())
                            .unwrap_or_default(),
                    );
                }
                "auto" => field.value = FormFieldValue::AutoBehavior(config.auto.clone()),
                "retry" => field.value = FormFieldValue::Number(config.retry.count()),
                "ready_delay" => field.value = FormFieldValue::OptionalNumber(config.ready_delay),
                "ready_output" => {
                    field.value = FormFieldValue::OptionalText(config.ready_output.clone())
                }
                "ready_http" => {
                    field.value = FormFieldValue::OptionalText(config.ready_http.clone())
                }
                "ready_port" => field.value = FormFieldValue::OptionalPort(config.ready_port),
                "boot_start" => field.value = FormFieldValue::OptionalBoolean(config.boot_start),
                "depends" => {
                    field.value = FormFieldValue::StringList(
                        config
                            .depends
                            .iter()
                            .map(|d: &DaemonId| d.qualified())
                            .collect(),
                    )
                }
                "watch" => field.value = FormFieldValue::StringList(config.watch.clone()),
                "cron_schedule" => {
                    field.value = FormFieldValue::OptionalText(
                        config.cron.as_ref().map(|c| c.schedule.clone()),
                    );
                }
                "cron_retrigger" => {
                    field.value = FormFieldValue::Retrigger(
                        config
                            .cron
                            .as_ref()
                            .map(|c| c.retrigger)
                            .unwrap_or(CronRetrigger::Finish),
                    );
                }
                _ => {}
            }
        }

        fields
    }

    pub fn to_daemon_config(&self) -> PitchforkTomlDaemon {
        let mut config = PitchforkTomlDaemon {
            ready_cmd: self.preserved_ready_cmd.clone(),
            path: Some(self.config_path.clone()),
            ..PitchforkTomlDaemon::default()
        };

        let mut cron_schedule: Option<String> = None;
        let mut cron_retrigger = CronRetrigger::Finish;

        for field in &self.fields {
            match (field.name, &field.value) {
                ("run", FormFieldValue::Text(s)) => config.run = s.clone(),
                ("dir", FormFieldValue::OptionalText(s)) => config.dir = s.clone(),
                ("env", FormFieldValue::StringList(v)) => {
                    if v.is_empty() {
                        config.env = None;
                    } else {
                        let mut map = indexmap::IndexMap::new();
                        for entry in v {
                            if let Some((k, val)) = entry.split_once('=') {
                                map.insert(k.trim().to_string(), val.trim().to_string());
                            }
                        }
                        config.env = if map.is_empty() { None } else { Some(map) };
                    }
                }
                ("auto", FormFieldValue::AutoBehavior(v)) => config.auto = v.clone(),
                ("retry", FormFieldValue::Number(n)) => config.retry = Retry(*n),
                ("ready_delay", FormFieldValue::OptionalNumber(n)) => config.ready_delay = *n,
                ("ready_output", FormFieldValue::OptionalText(s)) => {
                    config.ready_output = s.clone()
                }
                ("ready_http", FormFieldValue::OptionalText(s)) => config.ready_http = s.clone(),
                ("ready_port", FormFieldValue::OptionalPort(p)) => config.ready_port = *p,
                ("boot_start", FormFieldValue::OptionalBoolean(b)) => config.boot_start = *b,
                ("depends", FormFieldValue::StringList(v)) => {
                    config.depends = v.iter().filter_map(|s| DaemonId::parse(s).ok()).collect()
                }
                ("watch", FormFieldValue::StringList(v)) => config.watch = v.clone(),
                ("cron_schedule", FormFieldValue::OptionalText(s)) => cron_schedule = s.clone(),
                ("cron_retrigger", FormFieldValue::Retrigger(r)) => cron_retrigger = *r,
                _ => {}
            }
        }

        if let Some(schedule) = cron_schedule {
            config.cron = Some(PitchforkTomlCron {
                schedule,
                retrigger: cron_retrigger,
            });
        }

        config
    }

    pub fn next_field(&mut self) {
        // Stop editing current field if text editing
        if let Some(field) = self.fields.get_mut(self.focused_field) {
            field.editing = false;
        }

        // When leaving daemon_id editing, don't increment - just move to first form field
        if self.daemon_id_editing {
            self.daemon_id_editing = false;
            return;
        }

        if self.focused_field < self.fields.len() - 1 {
            self.focused_field += 1;
        }
    }

    pub fn prev_field(&mut self) {
        // Stop editing current field if text editing
        if let Some(field) = self.fields.get_mut(self.focused_field) {
            field.editing = false;
        }
        self.daemon_id_editing = false;

        if self.focused_field > 0 {
            self.focused_field -= 1;
        }
    }

    pub fn toggle_current_field(&mut self) {
        if let Some(field) = self.fields.get_mut(self.focused_field) {
            let toggled = match &mut field.value {
                FormFieldValue::Boolean(b) => {
                    *b = !*b;
                    true
                }
                FormFieldValue::OptionalBoolean(opt) => {
                    *opt = match opt {
                        None => Some(true),
                        Some(true) => Some(false),
                        Some(false) => None,
                    };
                    true
                }
                FormFieldValue::AutoBehavior(v) => {
                    // Cycle through: [] -> [Start] -> [Stop] -> [Start, Stop] -> []
                    let has_start = v.contains(&PitchforkTomlAuto::Start);
                    let has_stop = v.contains(&PitchforkTomlAuto::Stop);
                    *v = match (has_start, has_stop) {
                        (false, false) => vec![PitchforkTomlAuto::Start],
                        (true, false) => vec![PitchforkTomlAuto::Stop],
                        (false, true) => vec![PitchforkTomlAuto::Start, PitchforkTomlAuto::Stop],
                        (true, true) => vec![],
                    };
                    true
                }
                FormFieldValue::Retrigger(r) => {
                    *r = match r {
                        CronRetrigger::Finish => CronRetrigger::Always,
                        CronRetrigger::Always => CronRetrigger::Success,
                        CronRetrigger::Success => CronRetrigger::Fail,
                        CronRetrigger::Fail => CronRetrigger::Finish,
                    };
                    true
                }
                _ => false,
            };
            if toggled {
                self.unsaved_changes = true;
            }
        }
    }

    pub fn start_editing(&mut self) {
        if let Some(field) = self.fields.get_mut(self.focused_field) {
            if field.is_text_editable() {
                field.editing = true;
                field.cursor = field.get_text().chars().count();
            } else {
                // For non-text fields, toggle them
                self.toggle_current_field();
            }
        }
    }

    pub fn stop_editing(&mut self) {
        if let Some(field) = self.fields.get_mut(self.focused_field) {
            field.editing = false;
        }
        self.daemon_id_editing = false;
    }

    pub fn is_editing(&self) -> bool {
        self.daemon_id_editing
            || self
                .fields
                .get(self.focused_field)
                .map(|f| f.editing)
                .unwrap_or(false)
    }

    pub fn text_push(&mut self, c: char) {
        if self.daemon_id_editing {
            let byte_idx = char_to_byte_index(&self.daemon_id, self.daemon_id_cursor);
            self.daemon_id.insert(byte_idx, c);
            self.daemon_id_cursor += 1;
            self.unsaved_changes = true;
        } else if let Some(field) = self.fields.get_mut(self.focused_field)
            && field.editing
        {
            let mut text = field.get_text();
            let byte_idx = char_to_byte_index(&text, field.cursor);
            text.insert(byte_idx, c);
            field.cursor += 1;
            field.set_text(text);
            self.unsaved_changes = true;
        }
    }

    pub fn text_pop(&mut self) {
        if self.daemon_id_editing && self.daemon_id_cursor > 0 {
            self.daemon_id_cursor -= 1;
            let byte_idx = char_to_byte_index(&self.daemon_id, self.daemon_id_cursor);
            self.daemon_id.remove(byte_idx);
            self.unsaved_changes = true;
        } else if let Some(field) = self.fields.get_mut(self.focused_field)
            && field.editing
            && field.cursor > 0
        {
            let mut text = field.get_text();
            field.cursor -= 1;
            let byte_idx = char_to_byte_index(&text, field.cursor);
            text.remove(byte_idx);
            field.set_text(text);
            // For Number fields, sync cursor to end if value defaulted to "0"
            // This handles the case where backspacing to empty makes value 0
            if matches!(field.value, FormFieldValue::Number(_)) {
                field.cursor = field.get_text().chars().count();
            }
            self.unsaved_changes = true;
        }
    }

    pub fn validate(&mut self) -> bool {
        let mut valid = true;

        // Validate daemon ID
        self.daemon_id_error = None;
        if self.daemon_id.is_empty() {
            self.daemon_id_error = Some("Name is required".to_string());
            valid = false;
        } else if !self
            .daemon_id
            .chars()
            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
        {
            self.daemon_id_error =
                Some("Only letters, digits, hyphens, and underscores allowed".to_string());
            valid = false;
        }

        // Validate fields
        for field in &mut self.fields {
            field.error = None;

            match (field.name, &field.value) {
                ("run", FormFieldValue::Text(s)) if s.is_empty() => {
                    field.error = Some("Required".to_string());
                    valid = false;
                }
                ("ready_port", FormFieldValue::OptionalPort(Some(p))) if *p == 0 => {
                    field.error = Some("Port must be 1-65535".to_string());
                    valid = false;
                }
                ("ready_http", FormFieldValue::OptionalText(Some(url)))
                    if !(url.starts_with("http://") || url.starts_with("https://")) =>
                {
                    field.error = Some("Must start with http:// or https://".to_string());
                    valid = false;
                }
                _ => {}
            }
        }

        valid
    }
}

/// State for config file selection
#[derive(Debug, Clone)]
pub struct ConfigFileSelector {
    pub files: Vec<PathBuf>,
    pub selected: usize,
}

#[derive(Debug, Clone)]
pub enum PendingAction {
    Stop(DaemonId),
    Restart(DaemonId),
    Disable(DaemonId),
    // Batch operations
    BatchStop(Vec<DaemonId>),
    BatchRestart(Vec<DaemonId>),
    BatchDisable(Vec<DaemonId>),
    // Config editor actions
    DeleteDaemon { id: String, config_path: PathBuf },
    DiscardEditorChanges,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortColumn {
    #[default]
    Name,
    Status,
    Cpu,
    Memory,
    Uptime,
}

impl SortColumn {
    pub fn next(self) -> Self {
        match self {
            Self::Name => Self::Status,
            Self::Status => Self::Cpu,
            Self::Cpu => Self::Memory,
            Self::Memory => Self::Uptime,
            Self::Uptime => Self::Name,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortOrder {
    #[default]
    Ascending,
    Descending,
}

impl SortOrder {
    pub fn toggle(self) -> Self {
        match self {
            Self::Ascending => Self::Descending,
            Self::Descending => Self::Ascending,
        }
    }

    pub fn indicator(self) -> &'static str {
        match self {
            Self::Ascending => "↑",
            Self::Descending => "↓",
        }
    }
}

pub struct App {
    pub daemons: Vec<Daemon>,
    pub disabled: Vec<DaemonId>,
    pub selected: usize,
    pub view: View,
    pub prev_view: View,
    pub log_content: Vec<String>,
    pub log_daemon_id: Option<DaemonId>,
    pub log_scroll: usize,
    pub log_follow: bool, // Auto-scroll to bottom as new lines appear
    pub message: Option<String>,
    pub message_time: Option<Instant>,
    pub process_stats: HashMap<u32, ProcessStats>, // PID -> stats
    pub stats_history: HashMap<DaemonId, StatsHistory>, // daemon_id -> history
    pub pending_action: Option<PendingAction>,
    pub loading_text: Option<String>,
    pub search_query: String,
    pub search_active: bool,
    // Sorting
    pub sort_column: SortColumn,
    pub sort_order: SortOrder,
    // Log search
    pub log_search_query: String,
    pub log_search_active: bool,
    pub log_search_matches: Vec<usize>, // Line indices that match
    pub log_search_current: usize,      // Current match index
    // Details view daemon (now used for full-page details view from 'l' key)
    pub details_daemon_id: Option<DaemonId>,
    // Whether logs are expanded to fill the screen (hides charts)
    pub logs_expanded: bool,
    // Multi-select state
    pub multi_select: HashSet<DaemonId>,
    // Config-only daemons (defined in pitchfork.toml but not currently active)
    pub config_daemon_ids: HashSet<DaemonId>,
    // Whether to show config-only daemons in the list
    pub show_available: bool,
    // Config editor state
    pub editor_state: Option<EditorState>,
    // Config file selector state
    pub file_selector: Option<ConfigFileSelector>,
    // Network view state
    pub network_listeners: Vec<Listener>,
    pub network_search_query: String,
    pub network_search_active: bool,
    pub network_selected: usize,
    pub network_scroll_offset: usize,
    pub network_selected_pid: Option<u32>, // Store PID to ensure correct targeting
    pub network_visible_rows: usize,       // Cached visible row count for scroll calculations
}

impl App {
    pub fn new() -> Self {
        Self {
            daemons: Vec::new(),
            disabled: Vec::new(),
            selected: 0,
            view: View::Dashboard,
            prev_view: View::Dashboard,
            log_content: Vec::new(),
            log_daemon_id: None,
            log_scroll: 1,
            log_follow: true,
            message: None,
            message_time: None,
            process_stats: HashMap::new(),
            stats_history: HashMap::new(),
            pending_action: None,
            loading_text: None,
            search_query: String::new(),
            search_active: false,
            sort_column: SortColumn::default(),
            sort_order: SortOrder::default(),
            log_search_query: String::new(),
            log_search_active: false,
            log_search_matches: Vec::new(),
            log_search_current: 0,
            details_daemon_id: None,
            logs_expanded: false,
            multi_select: HashSet::new(),
            config_daemon_ids: HashSet::new(),
            show_available: true, // Show available daemons by default
            editor_state: None,
            file_selector: None,
            network_listeners: Vec::new(),
            network_search_query: String::new(),
            network_search_active: false,
            network_selected: 0,
            network_scroll_offset: 0,
            network_selected_pid: None,
            network_visible_rows: 20, // Default value, updated during draw
        }
    }

    pub fn confirm_action(&mut self, action: PendingAction) {
        self.pending_action = Some(action);
        self.prev_view = self.view;
        self.view = View::Confirm;
    }

    pub fn cancel_confirm(&mut self) {
        self.pending_action = None;
        self.view = self.prev_view;
    }

    pub fn take_pending_action(&mut self) -> Option<PendingAction> {
        self.view = self.prev_view;
        self.pending_action.take()
    }

    pub fn start_loading(&mut self, text: impl Into<String>) {
        self.prev_view = self.view;
        self.loading_text = Some(text.into());
        self.view = View::Loading;
    }

    pub fn stop_loading(&mut self) {
        self.loading_text = None;
        self.view = self.prev_view;
    }

    // Search functionality
    pub fn start_search(&mut self) {
        self.search_active = true;
    }

    pub fn end_search(&mut self) {
        self.search_active = false;
    }

    pub fn clear_search(&mut self) {
        self.search_query.clear();
        self.search_active = false;
        self.selected = 0;
    }

    pub fn search_push(&mut self, c: char) {
        self.search_query.push(c);
        // Reset selection when search changes
        self.selected = 0;
    }

    pub fn search_pop(&mut self) {
        self.search_query.pop();
        self.selected = 0;
    }

    pub fn filtered_daemons(&self) -> Vec<&Daemon> {
        let mut filtered: Vec<&Daemon> = if self.search_query.is_empty() {
            self.daemons.iter().collect()
        } else {
            // Use fuzzy matching with SkimMatcherV2
            let matcher = SkimMatcherV2::default();
            let mut scored: Vec<_> = self
                .daemons
                .iter()
                .filter_map(|d| {
                    matcher
                        .fuzzy_match(&d.id.qualified(), &self.search_query)
                        .map(|score| (d, score))
                })
                .collect();
            // Sort by score descending (best matches first)
            scored.sort_by_key(|s| std::cmp::Reverse(s.1));
            scored.into_iter().map(|(d, _)| d).collect()
        };

        // Sort the filtered list
        filtered.sort_by(|a, b| {
            let cmp = match self.sort_column {
                SortColumn::Name => {
                    a.id.to_string()
                        .to_lowercase()
                        .cmp(&b.id.to_string().to_lowercase())
                }
                SortColumn::Status => {
                    let status_order = |d: &Daemon| match &d.status {
                        crate::daemon_status::DaemonStatus::Running => 0,
                        crate::daemon_status::DaemonStatus::Waiting => 1,
                        crate::daemon_status::DaemonStatus::Stopping => 2,
                        crate::daemon_status::DaemonStatus::Stopped => 3,
                        crate::daemon_status::DaemonStatus::Errored(_) => 4,
                        crate::daemon_status::DaemonStatus::Failed(_) => 5,
                    };
                    status_order(a).cmp(&status_order(b))
                }
                SortColumn::Cpu => {
                    let cpu_a = a
                        .pid
                        .and_then(|p| self.get_stats(p))
                        .map(|s| s.cpu_percent)
                        .unwrap_or(0.0);
                    let cpu_b = b
                        .pid
                        .and_then(|p| self.get_stats(p))
                        .map(|s| s.cpu_percent)
                        .unwrap_or(0.0);
                    cpu_a
                        .partial_cmp(&cpu_b)
                        .unwrap_or(std::cmp::Ordering::Equal)
                }
                SortColumn::Memory => {
                    let mem_a = a
                        .pid
                        .and_then(|p| self.get_stats(p))
                        .map(|s| s.memory_bytes)
                        .unwrap_or(0);
                    let mem_b = b
                        .pid
                        .and_then(|p| self.get_stats(p))
                        .map(|s| s.memory_bytes)
                        .unwrap_or(0);
                    mem_a.cmp(&mem_b)
                }
                SortColumn::Uptime => {
                    let up_a = a
                        .pid
                        .and_then(|p| self.get_stats(p))
                        .map(|s| s.uptime_secs)
                        .unwrap_or(0);
                    let up_b = b
                        .pid
                        .and_then(|p| self.get_stats(p))
                        .map(|s| s.uptime_secs)
                        .unwrap_or(0);
                    up_a.cmp(&up_b)
                }
            };
            match self.sort_order {
                SortOrder::Ascending => cmp,
                SortOrder::Descending => cmp.reverse(),
            }
        });

        filtered
    }

    // Sorting
    pub fn cycle_sort(&mut self) {
        // If clicking the same column, toggle order; otherwise switch column
        self.sort_column = self.sort_column.next();
        self.selected = 0;
    }

    pub fn toggle_sort_order(&mut self) {
        self.sort_order = self.sort_order.toggle();
        self.selected = 0;
    }

    pub fn selected_daemon(&self) -> Option<&Daemon> {
        let filtered = self.filtered_daemons();
        filtered.get(self.selected).copied()
    }

    pub fn select_next(&mut self) {
        let count = self.filtered_daemons().len();
        if count > 0 {
            self.selected = (self.selected + 1) % count;
        }
    }

    pub fn select_prev(&mut self) {
        let count = self.filtered_daemons().len();
        if count > 0 {
            self.selected = self.selected.checked_sub(1).unwrap_or(count - 1);
        }
    }

    // Log follow mode
    pub fn toggle_log_follow(&mut self) {
        self.log_follow = !self.log_follow;
        if self.log_follow && !self.log_content.is_empty() {
            // Jump to bottom when enabling follow
            self.log_scroll = self.log_content.len();
        }
    }

    // Toggle logs expanded (hide/show charts)
    pub fn toggle_logs_expanded(&mut self) {
        self.logs_expanded = !self.logs_expanded;
    }

    // Multi-select methods
    pub fn toggle_select(&mut self) {
        if let Some(daemon) = self.selected_daemon() {
            let id = daemon.id.clone();
            if self.multi_select.contains(&id) {
                self.multi_select.remove(&id);
            } else {
                self.multi_select.insert(id);
            }
        }
    }

    pub fn select_all_visible(&mut self) {
        // Collect IDs first to avoid borrow conflict
        let ids: Vec<DaemonId> = self
            .filtered_daemons()
            .iter()
            .map(|d| d.id.clone())
            .collect();
        for id in ids {
            self.multi_select.insert(id);
        }
    }

    pub fn clear_selection(&mut self) {
        self.multi_select.clear();
    }

    pub fn is_selected(&self, daemon_id: &DaemonId) -> bool {
        self.multi_select.contains(daemon_id)
    }

    pub fn has_selection(&self) -> bool {
        !self.multi_select.is_empty()
    }

    pub fn selected_daemon_ids(&self) -> Vec<DaemonId> {
        self.multi_select.iter().cloned().collect()
    }

    pub fn set_message(&mut self, msg: impl Into<String>) {
        self.message = Some(msg.into());
        self.message_time = Some(Instant::now());
    }

    pub fn clear_stale_message(&mut self) {
        let duration = settings().tui_message_duration();
        if let Some(time) = self.message_time
            && time.elapsed() >= duration
        {
            self.message = None;
            self.message_time = None;
        }
    }

    pub fn get_stats(&self, pid: u32) -> Option<&ProcessStats> {
        self.process_stats.get(&pid)
    }

    fn refresh_process_stats(&mut self) {
        PROCS.refresh_processes();
        self.process_stats.clear();
        for daemon in &self.daemons {
            if let Some(pid) = daemon.pid
                && let Some(stats) = PROCS.get_stats(pid)
            {
                self.process_stats.insert(pid, stats);
                // Record history for this daemon
                let history = self.stats_history.entry(daemon.id.clone()).or_default();
                history.push(StatsSnapshot::from(&stats));
            }
        }
    }

    /// Get stats history for a daemon
    pub fn get_stats_history(&self, daemon_id: &DaemonId) -> Option<&StatsHistory> {
        self.stats_history.get(daemon_id)
    }

    pub async fn refresh(&mut self, client: &Arc<IpcClient>) -> Result<()> {
        use crate::daemon_list::get_all_daemons;

        // Get all daemons using shared logic (includes both active and available)
        let all_entries = get_all_daemons(client).await?;

        // Clear current lists
        self.daemons.clear();
        self.disabled.clear();
        self.config_daemon_ids.clear();

        // Populate daemons list based on show_available setting
        for entry in all_entries {
            // entry.id is already a DaemonId (entry.daemon.id)
            let daemon_id = entry.daemon.id.clone();

            // Track disabled daemons
            if entry.is_disabled {
                self.disabled.push(daemon_id.clone());
            }

            // Track config-only daemons
            if entry.is_available {
                self.config_daemon_ids.insert(daemon_id.clone());
            }

            // Add to daemons list if:
            // - It's an active daemon (not available), OR
            // - It's available and show_available is enabled
            if !entry.is_available || self.show_available {
                self.daemons.push(entry.daemon);
            }
        }

        // Refresh process stats (CPU, memory, uptime)
        self.refresh_process_stats();

        // Clear stale messages
        self.clear_stale_message();

        // Keep selection in bounds
        let total_count = self.total_daemon_count();
        if total_count > 0 && self.selected >= total_count {
            self.selected = total_count - 1;
        }

        // Refresh logs if viewing
        if self.view == View::Logs
            && let Some(id) = self.log_daemon_id.clone()
        {
            self.load_logs(&id);
        }

        Ok(())
    }

    /// Refresh network listeners data (for Network view)
    pub async fn refresh_network(&mut self) {
        // Use spawn_blocking since listeners::get_all() is a blocking operation
        let listeners: Vec<Listener> = tokio::task::spawn_blocking(|| {
            listeners::get_all()
                .map(|set| set.into_iter().collect::<Vec<_>>())
                .unwrap_or_default()
        })
        .await
        .unwrap_or_default();

        self.network_listeners = listeners;

        // Keep selection in bounds - first calculate the filtered count
        let filtered_count = self.filtered_network_listeners().len();

        // Update selection index
        if filtered_count > 0 && self.network_selected >= filtered_count {
            self.network_selected = filtered_count - 1;
        } else if filtered_count == 0 {
            self.network_selected = 0;
        }

        // Get a fresh filtered list and update the stored PID
        let selected_pid = self
            .filtered_network_listeners()
            .get(self.network_selected)
            .map(|l| l.process.pid);
        self.network_selected_pid = selected_pid;
    }

    /// Get filtered network listeners based on search query
    pub fn filtered_network_listeners(&self) -> Vec<&listeners::Listener> {
        if self.network_search_query.is_empty() {
            return self.network_listeners.iter().collect();
        }

        let matcher = SkimMatcherV2::default();
        let query = &self.network_search_query;

        self.network_listeners
            .iter()
            .filter(|listener| {
                // Search by process name, PID, or port
                let search_text = format!(
                    "{} {} {}",
                    listener.process.name,
                    listener.process.pid,
                    listener.socket.port()
                );
                matcher.fuzzy_match(&search_text, query).is_some()
            })
            .collect()
    }

    /// Toggle network search active state
    pub fn toggle_network_search(&mut self) {
        self.network_search_active = !self.network_search_active;
        if !self.network_search_active {
            self.network_search_query.clear();
        }
        // Reset scroll and selection when toggling search
        self.network_selected = 0;
        self.network_scroll_offset = 0;
        // Update PID for new selection
        let filtered = self.filtered_network_listeners();
        self.network_selected_pid = filtered.first().map(|l| l.process.pid);
    }

    /// Clear network search
    pub fn clear_network_search(&mut self) {
        self.network_search_query.clear();
        self.network_search_active = false;
        // Reset scroll and selection
        self.network_selected = 0;
        self.network_scroll_offset = 0;
        // Update PID for new selection
        let filtered = self.filtered_network_listeners();
        self.network_selected_pid = filtered.first().map(|l| l.process.pid);
    }

    /// Check if a daemon is from config only (not currently active)
    pub fn is_config_only(&self, daemon_id: &DaemonId) -> bool {
        self.config_daemon_ids.contains(daemon_id)
    }

    /// Toggle showing available daemons from config
    pub fn toggle_show_available(&mut self) {
        self.show_available = !self.show_available;
    }

    /// Get total daemon count (for selection bounds)
    fn total_daemon_count(&self) -> usize {
        self.filtered_daemons().len()
    }

    pub fn scroll_logs_down(&mut self) {
        let max_scroll = self.log_content.len();
        self.log_scroll = (self.log_scroll + 1).clamp(1, max_scroll);
    }

    pub fn scroll_logs_up(&mut self) {
        self.log_scroll = self.log_scroll.saturating_sub(1).max(1);
    }

    /// Scroll down by half page (Ctrl+D)
    pub fn scroll_logs_page_down(&mut self, visible_lines: usize) {
        let half_page = visible_lines / 2;
        let max_scroll = self.log_content.len();
        self.log_scroll = (self.log_scroll + half_page).clamp(1, max_scroll);
    }

    /// Scroll up by half page (Ctrl+U)
    pub fn scroll_logs_page_up(&mut self, visible_lines: usize) {
        let half_page = visible_lines / 2;
        self.log_scroll = self.log_scroll.saturating_sub(half_page).max(1);
    }

    // Log search
    pub fn start_log_search(&mut self) {
        self.log_search_active = true;
        self.log_search_query.clear();
        self.log_search_matches.clear();
        self.log_search_current = 0;
    }

    pub fn end_log_search(&mut self) {
        self.log_search_active = false;
    }

    pub fn clear_log_search(&mut self) {
        self.log_search_query.clear();
        self.log_search_active = false;
        self.log_search_matches.clear();
        self.log_search_current = 0;
    }

    pub fn log_search_push(&mut self, c: char) {
        self.log_search_query.push(c);
        self.update_log_search_matches();
    }

    pub fn log_search_pop(&mut self) {
        self.log_search_query.pop();
        self.update_log_search_matches();
    }

    fn update_log_search_matches(&mut self) {
        self.log_search_matches.clear();
        if !self.log_search_query.is_empty() {
            let query = self.log_search_query.to_lowercase();
            for (i, line) in self.log_content.iter().enumerate() {
                if line.to_lowercase().contains(&query) {
                    self.log_search_matches.push(i);
                }
            }
            // Jump to first match if any
            if !self.log_search_matches.is_empty() {
                self.log_search_current = 0;
                self.jump_to_log_match();
            }
        }
    }

    pub fn log_search_next(&mut self) {
        if !self.log_search_matches.is_empty() {
            self.log_search_current = (self.log_search_current + 1) % self.log_search_matches.len();
            self.jump_to_log_match();
        }
    }

    pub fn log_search_prev(&mut self) {
        if !self.log_search_matches.is_empty() {
            self.log_search_current = self
                .log_search_current
                .checked_sub(1)
                .unwrap_or(self.log_search_matches.len() - 1);
            self.jump_to_log_match();
        }
    }

    fn jump_to_log_match(&mut self) {
        if let Some(&line_idx) = self.log_search_matches.get(self.log_search_current) {
            // Scroll so the match is visible (center it if possible)
            let half_page = 10; // Assume ~20 visible lines
            self.log_scroll = line_idx.saturating_sub(half_page).max(1);
            self.log_follow = false;
        }
    }

    // Details view
    pub fn show_details(&mut self, daemon_id: &DaemonId) {
        self.details_daemon_id = Some(daemon_id.clone());
        self.prev_view = self.view;
        self.view = View::Details;
    }

    pub fn hide_details(&mut self) {
        self.details_daemon_id = None;
        self.view = View::Dashboard;
    }

    /// View daemon details (charts + logs)
    pub fn view_daemon_details(&mut self, daemon_id: &DaemonId) {
        self.log_daemon_id = Some(daemon_id.clone());
        self.logs_expanded = false; // Start with charts visible
        self.load_logs(daemon_id);
        self.view = View::Logs; // Logs view is now the full daemon details view
    }

    fn load_logs(&mut self, daemon_id: &DaemonId) {
        let log_path = daemon_id.log_path();
        let prev_len = self.log_content.len();

        self.log_content = if log_path.exists() {
            fs::read_to_string(&log_path)
                .unwrap_or_default()
                .lines()
                .map(String::from)
                .collect()
        } else {
            vec!["No logs available".to_string()]
        };

        // Auto-scroll to bottom when in follow mode
        if self.log_follow {
            self.log_scroll = self.log_content.len().max(1);
        } else if prev_len == 0 {
            // First load - start at bottom
            self.log_scroll = self.log_content.len().max(1);
        }
        // If not following and not first load, keep scroll position
    }

    pub fn show_help(&mut self) {
        self.view = View::Help;
    }

    pub fn back_to_dashboard(&mut self) {
        self.view = View::Dashboard;
        self.log_daemon_id = None;
        self.log_content.clear();
        self.log_scroll = 1;
    }

    /// Returns (total, running, stopped, errored, available)
    pub fn stats(&self) -> (usize, usize, usize, usize, usize) {
        let available = self.config_daemon_ids.len();
        let total = self.daemons.len();
        let running = self
            .daemons
            .iter()
            .filter(|d| d.status.is_running())
            .count();
        // Don't count config-only daemons as stopped
        let stopped = self
            .daemons
            .iter()
            .filter(|d| d.status.is_stopped() && !self.config_daemon_ids.contains(&d.id))
            .count();
        let errored = self
            .daemons
            .iter()
            .filter(|d| d.status.is_errored() || d.status.is_failed())
            .count();
        (total, running, stopped, errored, available)
    }

    pub fn is_disabled(&self, daemon_id: &DaemonId) -> bool {
        self.disabled.contains(daemon_id)
    }

    // Config editor methods

    /// Get list of available config file paths
    pub fn get_config_files(&self) -> Vec<PathBuf> {
        let mut files: Vec<PathBuf> = PitchforkToml::list_paths()
            .into_iter()
            .filter(|p| p.exists())
            .collect();

        // Add option to create in current directory if not present
        let cwd_config = crate::env::CWD.join("pitchfork.toml");
        if !files.contains(&cwd_config) {
            files.push(cwd_config);
        }

        files
    }

    /// Open file selector for creating a new daemon
    pub fn open_file_selector(&mut self) {
        let files = self.get_config_files();
        self.file_selector = Some(ConfigFileSelector { files, selected: 0 });
        self.view = View::ConfigFileSelect;
    }

    /// Open editor for a new daemon with the selected config file
    pub fn open_editor_create(&mut self, config_path: PathBuf) {
        self.editor_state = Some(EditorState::new_create(config_path));
        self.file_selector = None;
        self.view = View::ConfigEditor;
    }

    /// Open editor for an existing daemon
    pub fn open_editor_edit(&mut self, daemon_id: &DaemonId) {
        let config = match PitchforkToml::all_merged() {
            Ok(config) => config,
            Err(e) => {
                self.set_message(format!("Failed to load config: {e}"));
                return;
            }
        };
        if let Some(daemon_config) = config.daemons.get(daemon_id) {
            let config_path = daemon_config
                .path
                .clone()
                .unwrap_or_else(|| crate::env::CWD.join("pitchfork.toml"));
            self.editor_state = Some(EditorState::new_edit(
                daemon_id.to_string(),
                daemon_config,
                config_path,
            ));
            self.view = View::ConfigEditor;
        } else {
            self.set_message(format!("Daemon '{daemon_id}' not found in config"));
        }
    }

    /// Close the editor and return to dashboard
    pub fn close_editor(&mut self) {
        self.editor_state = None;
        self.file_selector = None;
        self.view = View::Dashboard;
    }

    /// Save the current editor state to config file.
    /// Returns Ok(true) if saved successfully, Ok(false) if validation/duplicate error (don't close editor).
    pub fn save_editor_config(&mut self) -> Result<bool> {
        let editor = self
            .editor_state
            .as_mut()
            .ok_or_else(|| miette::miette!("No editor state"))?;

        // Validate
        if !editor.validate() {
            self.set_message("Please fix validation errors before saving");
            return Ok(false);
        }

        // Build daemon config
        let daemon_config = editor.to_daemon_config();

        // Parse daemon ID from string
        let daemon_id = DaemonId::parse(&editor.daemon_id)
            .map_err(|e| miette::miette!("Invalid daemon ID: {}", e))?;

        // Read existing config (or create new)
        let mut config = PitchforkToml::read(&editor.config_path)?;

        // Check for duplicate daemon ID
        let is_duplicate = match &editor.mode {
            EditMode::Create => config.daemons.contains_key(&daemon_id),
            EditMode::Edit { original_id } => {
                // Only a duplicate if ID changed AND new ID already exists
                let original_daemon_id = DaemonId::parse(original_id)
                    .map_err(|e| miette::miette!("Invalid original daemon ID: {}", e))?;
                original_daemon_id != daemon_id && config.daemons.contains_key(&daemon_id)
            }
        };

        if is_duplicate {
            self.set_message(format!("A daemon named '{daemon_id}' already exists"));
            return Ok(false);
        }

        // Handle rename case
        if let EditMode::Edit { original_id } = &editor.mode {
            let original_daemon_id = DaemonId::parse(original_id)
                .map_err(|e| miette::miette!("Invalid original daemon ID: {}", e))?;
            if original_daemon_id != daemon_id {
                config.daemons.shift_remove(&original_daemon_id);
            }
        }

        // Insert/update daemon
        config.daemons.insert(daemon_id, daemon_config);

        // Write back
        config.write()?;

        editor.unsaved_changes = false;
        let daemon_id = editor.daemon_id.clone();
        self.set_message(format!("Saved daemon '{daemon_id}'"));

        Ok(true)
    }

    /// Delete a daemon from the config file. Returns Ok(true) if deleted, Ok(false) if not found.
    pub fn delete_daemon_from_config(
        &mut self,
        id: &str,
        config_path: &std::path::Path,
    ) -> Result<bool> {
        let mut config = PitchforkToml::read(config_path)?;

        // For qualified IDs, parse directly; for bare names derive the namespace
        // from the config file path so project-level daemons are found correctly.
        let daemon_id = if id.contains('/') {
            DaemonId::parse(id)?
        } else {
            let ns = namespace_from_path(config_path)?;
            DaemonId::try_new(&ns, id)?
        };

        if config.daemons.shift_remove(&daemon_id).is_some() {
            config.write()?;
            Ok(true)
        } else {
            Ok(false)
        }
    }
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}