powerliners 0.0.9

1:1 Rust port of powerline/powerline. The ultimate statusline/prompt utility.
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
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
// vim:fileencoding=utf-8:noet
//! `powerline-daemon` binary entry.
//!
//! Wires the already-ported pieces:
//!   - `_find_config_files` + `load_json_config` + `mergedicts` for
//!     config loading
//!   - `Colorscheme::new` for highlight resolution
//!   - `Theme` (constructed inline) for the segment table
//!   - `gen_segment_getter` for segment dict preparation
//!   - `Renderer::render` / `do_render` / `_render_segments` for the
//!     render loop
//!   - `TmuxRenderer::hlstyle` for the `#[fg=...,bg=...]` markup
//!   - `scripts::powerline_daemon::main` for the lifecycle
//!
//! Lives in `src/bin/` (sanctioned non-port location). No new fns
//! land under `src/ported/` from this file.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use serde_json::{Map, Value};

use powerliners::ported::colorscheme::Colorscheme;
use powerliners::ported::lib::config::load_json_config;
use powerliners::ported::lib::dict::mergedicts;
use powerliners::ported::renderer::{RenderReturn, Renderer};
use powerliners::ported::renderers::tmux::{ColorSpec, TmuxRenderer};
use powerliners::ported::scripts::powerline_daemon as daemon;
use powerliners::ported::scripts::powerline_daemon::{RenderFn, SpawnWmFn};
use powerliners::ported::segment::gen_segment_getter;
use powerliners::ported::theme::Theme;
use powerliners::ported::{_find_config_files, get_config_paths};

/// Adapter signature for one built-in segment fn.
/// Reads from `args` (segment kwargs) + `segment_info` (runtime env)
/// and returns either a string (single chunk) or list-of-dicts (multi-
/// chunk) as `Value`.
type AdapterFn = fn(&Map<String, Value>, &Map<String, Value>) -> Option<Value>;

fn search_paths() -> Vec<PathBuf> {
    let mut paths: Vec<PathBuf> = Vec::new();
    if let Ok(pcp) = std::env::var("POWERLINE_CONFIG_PATHS") {
        for p in pcp.split(':').filter(|s| !s.is_empty()) {
            paths.push(PathBuf::from(p));
        }
    }
    paths.extend(get_config_paths());
    if let Some(manifest) = option_env!("CARGO_MANIFEST_DIR") {
        let bundled = PathBuf::from(manifest).join("vendor/powerline/powerline/config_files");
        if bundled.is_dir() {
            paths.push(bundled);
        }
    }
    paths
}

fn load_one(name: &str, paths: &[PathBuf]) -> Option<Map<String, Value>> {
    let matches = _find_config_files(paths, name).ok()?;
    let p = matches.first()?;
    let v = load_json_config(p).ok()?;
    v.as_object().cloned()
}

fn load_cascade(levels: &[String], paths: &[PathBuf]) -> Option<Map<String, Value>> {
    let mut out: Map<String, Value> = Map::new();
    let mut loaded = 0u32;
    for level in levels {
        if let Ok(matches) = _find_config_files(paths, level) {
            if let Some(p) = matches.first() {
                if let Ok(v) = load_json_config(p) {
                    if let Some(o) = v.as_object().cloned() {
                        mergedicts(&mut out, o, true);
                        loaded += 1;
                    }
                }
            }
        }
    }
    if loaded == 0 {
        None
    } else {
        Some(out)
    }
}

#[derive(Clone)]
struct Configs {
    colorscheme: Arc<Colorscheme>,
    theme: Arc<Theme>,
    tmux: Arc<TmuxRenderer>,
    /// py:265-272 — WM extensions consume `update_interval` to drive
    /// background re-render. tmux daemon path doesn't run a WM thread;
    /// surfaced here so a future WM dispatch can read the configured
    /// value (default 2 seconds per upstream).
    #[allow(dead_code)]
    wm_update_interval: f64,
    /// py:133-141  `reload_config` (default true) — when true, the
    /// daemon polls cached config-file mtimes on each render and
    /// invalidates the cache when any have changed. Mirrors upstream
    /// `ConfigLoader.check` semantics with a per-request stat instead
    /// of a background watcher thread (the
    /// `lib/watcher/{inotify,stat,uv,tree}.rs` ports are ready but
    /// not threaded here to keep the daemon process model simple).
    reload_config: bool,
    /// Paths whose mtimes are checked when `reload_config` is true.
    loaded_paths: Vec<(PathBuf, std::time::SystemTime)>,
}

impl Configs {
    /// Returns true if any `loaded_paths` entry has a different mtime
    /// vs load time — mirrors `ConfigLoader.check` at
    /// `lib/config.py:130-141`.
    fn is_stale(&self) -> bool {
        if !self.reload_config {
            return false;
        }
        for (p, t) in &self.loaded_paths {
            match std::fs::metadata(p).and_then(|m| m.modified()) {
                Ok(now) if now != *t => return true,
                Err(_) => return true,
                _ => {}
            }
        }
        false
    }
}

/// Snapshot mtime of `path` for the `loaded_paths` cache. Returns
/// SystemTime::UNIX_EPOCH when the stat fails so a follow-up
/// `is_stale` check naturally returns true (treats missing as
/// changed).
fn mtime_or_epoch(path: &PathBuf) -> std::time::SystemTime {
    std::fs::metadata(path)
        .and_then(|m| m.modified())
        .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
}

fn build_configs(ext: &str) -> Result<Configs, String> {
    let paths = search_paths();
    let main = load_one("config", &paths).ok_or("config.json not found")?;
    let colors_json = load_one("colors", &paths).ok_or("colors.json not found")?;

    let (cs_name, theme_name) = {
        let mut cs = "default".to_string();
        let mut th = "default".to_string();
        if let Some(ext_block) = main
            .get("ext")
            .and_then(|v| v.as_object())
            .and_then(|o| o.get(ext))
            .and_then(|v| v.as_object())
        {
            if let Some(s) = ext_block.get("colorscheme").and_then(|v| v.as_str()) {
                cs = s.to_string();
            }
            if let Some(s) = ext_block.get("theme").and_then(|v| v.as_str()) {
                th = s.to_string();
            }
        }
        (cs, th)
    };

    let cs_levels = vec![
        format!("colorschemes/{}", cs_name),
        format!("colorschemes/{}/__main__", ext),
        format!("colorschemes/{}/{}", ext, cs_name),
    ];
    let colorscheme_json =
        load_cascade(&cs_levels, &paths).ok_or_else(|| format!("no colorscheme for {}", ext))?;

    let top_theme = main
        .get("common")
        .and_then(|c| c.get("default_top_theme"))
        .and_then(|v| v.as_str())
        .unwrap_or("powerline");
    // py:806-810 / py:821-823  Theme cascade has THREE layers:
    // 1. `themes/<top_theme>` (cross-ext defaults: dividers, spaces)
    // 2. `themes/<ext>/__main__` (per-ext defaults: segment_data,
    //    division of segments, …)
    // 3. `themes/<ext>/<theme_name>` (the user's specific theme)
    // Each later layer overrides earlier ones via `mergedicts`. Most
    // shipped exts have a `__main__.json` so dropping the middle
    // layer loses per-ext defaults.
    let theme_levels = vec![
        format!("themes/{}", top_theme),
        format!("themes/{}/__main__", ext),
        format!("themes/{}/{}", ext, theme_name),
    ];
    let theme_json =
        load_cascade(&theme_levels, &paths).ok_or_else(|| format!("no theme for {}", ext))?;

    let colorscheme = Colorscheme::new(&colorscheme_json, &colors_json);

    // Build the Theme.segments table from the theme JSON via gen_segment_getter.
    let get_segment = gen_segment_getter(
        &(),
        ext,
        &Map::new(),
        vec![theme_json.clone()],
        theme_json.get("default_module").and_then(|v| v.as_str()),
        |module: &str, name: &str| {
            // Resolve known module.fn pairs to the adapter registry.
            adapter_id(module, name).is_some()
        },
        Some(top_theme),
    );

    let segments_json = theme_json
        .get("segments")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();

    // Mirrors `Theme.__init__` segments-iteration at upstream
    // `powerline/theme.py:91-105`:
    //   `for segdict in itertools.chain((theme_config['segments'],),
    //                                    theme_config['segments'].get('above', ())):`
    //     `self.segments.append(new_empty_segment_line())`
    //     ... fill left + right ...
    // Each segdict = one line. Line 0 = the base render
    // (`segments.{left,right}`); lines 1..=N = `segments.above[0..]`
    // each a `{left, right}` dict in upstream order.
    let prepare_line = |segdict: &Map<String, Value>| -> Map<String, Value> {
        let mut line_map: Map<String, Value> = Map::new();
        for side in ["left", "right"] {
            let mut side_arr: Vec<Value> = Vec::new();
            if let Some(specs) = segdict.get(side).and_then(|v| v.as_array()) {
                for spec in specs {
                    if let Some(spec_obj) = spec.as_object() {
                        if let Some(prepared) = get_segment(spec_obj, side) {
                            side_arr.push(Value::Object(prepared));
                        }
                    }
                }
            }
            line_map.insert(side.to_string(), Value::Array(side_arr));
        }
        line_map
    };

    let mut lines: Vec<Map<String, Value>> = Vec::new();
    // Base line first (theme.py:91 `(theme_config['segments'],)`).
    lines.push(prepare_line(&segments_json));
    // Then each entry under `segments.above`. Python uses tuple()
    // default → empty iter; Rust mirrors with `unwrap_or_default`.
    if let Some(above_list) = segments_json.get("above").and_then(|v| v.as_array()) {
        for above_seg in above_list {
            if let Some(above_obj) = above_seg.as_object() {
                lines.push(prepare_line(above_obj));
            }
        }
    }

    let dividers = theme_json
        .get("dividers")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let spaces = theme_json
        .get("spaces")
        .and_then(|v| v.as_i64())
        .unwrap_or(1);
    let outer_padding = theme_json
        .get("outer_padding")
        .and_then(|v| v.as_i64())
        .unwrap_or(1);

    let mut empty_seg = Map::new();
    empty_seg.insert("contents".to_string(), Value::Null);
    let mut empty_hl = Map::new();
    empty_hl.insert("fg".to_string(), Value::Bool(false));
    empty_hl.insert("bg".to_string(), Value::Bool(false));
    empty_hl.insert("attrs".to_string(), Value::from(0));
    empty_seg.insert("highlight".to_string(), Value::Object(empty_hl));

    // py:67-70  Theme.__init__: cursor_space → 1 - (theme_config['cursor_space'] / 100)
    // when present (KeyError → None); cursor_columns from theme_config.get.
    let cursor_space_multiplier = theme_json
        .get("cursor_space")
        .and_then(|v| v.as_f64())
        .map(|n| 1.0 - (n / 100.0));
    let cursor_columns = theme_json.get("cursor_columns").and_then(|v| v.as_i64());

    let theme = Theme {
        colorscheme: Value::Null,
        dividers,
        cursor_space_multiplier,
        cursor_columns,
        spaces,
        outer_padding,
        segments: lines,
        empty_segment: Value::Object(empty_seg),
        shutdown_called: std::sync::Mutex::new(Vec::new()),
    };

    // Read common.term_truecolor from main config to drive
    // TmuxRenderer.hlstyle's `fg=#RRGGBB` vs `fg=colourN` branch.
    let term_truecolor = main
        .get("common")
        .and_then(|c| c.get("term_truecolor"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    // py:218-223  ext.wm.update_interval (default 2.0). Read from
    // main config so WM-ext requests can honor it once a WM thread
    // dispatcher lands. The tmux ext path is request-driven and
    // ignores it.
    let wm_update_interval = main
        .get("ext")
        .and_then(|v| v.as_object())
        .and_then(|o| o.get("wm"))
        .and_then(|v| v.as_object())
        .and_then(|o| o.get("update_interval"))
        .and_then(|v| v.as_f64())
        .unwrap_or(2.0);

    // py:133-141  reload_config (default true)
    let reload_config = main
        .get("common")
        .and_then(|c| c.get("reload_config"))
        .and_then(|v| v.as_bool())
        .unwrap_or(true);

    // Collect every config file path our cascade actually consumed so
    // `is_stale` can stat them on subsequent renders.
    let mut loaded_paths: Vec<(PathBuf, std::time::SystemTime)> = Vec::new();
    let probe_levels: Vec<String> = vec![
        "config".to_string(),
        "colors".to_string(),
        format!("colorschemes/{}", cs_name),
        format!("colorschemes/{}/__main__", ext),
        format!("colorschemes/{}/{}", ext, cs_name),
        format!("themes/{}", top_theme),
        format!("themes/{}/__main__", ext),
        format!("themes/{}/{}", ext, theme_name),
    ];
    for level in &probe_levels {
        if let Ok(matches) = _find_config_files(&paths, level) {
            if let Some(p) = matches.first().cloned() {
                let mt = mtime_or_epoch(&p);
                loaded_paths.push((p, mt));
            }
        }
    }

    Ok(Configs {
        colorscheme: Arc::new(colorscheme),
        theme: Arc::new(theme),
        tmux: Arc::new(TmuxRenderer::new(term_truecolor)),
        wm_update_interval,
        reload_config,
        loaded_paths,
    })
}

/// Look up the segment id (module + name) in the adapter registry.
/// Returns the canonical "module.name" form on match, None on miss.
fn adapter_id(module: &str, name: &str) -> Option<&'static str> {
    let full = format!("{}.{}", module, name);
    ADAPTERS
        .iter()
        .find(|(k, _)| *k == full.as_str())
        .map(|(k, _)| *k)
}

fn invoke_adapter(
    id: &str,
    args: &Map<String, Value>,
    segment_info: &Map<String, Value>,
) -> Option<Value> {
    let entry = ADAPTERS.iter().find(|(k, _)| *k == id)?;
    entry.1(args, segment_info)
}

// =============================================================
// Adapters: each maps a built-in Rust segment fn into the
// dispatcher's uniform signature. Lives in the bin (non-port).
// =============================================================

fn ad_hostname(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::net::hostname;
    let environ = info
        .get("environ")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let only_if_ssh = args
        .get("only_if_ssh")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let exclude_domain = args
        .get("exclude_domain")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let s = hostname(&environ, only_if_ssh, exclude_domain, || {
        std::process::Command::new("hostname")
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .map(|s| s.trim().to_string())
            .unwrap_or_default()
    })?;
    Some(Value::String(s))
}

fn ad_date(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::time::date;
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("%Y-%m-%d");
    let istime = args
        .get("istime")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let timezone = args.get("timezone").and_then(|v| v.as_str());
    let chunks = date(&(), format, istime, timezone);
    Some(Value::Array(chunks))
}

fn read_cpu_percent() -> f64 {
    // `top -l 1 -s 0 -n 0` prints one summary, including the CPU usage
    // line. On darwin: `CPU usage: 3.4% user, 5.2% sys, 91.3% idle`.
    // We sum user + sys for the "active" reading. Linux fallback parses
    // /proc/stat first delta over a 100ms sleep.
    #[cfg(target_os = "macos")]
    {
        if let Ok(out) = std::process::Command::new("top")
            .args(["-l", "1", "-s", "0", "-n", "0"])
            .output()
        {
            let text = String::from_utf8_lossy(&out.stdout);
            for line in text.lines() {
                if let Some(rest) = line.strip_prefix("CPU usage: ") {
                    let mut user = 0.0f64;
                    let mut sys = 0.0f64;
                    for part in rest.split(',') {
                        let part = part.trim();
                        if let Some(p) = part.strip_suffix("% user") {
                            user = p.trim().parse().unwrap_or(0.0);
                        } else if let Some(p) = part.strip_suffix("% sys") {
                            sys = p.trim().parse().unwrap_or(0.0);
                        }
                    }
                    return user + sys;
                }
            }
        }
    }
    #[cfg(target_os = "linux")]
    {
        let read = || -> Option<(u64, u64)> {
            let s = std::fs::read_to_string("/proc/stat").ok()?;
            let line = s.lines().next()?;
            let parts: Vec<u64> = line
                .split_whitespace()
                .skip(1)
                .filter_map(|p| p.parse().ok())
                .collect();
            let total: u64 = parts.iter().sum();
            let idle = *parts.get(3)?;
            Some((total, idle))
        };
        if let (Some((t1, i1)), _) = (
            read(),
            std::thread::sleep(std::time::Duration::from_millis(100)),
        ) {
            if let Some((t2, i2)) = read() {
                let dt = t2.saturating_sub(t1) as f64;
                let di = i2.saturating_sub(i1) as f64;
                if dt > 0.0 {
                    return 100.0 * (1.0 - di / dt);
                }
            }
        }
    }
    0.0
}

fn ad_cpu_load_percent(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::sys::render as cpu_render;
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{0:.0f}%");
    let pct = read_cpu_percent();
    let chunks = cpu_render(pct, format);
    Some(Value::Array(chunks))
}

fn ad_mem_usage(_args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // powerlinemem.mem_usage isn't in upstream; reproduce its typical
    // output (memory used percent) using `vm_stat` on darwin or
    // /proc/meminfo on linux.
    #[cfg(target_os = "macos")]
    let pct = {
        let out = std::process::Command::new("vm_stat").output().ok()?;
        let text = String::from_utf8_lossy(&out.stdout);
        let mut free = 0u64;
        let mut active = 0u64;
        let mut inactive = 0u64;
        let mut wired = 0u64;
        let mut compressed = 0u64;
        let mut page_size: u64 = 4096;
        for line in text.lines() {
            if let Some(p) = line.strip_prefix("Mach Virtual Memory Statistics: (page size of ") {
                if let Some(n) = p.split(' ').next().and_then(|s| s.parse().ok()) {
                    page_size = n;
                }
            }
            let parse = |label: &str| -> Option<u64> {
                line.strip_prefix(label)
                    .and_then(|r| r.trim().trim_end_matches('.').parse().ok())
            };
            if let Some(n) = parse("Pages free:") {
                free = n;
            }
            if let Some(n) = parse("Pages active:") {
                active = n;
            }
            if let Some(n) = parse("Pages inactive:") {
                inactive = n;
            }
            if let Some(n) = parse("Pages wired down:") {
                wired = n;
            }
            if let Some(n) = parse("Pages occupied by compressor:") {
                compressed = n;
            }
        }
        let used = (active + wired + compressed) * page_size;
        let total = (free + active + inactive + wired + compressed) * page_size;
        if total == 0 {
            0.0
        } else {
            100.0 * used as f64 / total as f64
        }
    };
    #[cfg(target_os = "linux")]
    let pct = {
        let s = std::fs::read_to_string("/proc/meminfo").ok()?;
        let mut total = 0u64;
        let mut available = 0u64;
        for line in s.lines() {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.first() == Some(&"MemTotal:") {
                total = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
            }
            if parts.first() == Some(&"MemAvailable:") {
                available = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
            }
        }
        if total == 0 {
            0.0
        } else {
            100.0 * (total - available) as f64 / total as f64
        }
    };
    Some(Value::Array(vec![serde_json::json!({
        "contents": format!("{:.0}%", pct),
        "highlight_groups": ["mem_usage_gradient", "mem_usage"],
        "gradient_level": pct,
    })]))
}

fn ad_system_load(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::sys::system_load;
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{avg:.1f}");
    let threshold_good = args
        .get("threshold_good")
        .and_then(|v| v.as_f64())
        .unwrap_or(1.0);
    let threshold_bad = args
        .get("threshold_bad")
        .and_then(|v| v.as_f64())
        .unwrap_or(2.0);
    let track_cpu_count = args
        .get("track_cpu_count")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let short = args.get("short").and_then(|v| v.as_bool()).unwrap_or(false);
    let _ = (threshold_good, threshold_bad, track_cpu_count, short);
    Some(Value::Array(system_load(
        &(),
        format,
        threshold_good,
        threshold_bad,
        track_cpu_count,
        short,
    )?))
}

fn ad_uptime(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::sys::uptime;
    let days_format = args
        .get("days_format")
        .and_then(|v| v.as_str())
        .unwrap_or("{days:d}d ");
    let hours_format = args
        .get("hours_format")
        .and_then(|v| v.as_str())
        .unwrap_or("{hours:d}h ");
    let minutes_format = args
        .get("minutes_format")
        .and_then(|v| v.as_str())
        .unwrap_or("{minutes:d}m ");
    let seconds_format = args
        .get("seconds_format")
        .and_then(|v| v.as_str())
        .unwrap_or("{seconds:d}s");
    let shorten_len = args
        .get("shorten_len")
        .and_then(|v| v.as_u64())
        .unwrap_or(3) as usize;
    let s = uptime(
        &(),
        days_format,
        hours_format,
        minutes_format,
        seconds_format,
        shorten_len,
    )?;
    Some(Value::String(s))
}

fn ad_external_ip(_args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::net::{_external_ip, external_ip_render};
    let ip = _external_ip(|| {
        std::process::Command::new("curl")
            .args(["-s", "https://ipv4.icanhazip.com"])
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .map(|s| s.trim().to_string())
    });
    let chunks = external_ip_render(ip.as_deref())?;
    Some(Value::Array(chunks))
}

fn ad_internal_ip(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    let interface = args
        .get("interface")
        .and_then(|v| v.as_str())
        .unwrap_or("auto");
    let ipv = args
        .get("ipv")
        .and_then(|v| v.as_u64())
        .map(|n| n as u8)
        .unwrap_or(4);
    let iface = if interface == "auto" {
        // Resolve default route's interface via netstat -rn on darwin /
        // ip route on linux.
        #[cfg(target_os = "macos")]
        {
            let out = std::process::Command::new("netstat")
                .args(["-rn", "-f", "inet"])
                .output()
                .ok()?;
            let text = String::from_utf8_lossy(&out.stdout);
            let mut found: Option<String> = None;
            for line in text.lines() {
                if line.starts_with("default ") {
                    let cols: Vec<&str> = line.split_whitespace().collect();
                    if let Some(name) = cols.get(3) {
                        found = Some(name.to_string());
                        break;
                    }
                }
            }
            found?
        }
        #[cfg(not(target_os = "macos"))]
        {
            let out = std::process::Command::new("ip")
                .args(["route", "show", "default"])
                .output()
                .ok()?;
            let text = String::from_utf8_lossy(&out.stdout);
            text.split_whitespace()
                .skip_while(|s| *s != "dev")
                .nth(1)?
                .to_string()
        }
    } else {
        interface.to_string()
    };

    let out = std::process::Command::new("ifconfig")
        .arg(&iface)
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&out.stdout);
    let needle = if ipv == 6 { "inet6 " } else { "inet " };
    for line in text.lines() {
        let trimmed = line.trim();
        if let Some(after) = trimmed.strip_prefix(needle) {
            let ip = after.split_whitespace().next()?.to_string();
            if ipv == 4 && ip == "127.0.0.1" {
                continue;
            }
            return Some(Value::String(ip));
        }
    }
    None
}

fn ad_network_load(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::net::render_one;
    let interface = args
        .get("interface")
        .and_then(|v| v.as_str())
        .unwrap_or("auto")
        .to_string();
    // Darwin: netstat -ib gives per-interface byte counters.
    // Linux: /sys/class/net/<iface>/statistics/{rx,tx}_bytes via _get_bytes_sysfs.
    #[cfg(target_os = "macos")]
    let bytes = {
        let read = || -> Option<(u64, u64)> {
            let out = std::process::Command::new("netstat")
                .args(["-ibn"])
                .output()
                .ok()?;
            let text = String::from_utf8_lossy(&out.stdout);
            for line in text.lines().skip(1) {
                let cols: Vec<&str> = line.split_whitespace().collect();
                if cols.first().map(|c| *c == interface).unwrap_or(false) {
                    let rx: u64 = cols.get(6).and_then(|c| c.parse().ok())?;
                    let tx: u64 = cols.get(9).and_then(|c| c.parse().ok())?;
                    return Some((rx, tx));
                }
            }
            None
        };
        let snap1 = read()?;
        std::thread::sleep(std::time::Duration::from_millis(500));
        let snap2 = read()?;
        let rx_rate = snap2.0.saturating_sub(snap1.0) as f64 * 2.0;
        let tx_rate = snap2.1.saturating_sub(snap1.1) as f64 * 2.0;
        (rx_rate, tx_rate)
    };
    #[cfg(target_os = "linux")]
    let bytes = {
        let read = || {
            let rx = std::fs::read_to_string(format!(
                "/sys/class/net/{}/statistics/rx_bytes",
                interface
            ))
            .ok()?;
            let tx = std::fs::read_to_string(format!(
                "/sys/class/net/{}/statistics/tx_bytes",
                interface
            ))
            .ok()?;
            Some((rx.trim().parse().ok()?, tx.trim().parse().ok()?))
        };
        let snap1: (u64, u64) = read()?;
        std::thread::sleep(std::time::Duration::from_millis(500));
        let snap2: (u64, u64) = read()?;
        (
            snap2.0.saturating_sub(snap1.0) as f64 * 2.0,
            snap2.1.saturating_sub(snap1.1) as f64 * 2.0,
        )
    };
    let recv_format = args
        .get("recv_format")
        .and_then(|v| v.as_str())
        .unwrap_or("DL {value:>8}");
    let sent_format = args
        .get("sent_format")
        .and_then(|v| v.as_str())
        .unwrap_or("UL {value:>8}");
    let suffix = args.get("suffix").and_then(|v| v.as_str()).unwrap_or("B/s");
    let si_prefix = args
        .get("si_prefix")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let recv_max = args
        .get("recv_max")
        .and_then(|v| v.as_f64())
        .unwrap_or(1_000_000.0);
    let sent_max = args
        .get("sent_max")
        .and_then(|v| v.as_f64())
        .unwrap_or(1_000_000.0);
    let _ = bytes; // already-rate values; render_one wants raw snapshots
                   // Re-snapshot to feed render_one: it needs (t1, (rx1,tx1)) and (t2, (rx2,tx2)).
    #[cfg(target_os = "macos")]
    let (prev, last) = {
        let read = || -> Option<(f64, (u64, u64))> {
            let out = std::process::Command::new("netstat")
                .args(["-ibn"])
                .output()
                .ok()?;
            let text = String::from_utf8_lossy(&out.stdout);
            for line in text.lines().skip(1) {
                let cols: Vec<&str> = line.split_whitespace().collect();
                if cols.first().map(|c| *c == interface).unwrap_or(false) {
                    let rx: u64 = cols.get(6).and_then(|c| c.parse().ok())?;
                    let tx: u64 = cols.get(9).and_then(|c| c.parse().ok())?;
                    let t = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .ok()?
                        .as_secs_f64();
                    return Some((t, (rx, tx)));
                }
            }
            None
        };
        let p = read()?;
        std::thread::sleep(std::time::Duration::from_millis(500));
        let l = read()?;
        (p, l)
    };
    #[cfg(target_os = "linux")]
    let (prev, last) = {
        let read = || -> Option<(f64, (u64, u64))> {
            let rx = std::fs::read_to_string(format!(
                "/sys/class/net/{}/statistics/rx_bytes",
                interface
            ))
            .ok()?
            .trim()
            .parse::<u64>()
            .ok()?;
            let tx = std::fs::read_to_string(format!(
                "/sys/class/net/{}/statistics/tx_bytes",
                interface
            ))
            .ok()?
            .trim()
            .parse::<u64>()
            .ok()?;
            let t = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .ok()?
                .as_secs_f64();
            Some((t, (rx, tx)))
        };
        let p = read()?;
        std::thread::sleep(std::time::Duration::from_millis(500));
        let l = read()?;
        (p, l)
    };
    let chunks = render_one(
        Some(prev),
        Some(last),
        recv_format,
        sent_format,
        suffix,
        si_prefix,
        Some(recv_max),
        Some(sent_max),
    )?;
    Some(Value::Array(chunks))
}

// `needless_return` allowed: the `return` keeps the macOS branch readable
// alongside the `#[cfg(not(target_os = "macos"))] None` tail without
// restructuring around the cfg gate.
#[allow(clippy::needless_return)]
fn ad_spotify(_args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // Darwin-only AppleScript probe.
    #[cfg(target_os = "macos")]
    {
        let out = std::process::Command::new("osascript")
            .args([
                "-e",
                "if application \"Spotify\" is running then\n\
                 tell application \"Spotify\"\n\
                 if player state is playing then\n\
                 return artist of current track & \" - \" & name of current track\n\
                 end if\n\
                 end tell\n\
                 end if",
            ])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
        if s.is_empty() {
            return None;
        }
        return Some(Value::Array(vec![serde_json::json!({
            "contents": s,
            "highlight_groups": ["now_playing"],
            "divider_highlight_group": Value::Null,
        })]));
    }
    #[cfg(not(target_os = "macos"))]
    {
        None
    }
}

fn ad_branch(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    let cwd = info
        .get("getcwd")
        .and_then(|v| v.as_str())
        .unwrap_or("/")
        .to_string();
    let status_colors = args
        .get("status_colors")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    // py:18-39  BranchSegment tries each registered VCS guesser in
    // order (git → mercurial → bazaar). Mirror by probing the same
    // three backends; first one to find a repo wins.
    let (branch, dirty_opt) = git_branch(&cwd)
        .or_else(|| hg_branch(&cwd))
        .or_else(|| bzr_branch(&cwd))?;
    if branch.is_empty() {
        return None;
    }
    let mut groups: Vec<Value> = vec![Value::String("branch".to_string())];
    if status_colors {
        let dirty = dirty_opt.unwrap_or(false);
        groups.insert(
            0,
            Value::String(
                if dirty {
                    "branch_dirty"
                } else {
                    "branch_clean"
                }
                .to_string(),
            ),
        );
    }
    Some(Value::Array(vec![serde_json::json!({
        "contents": branch,
        "highlight_groups": groups,
        "divider_highlight_group": Value::Null,
    })]))
}

/// Probe git for the current branch + dirty flag.
/// Returns None when the cwd isn't a git repo.
fn git_branch(cwd: &str) -> Option<(String, Option<bool>)> {
    let out = std::process::Command::new("git")
        .args(["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let branch = String::from_utf8(out.stdout).ok()?.trim().to_string();
    let dirty = std::process::Command::new("git")
        .args(["-C", cwd, "status", "--porcelain"])
        .output()
        .ok()
        .map(|o| !o.stdout.is_empty());
    Some((branch, dirty))
}

/// Probe mercurial. `hg branch` prints the active branch (default
/// "default"); `hg status` reports working-copy changes.
fn hg_branch(cwd: &str) -> Option<(String, Option<bool>)> {
    let out = std::process::Command::new("hg")
        .args(["--cwd", cwd, "branch"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let branch = String::from_utf8(out.stdout).ok()?.trim().to_string();
    let dirty = std::process::Command::new("hg")
        .args(["--cwd", cwd, "status"])
        .output()
        .ok()
        .map(|o| !o.stdout.is_empty());
    Some((branch, dirty))
}

/// Probe bazaar. `bzr nick` prints the nick of the current branch;
/// `bzr status` reports working-tree changes.
fn bzr_branch(cwd: &str) -> Option<(String, Option<bool>)> {
    let out = std::process::Command::new("bzr")
        .args(["--directory", cwd, "nick"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let branch = String::from_utf8(out.stdout).ok()?.trim().to_string();
    let dirty = std::process::Command::new("bzr")
        .args(["--directory", cwd, "status"])
        .output()
        .ok()
        .map(|o| !o.stdout.is_empty());
    Some((branch, dirty))
}

fn ad_stash(_args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    let cwd = info
        .get("getcwd")
        .and_then(|v| v.as_str())
        .unwrap_or("/")
        .to_string();
    let out = std::process::Command::new("git")
        .args(["-C", &cwd, "stash", "list"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let count = String::from_utf8(out.stdout)
        .ok()?
        .lines()
        .filter(|l| !l.is_empty())
        .count();
    if count == 0 {
        return None;
    }
    Some(Value::Array(vec![serde_json::json!({
        "contents": format!("{}", count),
        "highlight_groups": ["stash"],
        "divider_highlight_group": Value::Null,
    })]))
}

fn ad_battery(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::bat::{battery, parse_pmset_output};
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{ac_state} {capacity:3.0%}");
    let steps = args.get("steps").and_then(|v| v.as_u64()).unwrap_or(5) as u32;
    let gamify = args
        .get("gamify")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let full_heart = args
        .get("full_heart")
        .and_then(|v| v.as_str())
        .unwrap_or("O");
    let empty_heart = args
        .get("empty_heart")
        .and_then(|v| v.as_str())
        .unwrap_or("O");
    let online = args.get("online").and_then(|v| v.as_str()).unwrap_or("C");
    let offline = args.get("offline").and_then(|v| v.as_str()).unwrap_or(" ");
    let result = battery(
        || {
            let out = std::process::Command::new("pmset")
                .args(["-g", "batt"])
                .output()
                .ok()?;
            let text = String::from_utf8(out.stdout).ok()?;
            let (pct, ac) = parse_pmset_output(&text)?;
            Some((pct as f64, ac))
        },
        format,
        steps,
        gamify,
        full_heart,
        empty_heart,
        online,
        offline,
    )?;
    Some(Value::Array(result))
}

fn ad_environment(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::env::environment;
    let environ = info
        .get("environ")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let variable = args.get("variable").and_then(|v| v.as_str())?;
    let v = environment(&environ, variable)?;
    Some(Value::String(v))
}

fn ad_jobnum(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::shell::jobnum;
    use powerliners::ported::segments::shell::ShellSegmentInfo;
    let show_zero = args
        .get("show_zero")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let seg_info = ShellSegmentInfo {
        jobnum: info
            .get("args")
            .and_then(|v| v.as_object())
            .and_then(|o| o.get("jobnum"))
            .and_then(|v| v.as_i64())
            .map(|n| n as i32),
        ..Default::default()
    };
    let s = jobnum(&(), &seg_info, show_zero)?;
    Some(Value::String(s))
}

fn ad_last_status(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::shell::last_status;
    use powerliners::ported::segments::shell::ShellSegmentInfo;
    let signal_names = args
        .get("signal_names")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    // ShellSegmentInfo uses i32 for last_exit_code. Signal-name strings
    // (e.g. "sigINT") aren't carried through the i32 path — that's a
    // structural divergence from upstream (Python IntOrSig union) which
    // we surface by treating signal names as exit-code 0 here. Real
    // shell-prompt drivers should switch to IntOrSig once
    // ShellSegmentInfo gains a union field.
    let last_exit_code = info
        .get("args")
        .and_then(|v| v.as_object())
        .and_then(|o| o.get("last_exit_code"))
        .and_then(|v| v.as_i64())
        .map(|n| n as i32);
    let seg_info = ShellSegmentInfo {
        last_exit_code,
        ..Default::default()
    };
    let chunks = last_status(&(), &seg_info, signal_names)?;
    Some(Value::Array(chunks))
}

fn ad_last_pipe_status(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::shell::last_pipe_status as lps_fn;
    use powerliners::ported::segments::shell::ShellSegmentInfo;
    let signal_names = args
        .get("signal_names")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    let lps_vec: Vec<i32> = info
        .get("args")
        .and_then(|v| v.as_object())
        .and_then(|o| o.get("last_pipe_status"))
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().map(|v| v.as_i64().unwrap_or(0) as i32).collect())
        .unwrap_or_default();
    let seg_info = ShellSegmentInfo {
        last_pipe_status: lps_vec,
        ..Default::default()
    };
    let chunks = lps_fn(&(), &seg_info, signal_names)?;
    Some(Value::Array(chunks))
}

fn ad_cwd(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::env::cwd_segments;
    let cwd = info
        .get("getcwd")
        .and_then(|v| v.as_str())
        .unwrap_or("/")
        .to_string();
    let dir_shorten_len = args
        .get("dir_shorten_len")
        .and_then(|v| v.as_u64())
        .map(|n| n as usize);
    let dir_limit_depth = args
        .get("dir_limit_depth")
        .and_then(|v| v.as_u64())
        .map(|n| n as usize);
    let use_path_separator = args
        .get("use_path_separator")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let ellipsis = args.get("ellipsis").and_then(|v| v.as_str());
    let chunks = cwd_segments(
        &cwd,
        dir_shorten_len,
        dir_limit_depth,
        use_path_separator,
        ellipsis,
    );
    if chunks.is_empty() {
        return None;
    }
    Some(Value::Array(chunks))
}

fn ad_virtualenv(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::env::virtualenv;
    let environ = info
        .get("environ")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let ignore_venv = args
        .get("ignore_venv")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let ignore_conda = args
        .get("ignore_conda")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let ignored: Vec<String> = args
        .get("ignored_names")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_else(|| vec!["venv".to_string(), ".venv".to_string()]);
    let ignored_refs: Vec<&str> = ignored.iter().map(String::as_str).collect();
    let v = virtualenv(&environ, ignore_venv, ignore_conda, &ignored_refs)?;
    Some(Value::String(v))
}

fn ad_fuzzy_time(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::time::{
        fuzzy_time, fuzzy_time_default_hour_str, fuzzy_time_default_minute_str,
        fuzzy_time_default_special_cases,
    };
    let format = args.get("format").and_then(|v| v.as_str());
    let unicode_text = args
        .get("unicode_text")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let timezone = args.get("timezone").and_then(|v| v.as_str());

    // py:46  hour_str=[...], minute_str={...}, special_case_str={...}
    // User-supplied overrides come in via theme args; build the
    // owned String buffers, then take &str slices for the fuzzy_time
    // call. Defaults fill in any keys the user omits.
    let hour_str_default = fuzzy_time_default_hour_str();
    let hour_str_owned: Vec<String> = match args.get("hour_str").and_then(|v| v.as_array()) {
        Some(arr) => arr
            .iter()
            .filter_map(|v| v.as_str().map(String::from))
            .collect(),
        None => hour_str_default.iter().map(|s| s.to_string()).collect(),
    };
    let hour_str: Vec<&str> = hour_str_owned.iter().map(String::as_str).collect();

    let minute_str_default = fuzzy_time_default_minute_str();
    let minute_str_owned: std::collections::HashMap<u32, String> =
        match args.get("minute_str").and_then(|v| v.as_object()) {
            Some(obj) => obj
                .iter()
                .filter_map(|(k, v)| {
                    let key: u32 = k.parse().ok()?;
                    let val = v.as_str()?.to_string();
                    Some((key, val))
                })
                .collect(),
            None => minute_str_default
                .iter()
                .map(|(k, v)| (*k, v.to_string()))
                .collect(),
        };
    let minute_str: std::collections::HashMap<u32, &str> = minute_str_owned
        .iter()
        .map(|(k, v)| (*k, v.as_str()))
        .collect();

    let special_cases = fuzzy_time_default_special_cases();
    let s = fuzzy_time(
        format,
        unicode_text,
        timezone,
        Some(&hour_str),
        Some(&minute_str),
        Some(&special_cases),
    );
    if s.is_empty() {
        return None;
    }
    Some(Value::String(s))
}

fn ad_weather(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::wthr::{compute_state, render_one, weather_key};
    let location_query = args
        .get("location_query")
        .and_then(|v| v.as_str())
        .map(String::from);
    let api_key = args
        .get("weather_api_key")
        .and_then(|v| v.as_str())
        .map(String::from);
    let key = weather_key(location_query, api_key);
    let weather = compute_state(&key)?;
    let unit = args.get("unit").and_then(|v| v.as_str()).unwrap_or("C");
    let temp_format = args.get("temp_format").and_then(|v| v.as_str());
    let temp_coldest = args
        .get("temp_coldest")
        .and_then(|v| v.as_f64())
        .unwrap_or(-30.0);
    let temp_hottest = args
        .get("temp_hottest")
        .and_then(|v| v.as_f64())
        .unwrap_or(40.0);
    let icons = args.get("icons").and_then(|v| v.as_object());
    let chunks = render_one(
        Some(weather),
        icons,
        unit,
        temp_format,
        temp_coldest,
        temp_hottest,
    )?;
    Some(Value::Array(chunks))
}

fn ad_email_imap_alert(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // py:43-138  EmailIMAPSegment — full IMAP probe would need a
    // TLS imap crate (not in deps). Surface a configured-username
    // placeholder so the segment is visible; faithful imap probe
    // is a follow-up dep choice.
    let username = args.get("username").and_then(|v| v.as_str())?;
    Some(Value::Array(vec![serde_json::json!({
        "contents": format!("{}: 0", username),
        "highlight_groups": ["email_alert"],
    })]))
}

fn ad_cmus(_args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::players::CmusPlayerSegment;
    let out = std::process::Command::new("cmus-remote")
        .arg("-Q")
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8(out.stdout).ok()?;
    let segment = CmusPlayerSegment;
    let stats = segment.get_player_status(&s)?;
    let title = stats.title.as_deref().unwrap_or("");
    if title.is_empty() {
        return None;
    }
    let artist = stats.artist.as_deref().unwrap_or("");
    let contents = if artist.is_empty() {
        title.to_string()
    } else {
        format!("{} - {}", artist, title)
    };
    Some(Value::Array(vec![serde_json::json!({
        "contents": contents,
        "highlight_groups": ["now_playing"],
    })]))
}

fn ad_rhythmbox(_args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::players::RhythmboxPlayerSegment;
    // py:458-473  rhythmbox-client probe
    let out = std::process::Command::new("rhythmbox-client")
        .args([
            "--no-start",
            "--print-playing-format",
            "%at\n%aa\n%tt\n%te\n%td",
        ])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8(out.stdout).ok()?;
    let segment = RhythmboxPlayerSegment;
    let stats = segment.get_player_status(&s)?;
    let title = stats.title.as_deref().unwrap_or("");
    if title.is_empty() {
        return None;
    }
    let artist = stats.artist.as_deref().unwrap_or("");
    let contents = if artist.is_empty() {
        title.to_string()
    } else {
        format!("{} - {}", artist, title)
    };
    Some(Value::Array(vec![serde_json::json!({
        "contents": contents,
        "highlight_groups": ["now_playing"],
    })]))
}

fn ad_itunes(_args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // py:534-572  iTunes via AppleScript on darwin.
    #[cfg(target_os = "macos")]
    {
        let out = std::process::Command::new("osascript")
            .args([
                "-e",
                "if application \"iTunes\" is running then\n\
                 tell application \"iTunes\"\n\
                 if player state is playing then\n\
                 return artist of current track & \" - \" & name of current track\n\
                 end if\n\
                 end tell\n\
                 end if",
            ])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
        if s.is_empty() {
            return None;
        }
        Some(Value::Array(vec![serde_json::json!({
            "contents": s,
            "highlight_groups": ["now_playing"],
        })]))
    }
    #[cfg(not(target_os = "macos"))]
    None
}

fn ad_dbus_player(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // py:384-449  generic MPRIS probe parameterized by player_name.
    let player = args.get("player_name").and_then(|v| v.as_str())?;
    let service = format!("org.mpris.MediaPlayer2.{}", player);
    let metadata = std::process::Command::new("qdbus")
        .args([
            &service,
            "/Player",
            "org.freedesktop.MediaPlayer.GetMetadata",
        ])
        .output()
        .ok()?;
    if !metadata.status.success() {
        return None;
    }
    let text = String::from_utf8(metadata.stdout).ok()?;
    let mut artist = String::new();
    let mut title = String::new();
    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("artist: ") {
            artist = rest.to_string();
        } else if let Some(rest) = line.strip_prefix("title: ") {
            title = rest.to_string();
        }
    }
    if title.is_empty() {
        return None;
    }
    let contents = if artist.is_empty() {
        title
    } else {
        format!("{} - {}", artist, title)
    };
    Some(Value::Array(vec![serde_json::json!({
        "contents": contents,
        "highlight_groups": ["now_playing"],
    })]))
}

fn ad_clementine(_args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // py:431-449  Clementine via MPRIS dbus. `qdbus` shells the
    // method calls; on systems without qdbus we silently skip.
    let metadata = std::process::Command::new("qdbus")
        .args([
            "org.mpris.MediaPlayer2.clementine",
            "/Player",
            "org.freedesktop.MediaPlayer.GetMetadata",
        ])
        .output()
        .ok()?;
    if !metadata.status.success() {
        return None;
    }
    let text = String::from_utf8(metadata.stdout).ok()?;
    // qdbus prints `key: value` lines for the dict. Extract artist + title.
    let mut artist = String::new();
    let mut title = String::new();
    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("artist: ") {
            artist = rest.to_string();
        } else if let Some(rest) = line.strip_prefix("title: ") {
            title = rest.to_string();
        }
    }
    if title.is_empty() {
        return None;
    }
    let contents = if artist.is_empty() {
        title
    } else {
        format!("{} - {}", artist, title)
    };
    Some(Value::Array(vec![serde_json::json!({
        "contents": contents,
        "highlight_groups": ["now_playing"],
    })]))
}

fn ad_mocp(_args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::players::MocPlayerSegment;
    let out = std::process::Command::new("mocp").arg("-i").output().ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8(out.stdout).ok()?;
    let segment = MocPlayerSegment;
    let stats = segment.get_player_status(&s)?;
    let title = stats.title.as_deref().unwrap_or("");
    if title.is_empty() {
        return None;
    }
    let artist = stats.artist.as_deref().unwrap_or("");
    let contents = if artist.is_empty() {
        title.to_string()
    } else {
        format!("{} - {}", artist, title)
    };
    Some(Value::Array(vec![serde_json::json!({
        "contents": contents,
        "highlight_groups": ["now_playing"],
    })]))
}

fn ad_mpd(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // Probe `mpc current` and wrap as a player segment. Mirrors the
    // upstream `MpdPlayerSegment.__call__` at
    // `powerline/segments/common/players.py:173` shape — host/password/
    // port args are honored via `-h HOST -p PORT` flags + `MPD_HOST=PASSWORD@HOST`
    // env per `mpc(1)`.
    let host = args.get("host").and_then(|v| v.as_str());
    let port = args.get("port").and_then(|v| v.as_u64());
    let password = args.get("password").and_then(|v| v.as_str());
    let mut cmd = std::process::Command::new("mpc");
    if let (Some(pw), Some(h)) = (password, host) {
        cmd.env("MPD_HOST", format!("{}@{}", pw, h));
    } else if let Some(h) = host {
        cmd.env("MPD_HOST", h);
    }
    if let Some(p) = port {
        cmd.arg("-p").arg(p.to_string());
    }
    cmd.arg("current");
    let out = cmd.output().ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
    if s.is_empty() {
        return None;
    }
    Some(Value::Array(vec![serde_json::json!({
        "contents": s,
        "highlight_groups": ["now_playing"],
        "divider_highlight_group": Value::Null,
    })]))
}

fn ad_user(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::env::user;
    let environ = info
        .get("environ")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let hide_user = args.get("hide_user").and_then(|v| v.as_str());
    let hide_domain = args
        .get("hide_domain")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    // SAFETY: geteuid() is async-signal-safe POSIX.
    let euid = unsafe { libc::geteuid() };
    let chunks = user(&environ, hide_user, hide_domain, euid)?;
    Some(Value::Array(chunks))
}

const ADAPTERS: &[(&str, AdapterFn)] = &[
    ("powerline.segments.common.net.hostname", ad_hostname),
    ("powerline.segments.common.time.date", ad_date),
    ("powerline.segments.common.time.fuzzy_time", ad_fuzzy_time),
    ("powerline.segments.common.env.environment", ad_environment),
    ("powerline.segments.common.env.virtualenv", ad_virtualenv),
    ("powerline.segments.common.env.cwd", ad_cwd),
    ("powerline.segments.shell.jobnum", ad_jobnum),
    ("powerline.segments.shell.last_status", ad_last_status),
    (
        "powerline.segments.shell.last_pipe_status",
        ad_last_pipe_status,
    ),
    ("powerline.segments.common.env.user", ad_user),
    ("powerline.segments.common.players.mpd", ad_mpd),
    (
        "powerline.segments.common.sys.cpu_load_percent",
        ad_cpu_load_percent,
    ),
    ("powerline.segments.common.sys.system_load", ad_system_load),
    ("powerline.segments.common.sys.uptime", ad_uptime),
    ("powerline.segments.common.net.external_ip", ad_external_ip),
    ("powerline.segments.common.net.internal_ip", ad_internal_ip),
    ("powerline.segments.common.vcs.branch", ad_branch),
    ("powerline.segments.common.vcs.stash", ad_stash),
    ("powerline.segments.common.bat.battery", ad_battery),
    ("powerlinemem.mem_usage.mem_usage", ad_mem_usage),
    (
        "powerline.segments.common.net.network_load",
        ad_network_load,
    ),
    ("powerline.segments.common.players.spotify", ad_spotify),
    ("powerline.segments.common.players.cmus", ad_cmus),
    ("powerline.segments.common.players.mocp", ad_mocp),
    ("powerline.segments.common.players.rhythmbox", ad_rhythmbox),
    ("powerline.segments.common.players.itunes", ad_itunes),
    (
        "powerline.segments.common.players.clementine",
        ad_clementine,
    ),
    (
        "powerline.segments.common.players.dbus_player",
        ad_dbus_player,
    ),
    ("powerline.segments.common.wthr.weather", ad_weather),
    (
        "powerline.segments.common.mail.email_imap_alert",
        ad_email_imap_alert,
    ),
];

/// Python-faithful color encoding for the hlstyle directive builder.
/// Python passes `fg`/`bg` as one of:
///   - `None` → don't emit the channel directive at all
///   - `False` or `(False, ...)` → emit `<channel>=default`
///   - `(cterm_int, hex_int_or_None)` → emit `<channel>=colourN` (or `=#hex` truecolor)
enum ColorChoice {
    /// Python `None` — no directive.
    None,
    /// Python `False` (or `[False, …]`) — `<channel>=default`.
    Default,
    /// Python `[cterm, hex]` tuple.
    Spec(ColorSpec),
}

fn classify_color(v: &Value) -> ColorChoice {
    match v {
        Value::Null => ColorChoice::None,
        Value::Bool(false) => ColorChoice::Default,
        Value::Bool(true) => ColorChoice::Default,
        Value::Array(arr) => {
            // Python `[False, …]` is the array form of the default sentinel.
            if matches!(arr.first(), Some(Value::Bool(false))) {
                return ColorChoice::Default;
            }
            let cterm = arr.first().and_then(|x| x.as_u64()).unwrap_or(0) as u16;
            let truecolor = arr.get(1).and_then(|x| x.as_u64()).map(|n| n as u32);
            ColorChoice::Spec(ColorSpec { cterm, truecolor })
        }
        _ => ColorChoice::None,
    }
}

/// Classify a `Value`-encoded `attrs` field.
/// - `Value::Null` → no `attrs` directive (Python `attrs is None`)
/// - `Value::Bool(_)` → Python `False` sentinel: emit all "no-" resets
/// - integer → standard bit field
enum AttrsChoice {
    /// Python `None` — no attrs directive at all.
    None,
    /// Python `False` — all-off ("nobold,noitalics,nounderscore").
    AllOff,
    /// Standard bit field (matches `get_attrs_flag` output).
    Flag(u32),
}

fn classify_attrs(v: &Value) -> AttrsChoice {
    match v {
        Value::Null => AttrsChoice::None,
        Value::Bool(_) => AttrsChoice::AllOff,
        _ => match v.as_u64() {
            Some(n) => AttrsChoice::Flag(n as u32),
            None => AttrsChoice::None,
        },
    }
}

/// Build the Python-faithful `#[…]` tag for the given fg/bg/attrs.
/// Mirrors `TmuxRenderer.hlstyle` at `powerline/renderers/tmux.py:40`
/// exactly, including the early-exit "if not attrs and not bg and not
/// fg: return ''" check and the three-state fg/bg semantics. Used by
/// both the `hl_fn` and `hlstyle_fn` closures so the bin shim emits
/// byte-for-byte parity with upstream Python.
fn render_hlstyle(tmux: &TmuxRenderer, fg: &Value, bg: &Value, attrs: &Value) -> String {
    let fc = classify_color(fg);
    let bc = classify_color(bg);
    let ac = classify_attrs(attrs);

    // py:44  if not attrs and not bg and not fg: return ''
    let attrs_empty = matches!(ac, AttrsChoice::None);
    let bg_empty = matches!(bc, ColorChoice::None);
    let fg_empty = matches!(fc, ColorChoice::None);
    if attrs_empty && bg_empty && fg_empty {
        return String::new();
    }

    let mut parts: Vec<String> = Vec::new();
    // py:47-54  fg branch — Python `if term_truecolor and fg[1]:`
    // includes the implicit truthiness check on the hex value, so
    // `hex == 0` (e.g. pure black 0x000000) falls back to cterm.
    match fc {
        ColorChoice::None => {}
        ColorChoice::Default => parts.push("fg=default".into()),
        ColorChoice::Spec(spec) => {
            if tmux.term_truecolor && spec.truecolor.filter(|&n| n != 0).is_some() {
                parts.push(format!("fg=#{:06x}", spec.truecolor.unwrap()));
            } else {
                parts.push(format!("fg=colour{}", spec.cterm));
            }
        }
    }
    // py:55-62  bg branch — same truthiness rule on bg[1].
    match bc {
        ColorChoice::None => {}
        ColorChoice::Default => parts.push("bg=default".into()),
        ColorChoice::Spec(spec) => {
            if tmux.term_truecolor && spec.truecolor.filter(|&n| n != 0).is_some() {
                parts.push(format!("bg=#{:06x}", spec.truecolor.unwrap()));
            } else {
                parts.push(format!("bg=colour{}", spec.cterm));
            }
        }
    }
    // py:63-64  attrs branch
    match ac {
        AttrsChoice::None => {}
        AttrsChoice::AllOff => parts.extend(
            powerliners::ported::renderers::tmux::attrs_to_tmux_attrs(None),
        ),
        AttrsChoice::Flag(flag) => parts.extend(
            powerliners::ported::renderers::tmux::attrs_to_tmux_attrs(Some(flag)),
        ),
    }
    // py:65  return '#[' + ','.join(tmux_attrs) + ']'
    format!("#[{}]", parts.join(","))
}

fn main() {
    let argv: Vec<String> = std::env::args().skip(1).collect();

    // One slot per ext — the daemon caches keyed by PowerlineKey but
    // the configs themselves only depend on `ext`. Lazy-load on first
    // request, then reuse for the daemon's lifetime.
    let store: Arc<Mutex<HashMap<String, Configs>>> = Arc::new(Mutex::new(HashMap::new()));
    let mut renderer_inner = Renderer::new(Map::new(), Map::new(), 1);
    // Wire TmuxRenderer.character_translations onto the base renderer
    // so `Renderer::escape` performs the `#` → `##[]` substitution
    // upstream Python `class TmuxRenderer(Renderer): character_translations
    // = Renderer.character_translations.copy(); ct[ord('#')] = '##['`
    // (powerline/renderers/tmux.py:30-31) installs at class-load time.
    for (ch, replacement) in TmuxRenderer::character_translations() {
        renderer_inner
            .character_translations
            .insert(ch, replacement.to_string());
    }
    let renderer = Arc::new(renderer_inner);

    let store_clone = store.clone();
    let renderer_clone = renderer.clone();
    let render_fn: Arc<RenderFn> = Arc::new(move |args, environ, cwd, _is_daemon| {
        let ext = args.ext.first().cloned().unwrap_or_default();
        let side = args.side.clone().unwrap_or_default();

        let configs = {
            let mut guard = store_clone.lock().expect("config store poisoned");
            // py:851-866  update_renderer's reload-check: when any
            // tracked config file's mtime differs vs the cached load,
            // drop the cache so build_configs re-reads from disk.
            // Honors `common.reload_config` (default true).
            let cached = guard.get(&ext).cloned();
            let stale = cached.as_ref().map(|c| c.is_stale()).unwrap_or(false);
            if stale {
                guard.remove(&ext);
            }
            match (cached, stale) {
                (Some(c), false) => c,
                _ => match build_configs(&ext) {
                    Ok(c) => {
                        guard.insert(ext.clone(), c.clone());
                        c
                    }
                    Err(e) => {
                        return format!("powerline-daemon: config error: {}\n", e).into_bytes()
                    }
                },
            }
        };

        // Build segment_info from the wire request.
        let mut environ_map: Map<String, Value> = Map::new();
        for (k, v) in environ {
            environ_map.insert(k.clone(), Value::String(v.clone()));
        }
        let mut segment_info: Map<String, Value> = Map::new();
        segment_info.insert("environ".to_string(), Value::Object(environ_map));
        segment_info.insert(
            "home".to_string(),
            Value::String(environ.get("HOME").cloned().unwrap_or_default()),
        );
        segment_info.insert("getcwd".to_string(), Value::String(cwd.to_string()));
        // Shell-segment fields per `develop/segments.rst` segment_info
        // contract: `args` carries the parsed Args fields (jobnum,
        // last_exit_code, last_pipe_status) that shell adapters
        // (jobnum, last_status, last_pipe_status, mode) read.
        let mut args_map: Map<String, Value> = Map::new();
        if let Some(j) = args.jobnum {
            args_map.insert("jobnum".to_string(), Value::from(j));
        }
        if let Some(ec) = args.last_exit_code.as_ref() {
            args_map.insert(
                "last_exit_code".to_string(),
                match ec {
                    powerliners::ported::commands::main::IntOrSig::Int(n) => Value::from(*n),
                    powerliners::ported::commands::main::IntOrSig::Sig(s) => {
                        Value::String(s.clone())
                    }
                },
            );
        }
        if !args.last_pipe_status.is_empty() {
            let arr: Vec<Value> = args
                .last_pipe_status
                .iter()
                .map(|v| match v {
                    powerliners::ported::commands::main::IntOrSig::Int(n) => Value::from(*n),
                    powerliners::ported::commands::main::IntOrSig::Sig(s) => {
                        Value::String(s.clone())
                    }
                })
                .collect();
            args_map.insert("last_pipe_status".to_string(), Value::Array(arr));
        }
        segment_info.insert("args".to_string(), Value::Object(args_map));

        // Pick up the per-config TmuxRenderer so the truecolor flag
        // from common.term_truecolor drives the hex-vs-cterm branch.
        let tmux_for_hl = configs.tmux.clone();
        let tmux_for_hlstyle = configs.tmux.clone();
        let hl_fn = move |contents: Option<&str>,
                          fg: &Value,
                          bg: &Value,
                          attrs: &Value,
                          _hl_args: &Map<String, Value>|
              -> String {
            // py:600-606  return self.hlstyle(fg, bg, attrs, **kwargs) + (contents or '')
            let style = render_hlstyle(&tmux_for_hl, fg, bg, attrs);
            format!("{}{}", style, contents.unwrap_or(""))
        };
        let hlstyle_fn =
            move |fg: &Value, bg: &Value, attrs: &Value, _hl_args: &Map<String, Value>| -> String {
                render_hlstyle(&tmux_for_hlstyle, fg, bg, attrs)
            };

        let contents_func = |id: &str,
                             _pl: &(),
                             si: &Map<String, Value>,
                             args: &Map<String, Value>|
         -> Option<Value> { invoke_adapter(id, args, si) };

        // Mode extraction: Python pulls it from `args.renderer_arg["mode"]`
        // before passing to `Renderer.render`. Mirrors
        // `commands/main.py:170-189` `write_output`'s segment_info update
        // and the explicit `mode=segment_info.get('mode', None)` at
        // py:177/188.
        let mode_owned: Option<String> = args
            .renderer_arg_merged
            .as_ref()
            .and_then(|m| m.get("mode"))
            .and_then(|v| v.as_str())
            .map(String::from);
        let mode_ref: Option<&str> = mode_owned.as_deref();
        let result = renderer_clone.render(
            mode_ref,
            args.width.map(|w| w as usize),
            if side.is_empty() { None } else { Some(&side) },
            0,
            false,
            false,
            Some(segment_info),
            None,
            None,
            &configs.theme,
            &configs.colorscheme,
            &contents_func,
            &hlstyle_fn,
            &hl_fn,
        );

        match result {
            RenderReturn::Plain(s) => s.into_bytes(),
            RenderReturn::Tuple { highlighted, .. } => highlighted.into_bytes(),
        }
    });
    let spawn_wm_fn: Arc<SpawnWmFn> = Arc::new(|_name, _t_evt, _pl_evt| None);
    let code = daemon::main(&argv, render_fn, spawn_wm_fn);
    std::process::exit(code);
}