zinit 0.3.9

Process supervisor with dependency management
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
//! Zinit RPC Client with Modern Factory and Builder Patterns
//!
//! This module provides a complete client library for the Zinit process supervisor.
//! It features:
//!
//! - **Factory Pattern**: Configure and connect via fluent API
//! - **Log Levels**: Automatic logging with configurable verbosity (0-3)
//! - **Builder Pattern**: Easy service configuration with sensible defaults
//! - **Type Safety**: Full type definitions for all service configurations
//! - **Async/Sync**: Both async client and synchronous handle wrapper
//!
//! ## Quick Start
//!
//! ```no_run
//! use zinit::ZinitHandle;
//!
//! // Connect and list services
//! let z = ZinitHandle::new()?;
//! let services = z.list()?;
//! println!("Services: {:?}", services);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Complete Example: Service Lifecycle Management
//!
//! Here's a complete example showing service creation, management, and cleanup:
//!
//! ```no_run
//! use zinit::{ZinitHandle, client::client::ServiceConfigBuilder};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Connect to the server
//!     let z = ZinitHandle::new()?;
//!
//!     println!("=== Service Lifecycle Management ===\n");
//!
//!     // 1. Create a service using the builder pattern
//!     println!("1. Creating web_server service...");
//!     let config = ServiceConfigBuilder::new("web_server")
//!         .exec("/app/server")
//!         .dir("/app")
//!         .env("PORT", "8000")
//!         .env("ENV", "production")
//!         .restart("on-failure")
//!         .restart_delay_ms(5000)
//!         .max_restarts(5)
//!         .critical(false)
//!         .health_http("http://localhost:8000/health")
//!         .log_buffer_lines(10000)
//!         .log_file("/var/log/web_server.log")
//!         .build();
//!
//!     z.service_set(config)?;  // Automatic logging: ✓ Created: web_server
//!
//!     // 2. List all services
//!     println!("\n2. Listing all services...");
//!     let services = z.list()?;
//!     for service in &services {
//!         println!("   - {}", service);
//!     }
//!
//!     // 3. Get detailed status
//!     println!("\n3. Service status...");
//!     let status = z.status("web_server")?;
//!     println!("   State: {:?}", status.state);
//!     println!("   PID: {:?}", status.pid);
//!
//!     // 4. Start the service
//!     println!("\n4. Starting service...");
//!     z.start("web_server")?;  // Automatic logging: ✓ Started: web_server
//!
//!     // 5. Check logs
//!     println!("\n5. Retrieving logs...");
//!     let logs = z.logs_tail(Some("web_server"), Some(5))?;
//!     for (i, log) in logs.iter().enumerate() {
//!         println!("   [{}] {}", i, log.content);
//!     }
//!
//!     // 6. Restart the service
//!     println!("\n6. Restarting service...");
//!     z.restart("web_server")?;  // Automatic logging: ✓ Restarted: web_server
//!
//!     // 7. Stop the service
//!     println!("\n7. Stopping service...");
//!     z.stop("web_server")?;  // Automatic logging: ✓ Stopped: web_server
//!
//!     // 8. Delete the service
//!     println!("\n8. Deleting service...");
//!     z.service_delete("web_server")?;  // Automatic logging: ✓ Deleted: web_server
//!
//!     println!("\n✓ Complete!");
//!     Ok(())
//! }
//! ```
//!
//! ## Factory Pattern with Logging
//!
//! ```no_run
//! use zinit::client::client::ZinitClientBuilder;
//!
//! let client = ZinitClientBuilder::new()
//!     .socket("/run/zinit/zinit.sock")
//!     .build()?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Service Builder with All Options
//!
//! ```
//! use zinit::client::client::ServiceConfigBuilder;
//!
//! let config = ServiceConfigBuilder::new("database")
//!     // Basic configuration
//!     .exec("postgres -D /var/lib/postgres")
//!     .dir("/var/lib/postgres")
//!
//!     // Environment variables
//!     .env("PGDATA", "/var/lib/postgres")
//!
//!     // Dependencies
//!     .requires("filesystem")
//!     .after("network")
//!
//!     // Restart policy
//!     .restart("on-failure")
//!     .restart_delay_ms(5000)
//!     .max_restarts(5)
//!
//!     // Health monitoring
//!     .health_tcp("127.0.0.1:5432")
//!
//!     // Port declaration (checked for conflicts)
//!     .port(5432)
//!
//!     // Logging
//!     .log_buffer_lines(5000)
//!     .log_file("/var/log/postgres.log")
//!
//!     .build();
//!
//! // Config is ready to send to server
//! assert_eq!(config.service.name, "database");
//! assert!(config.service.ports.contains(&5432));
//! ```
//!
//! ## Log Levels Explained
//!
//! The client supports configurable logging levels:
//! - **Silent (0)**: No output
//! - **Minimal (1)**: Connection status only
//! - **Normal (2)**: Operations and status updates (default)
//! - **Verbose (3)**: Detailed output including all operations
//!
//! Automatic output example with Normal logging:
//! ```text
//! ✓ Connected to zinit server
//! ✓ Created: web_server
//! ✓ Started: web_server
//! ✓ Stopped: web_server
//! ✓ Deleted: web_server
//! ```
//!
//! ## Connection Options
//!
//! Connects to zinit server via Unix socket or TCP:
//!
//! ```no_run
//! use zinit::client::client::ZinitClient;
//!
//! // Unix socket (default)
//! let client = ZinitClient::unix("/run/zinit/zinit.sock");
//!
//! // TCP connection
//! let client = ZinitClient::tcp("127.0.0.1:5555");
//!
//! // Default socket (auto-detected)
//! let client = ZinitClient::try_default()?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Error Handling
//!
//! ```no_run
//! use zinit::ZinitHandle;
//!
//! match ZinitHandle::new() {
//!     Ok(z) => {
//!         match z.list() {
//!             Ok(services) => println!("Services: {:?}", services),
//!             Err(e) => eprintln!("Failed to list services: {}", e),
//!         }
//!     }
//!     Err(e) => {
//!         eprintln!("Failed to connect: {}", e);
//!         eprintln!("Please start zinit server");
//!     }
//! }
//! ```
//!
//! Based on the zinit_mos SDK types and API.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpStream, UnixStream};
use tokio::time::timeout;

// Note: This module defines its own versions of SDK types for wire protocol compatibility.
// These definitions mirror the SDK types exactly and are used for JSON serialization/deserialization.

/// JSON-RPC Request
#[derive(Debug, Serialize)]
struct RpcRequest {
    jsonrpc: &'static str,
    method: String,
    params: Value,
    id: u64,
}

/// JSON-RPC Response
#[derive(Debug, Deserialize)]
struct RpcResponse {
    #[allow(dead_code)]
    jsonrpc: String,
    result: Option<Value>,
    error: Option<RpcError>,
    #[allow(dead_code)]
    id: Value,
}

/// JSON-RPC Error
#[derive(Debug, Deserialize)]
struct RpcError {
    #[allow(dead_code)]
    code: i32,
    message: String,
}

// ============================================================================
// Service State Types (matching zinit_mos SDK)
// ============================================================================

/// Service state enum - the 7 explicit states a service can be in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum State {
    /// Service has never been started.
    Inactive,
    /// Service is waiting on dependencies.
    Blocked,
    /// Process has been spawned, waiting for health check or startup.
    Starting,
    /// Process is running and healthy.
    Running,
    /// SIGTERM sent, waiting for process to exit.
    Stopping,
    /// Process exited cleanly.
    Exited,
    /// Process failed.
    Failed,
}

impl State {
    /// Check if this state represents a running process.
    pub fn is_running(&self) -> bool {
        matches!(self, State::Running)
    }

    /// Check if this state has an active process.
    pub fn is_active(&self) -> bool {
        matches!(self, State::Starting | State::Running | State::Stopping)
    }
}

impl std::fmt::Display for State {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            State::Inactive => write!(f, "inactive"),
            State::Blocked => write!(f, "blocked"),
            State::Starting => write!(f, "starting"),
            State::Running => write!(f, "running"),
            State::Stopping => write!(f, "stopping"),
            State::Exited => write!(f, "exited"),
            State::Failed => write!(f, "failed"),
        }
    }
}

impl Default for State {
    fn default() -> Self {
        State::Inactive
    }
}

// ============================================================================
// Service Configuration Types (matching zinit_mos SDK config.rs)
// ============================================================================

/// Complete service configuration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceConfig {
    pub service: ServiceDef,
    #[serde(default)]
    pub dependencies: DependencyDef,
    #[serde(default)]
    pub lifecycle: LifecycleDef,
    #[serde(default)]
    pub health: Option<HealthDef>,
    #[serde(default)]
    pub logging: LoggingDef,
}

impl ServiceConfig {
    /// Parse a service configuration from a TOML string.
    pub fn parse(content: &str) -> Result<Self> {
        toml::from_str(content).context("Failed to parse service config")
    }

    /// Serialize to TOML string.
    pub fn to_toml(&self) -> Result<String> {
        toml::to_string_pretty(self).context("Failed to serialize service config")
    }
}

/// Service definition section.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceDef {
    pub name: String,
    pub exec: String,
    #[serde(default)]
    pub dir: Option<String>,
    #[serde(default)]
    pub oneshot: bool,
    #[serde(default)]
    pub env: HashMap<String, String>,
    /// Desired status: start (default), stop, or ignore.
    #[serde(default)]
    pub status: Status,
    /// Service class: user (default) or system.
    #[serde(default)]
    pub class: ServiceClass,
    /// If true, failure triggers emergency shell (PID1 mode only).
    #[serde(default)]
    pub critical: bool,
    /// TCP ports used by this service (checked for conflicts on startup).
    #[serde(default)]
    pub ports: Vec<u16>,
    /// If true, kill other processes using declared ports before starting this service.
    #[serde(default)]
    pub kill_others: bool,
    /// Process name filters for conflict detection (case-insensitive partial match).
    #[serde(default)]
    pub process_filters: Vec<String>,
}

impl Default for ServiceDef {
    fn default() -> Self {
        Self {
            name: String::new(),
            exec: String::new(),
            dir: None,
            oneshot: false,
            env: HashMap::new(),
            status: Status::default(),
            class: ServiceClass::default(),
            critical: false,
            ports: Vec::new(),
            kill_others: false,
            process_filters: Vec::new(),
        }
    }
}

/// Desired status of a service - what the supervisor should enforce.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    /// Supervisor ensures service is running (default).
    #[default]
    Start,
    /// Supervisor ensures service is stopped.
    Stop,
    /// Supervisor doesn't manage service state (manual control only).
    Ignore,
}

impl Status {
    /// Returns true if the service should be auto-started.
    pub fn should_autostart(&self) -> bool {
        matches!(self, Status::Start)
    }
}

/// Service class - determines protection level and behavior.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ServiceClass {
    /// User service (default) - affected by bulk operations (*_all).
    #[default]
    User,
    /// System service - protected from bulk operations.
    System,
}

impl ServiceClass {
    /// Returns true if this is a system service (protected).
    pub fn is_system(&self) -> bool {
        matches!(self, ServiceClass::System)
    }
}

/// Builder for creating ServiceConfig with fluent API.
///
/// Example:
/// ```no_run
/// use zinit::client::client::ServiceConfigBuilder;
///
/// let config = ServiceConfigBuilder::new("my_service")
///     .exec("python3 /app/main.py")
///     .restart("on-failure")
///     .health_tcp("127.0.0.1:8000")
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct ServiceConfigBuilder {
    service: ServiceDef,
    dependencies: DependencyDef,
    lifecycle: LifecycleDef,
    health: Option<HealthDef>,
    logging: LoggingDef,
}

impl ServiceConfigBuilder {
    /// Create a new service configuration builder.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            service: ServiceDef {
                name: name.into(),
                exec: String::new(),
                dir: None,
                oneshot: false,
                env: HashMap::new(),
                status: Status::Start,
                class: ServiceClass::default(),
                critical: false,
                ports: Vec::new(),
                kill_others: false,
                process_filters: Vec::new(),
            },
            dependencies: DependencyDef::default(),
            lifecycle: LifecycleDef::default(),
            health: None,
            logging: LoggingDef::default(),
        }
    }

    /// Set the command to execute.
    pub fn exec(mut self, exec: impl Into<String>) -> Self {
        self.service.exec = exec.into();
        self
    }

    /// Set the working directory.
    pub fn dir(mut self, dir: impl Into<String>) -> Self {
        self.service.dir = Some(dir.into());
        self
    }

    /// Mark service as oneshot (runs once and exits).
    pub fn oneshot(mut self, oneshot: bool) -> Self {
        self.service.oneshot = oneshot;
        self
    }

    /// Add an environment variable.
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.service.env.insert(key.into(), value.into());
        self
    }

    /// Set the service status (Start, Stop, or Ignore).
    pub fn status(mut self, status: Status) -> Self {
        self.service.status = status;
        self
    }

    /// Set the service class (User or System).
    pub fn class(mut self, class: ServiceClass) -> Self {
        self.service.class = class;
        self
    }

    /// Mark as critical service (PID1 mode only).
    pub fn critical(mut self, critical: bool) -> Self {
        self.service.critical = critical;
        self
    }

    /// Add dependency: service must start after this.
    pub fn after(mut self, service: impl Into<String>) -> Self {
        self.dependencies.after.push(service.into());
        self
    }

    /// Add hard dependency: service must be running.
    pub fn requires(mut self, service: impl Into<String>) -> Self {
        self.dependencies.requires.push(service.into());
        self
    }

    /// Add soft dependency: try to start but don't fail if missing.
    pub fn wants(mut self, service: impl Into<String>) -> Self {
        self.dependencies.wants.push(service.into());
        self
    }

    /// Add conflicting service: cannot run together.
    pub fn conflicts(mut self, service: impl Into<String>) -> Self {
        self.dependencies.conflicts.push(service.into());
        self
    }

    /// Set restart policy: "always", "on-failure", or "never".
    pub fn restart(mut self, policy: impl Into<String>) -> Self {
        let policy_str = policy.into().to_lowercase();
        self.lifecycle.restart = match policy_str.as_str() {
            "always" => RestartPolicy::Always,
            "never" => RestartPolicy::Never,
            _ => RestartPolicy::OnFailure,
        };
        self
    }

    /// Set restart delay in milliseconds.
    pub fn restart_delay_ms(mut self, ms: u64) -> Self {
        self.lifecycle.restart_delay_ms = ms;
        self
    }

    /// Set maximum number of restarts.
    pub fn max_restarts(mut self, count: u32) -> Self {
        self.lifecycle.max_restarts = count;
        self
    }

    /// Set TCP health check.
    pub fn health_tcp(mut self, target: impl Into<String>) -> Self {
        self.health = Some(HealthDef::Tcp {
            target: target.into(),
            common: Default::default(),
        });
        self
    }

    /// Set HTTP health check.
    pub fn health_http(mut self, target: impl Into<String>) -> Self {
        self.health = Some(HealthDef::Http {
            target: target.into(),
            expect_status: 200,
            common: Default::default(),
        });
        self
    }

    /// Set health check interval in milliseconds.
    pub fn health_interval_ms(self, _ms: u64) -> Self {
        // Note: interval configuration would require more complex updates
        // to preserve the existing health config. This is a placeholder.
        self
    }

    /// Set log buffer size in lines.
    pub fn log_buffer_lines(mut self, lines: usize) -> Self {
        self.logging.buffer_lines = lines;
        self
    }

    /// Set log file path.
    pub fn log_file(mut self, path: impl Into<String>) -> Self {
        self.logging.file = Some(path.into());
        self
    }

    /// Add a TCP port used by this service (can be called multiple times).
    /// When service starts, zinit checks if port is already in use by another service.
    pub fn port(mut self, port: u16) -> Self {
        self.service.ports.push(port);
        self
    }

    /// Enable kill_others mode - kill processes using declared ports before starting.
    /// When enabled, any external processes using the declared ports will be terminated
    /// (including their child processes) before this service starts.
    pub fn kill_others(mut self) -> Self {
        self.service.kill_others = true;
        self
    }

    /// Add a process name filter for conflict detection.
    ///
    /// Before starting, zinit will check if any process with a name
    /// containing this substring is running. If found, the service
    /// will be blocked unless `kill_others` is enabled.
    /// Can be called multiple times to add multiple filters.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let mut builder = ServiceConfigBuilder::new("myservice");
    /// builder.process_filter("nginx");  // Matches "nginx", "nginx-worker", etc.
    /// builder.process_filter("Server"); // Matches "myServer", "TestServer", etc.
    /// builder.process_filter("python"); // Multiple filters supported
    /// ```
    pub fn process_filter(mut self, filter: impl Into<String>) -> Self {
        self.service.process_filters.push(filter.into());
        self
    }

    /// Build the final ServiceConfig.
    pub fn build(self) -> ServiceConfig {
        ServiceConfig {
            service: self.service,
            dependencies: self.dependencies,
            lifecycle: self.lifecycle,
            health: self.health,
            logging: self.logging,
        }
    }
}

/// Dependency definition section.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct DependencyDef {
    /// Services that must start before this one (ordering only).
    #[serde(default)]
    pub after: Vec<String>,
    /// Services that must be running for this to start (hard dependency).
    #[serde(default)]
    pub requires: Vec<String>,
    /// Services that should be running if available (soft dependency).
    #[serde(default)]
    pub wants: Vec<String>,
    /// Services that cannot run at the same time.
    #[serde(default)]
    pub conflicts: Vec<String>,
}

/// Lifecycle configuration section.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LifecycleDef {
    #[serde(default = "default_restart_policy")]
    pub restart: RestartPolicy,
    /// Initial restart delay in milliseconds.
    #[serde(default = "default_restart_delay_ms")]
    pub restart_delay_ms: u64,
    /// Maximum restart delay in milliseconds.
    #[serde(default = "default_restart_delay_max_ms")]
    pub restart_delay_max_ms: u64,
    /// Maximum number of restart attempts (0 = unlimited).
    #[serde(default = "default_max_restarts")]
    pub max_restarts: u32,
    /// How long a service must run before backoff counter is reset.
    #[serde(default = "default_stability_period_ms")]
    pub stability_period_ms: u64,
    #[serde(default = "default_start_timeout_ms")]
    pub start_timeout_ms: u64,
    #[serde(default = "default_stop_timeout_ms")]
    pub stop_timeout_ms: u64,
    #[serde(default = "default_stop_signal")]
    pub stop_signal: String,
}

impl Default for LifecycleDef {
    fn default() -> Self {
        Self {
            restart: default_restart_policy(),
            restart_delay_ms: default_restart_delay_ms(),
            restart_delay_max_ms: default_restart_delay_max_ms(),
            max_restarts: default_max_restarts(),
            stability_period_ms: default_stability_period_ms(),
            start_timeout_ms: default_start_timeout_ms(),
            stop_timeout_ms: default_stop_timeout_ms(),
            stop_signal: default_stop_signal(),
        }
    }
}

fn default_restart_policy() -> RestartPolicy {
    RestartPolicy::OnFailure
}

fn default_restart_delay_ms() -> u64 {
    1000
}

fn default_restart_delay_max_ms() -> u64 {
    300000
}

fn default_max_restarts() -> u32 {
    10
}

fn default_stability_period_ms() -> u64 {
    30000
}

fn default_start_timeout_ms() -> u64 {
    30000
}

fn default_stop_timeout_ms() -> u64 {
    10000
}

fn default_stop_signal() -> String {
    "SIGTERM".to_string()
}

/// Restart policy for a service.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RestartPolicy {
    /// Always restart the service when it exits.
    Always,
    /// Only restart if the service exits with failure.
    #[default]
    OnFailure,
    /// Never restart the service.
    Never,
}

/// Health check definition (tagged enum).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum HealthDef {
    /// TCP connection health check.
    Tcp {
        target: String,
        #[serde(flatten)]
        common: HealthCommon,
    },
    /// HTTP health check.
    Http {
        target: String,
        #[serde(default = "default_http_status")]
        expect_status: u16,
        #[serde(flatten)]
        common: HealthCommon,
    },
    /// Command execution health check.
    Exec {
        target: String,
        #[serde(flatten)]
        common: HealthCommon,
    },
}

fn default_http_status() -> u16 {
    200
}

/// Common health check parameters.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HealthCommon {
    #[serde(default = "default_health_interval_ms")]
    pub interval_ms: u64,
    #[serde(default = "default_health_timeout_ms")]
    pub timeout_ms: u64,
    #[serde(default = "default_health_retries")]
    pub retries: u32,
    #[serde(default = "default_health_start_period_ms")]
    pub start_period_ms: u64,
}

impl Default for HealthCommon {
    fn default() -> Self {
        Self {
            interval_ms: default_health_interval_ms(),
            timeout_ms: default_health_timeout_ms(),
            retries: default_health_retries(),
            start_period_ms: default_health_start_period_ms(),
        }
    }
}

fn default_health_interval_ms() -> u64 {
    10000
}

fn default_health_timeout_ms() -> u64 {
    5000
}

fn default_health_retries() -> u32 {
    3
}

fn default_health_start_period_ms() -> u64 {
    0
}

/// Logging configuration section.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LoggingDef {
    #[serde(default = "default_buffer_lines")]
    pub buffer_lines: usize,
    #[serde(default)]
    pub file: Option<String>,
    #[serde(default)]
    pub forward: Option<String>,
}

impl Default for LoggingDef {
    fn default() -> Self {
        Self {
            buffer_lines: default_buffer_lines(),
            file: None,
            forward: None,
        }
    }
}

fn default_buffer_lines() -> usize {
    1000
}

// ============================================================================
// Response Types (matching zinit_mos SDK responses.rs)
// ============================================================================

/// Service status returned by service.status.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceStatus {
    pub name: String,
    /// State as enum (serializes as lowercase string).
    pub state: State,
    /// Process ID (0 if not running).
    #[serde(default)]
    pub pid: u32,
    /// Last exit code (if exited or failed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    /// Error message (if failed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Service resource usage statistics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceStats {
    pub pid: u32,
    pub memory_bytes: u64,
    pub cpu_percent: f32,
}

/// Ping response from the server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PingResponse {
    pub version: String,
}

/// Response explaining why a service is blocked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WhyBlocked {
    pub name: String,
    pub blocked: bool,
    pub waiting_on: Vec<String>,
    pub conflicts_with: Vec<String>,
    /// Port conflict reason if blocked due to port in use
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub port_conflict: Option<String>,
    /// Process filter conflict if blocked due to matching process
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub process_conflict: Option<ProcessConflictDetails>,
    pub ascii: String,
}

/// Process conflict details in WhyBlocked response
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProcessConflictDetails {
    pub filter: String,
    pub processes: Vec<ProcessConflictInfo>,
}

/// Information about a conflicting process
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProcessConflictInfo {
    pub pid: u32,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cmdline: Option<String>,
}

/// Response for dependency tree.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TreeResponse {
    pub ascii: String,
}

/// Result of prepare_restart operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrepareRestartResult {
    pub state_path: String,
    pub ready: bool,
}

/// Information about a child process.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChildProcessInfo {
    pub pid: u32,
    pub name: String,
    pub memory_bytes: u64,
}

/// Response containing child processes.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChildrenResponse {
    pub children: Vec<ChildProcessInfo>,
}

/// Structured log entry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LogLine {
    pub timestamp_ms: u64,
    pub service: String,
    pub stream: String,
    pub content: String,
}

/// Debug output response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DebugOutput {
    pub output: String,
}

/// Service info for list_full operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceInfo {
    pub name: String,
    pub state: ServiceState,
    pub is_target: bool,
}

/// Service state with associated data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "lowercase")]
pub enum ServiceState {
    Inactive,
    Blocked {
        #[serde(default)]
        waiting_on: Vec<String>,
    },
    Starting {
        pid: u32,
    },
    Running {
        pid: u32,
    },
    Stopping {
        pid: u32,
    },
    Exited {
        #[serde(default)]
        exit_code: Option<i32>,
    },
    Failed {
        reason: FailureReason,
    },
}

/// Reason why a service failed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FailureReason {
    ExitCode { code: i32 },
    Signal { signal: i32 },
    StartTimeout,
    StopTimeout,
    HealthCheckFailed { attempts: u32 },
    DependencyFailed { service: String },
    SpawnError { message: String },
    MissingDependency { dependency: String },
}

/// Dependency info for status_full.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DependencyInfo {
    pub name: String,
    pub dep_type: String,
    pub state: ServiceState,
    pub satisfied: bool,
}

/// Full service status with dependencies and uptime.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceStatusFull {
    pub name: String,
    pub state: ServiceState,
    pub is_target: bool,
    pub dependencies: Vec<DependencyInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uptime_secs: Option<u64>,
}

/// Xinet proxy definition for set operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct XinetDef {
    pub name: String,
    pub listen: Vec<SocketAddr>,
    pub backend: SocketAddr,
    pub service: String,
    #[serde(default = "default_connect_timeout")]
    pub connect_timeout: u64,
    #[serde(default)]
    pub idle_timeout: u64,
    #[serde(default)]
    pub single_connection: bool,
}

/// Xinet status (simplified).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct XinetStatus {
    pub name: String,
    pub running: bool,
    pub active_connections: usize,
}

/// Xinet status (full).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct XinetStatusFull {
    pub name: String,
    pub listen: String,
    pub backend: String,
    pub service: String,
    pub running: bool,
    pub total_connections: u64,
    pub active_connections: usize,
    pub bytes_to_backend: u64,
    pub bytes_from_backend: u64,
}

/// Result of service.add operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AddServiceResult {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(default)]
    pub warnings: Vec<String>,
}

// ============================================================================
// Xinet Types (matching zinit_mos SDK xinet.rs)
// ============================================================================

/// Socket address - either Unix socket or TCP.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum SocketAddr {
    /// Unix domain socket path.
    Unix(PathBuf),
    /// TCP address (host:port).
    Tcp(String),
}

impl SocketAddr {
    /// Create a Unix socket address.
    pub fn unix<P: Into<PathBuf>>(path: P) -> Self {
        SocketAddr::Unix(path.into())
    }

    /// Create a TCP socket address.
    pub fn tcp<S: Into<String>>(addr: S) -> Self {
        SocketAddr::Tcp(addr.into())
    }

    /// Check if this is a Unix socket.
    pub fn is_unix(&self) -> bool {
        matches!(self, SocketAddr::Unix(_))
    }

    /// Check if this is a TCP socket.
    pub fn is_tcp(&self) -> bool {
        matches!(self, SocketAddr::Tcp(_))
    }
}

impl std::fmt::Display for SocketAddr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SocketAddr::Unix(p) => write!(f, "unix:{}", p.display()),
            SocketAddr::Tcp(a) => write!(f, "tcp:{}", a),
        }
    }
}

/// Configuration for a single xinet proxy.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct XinetConfig {
    /// Name of this proxy.
    pub name: String,
    /// Frontend sockets to listen on.
    pub listen: Vec<SocketAddr>,
    /// Backend socket to connect to.
    pub backend: SocketAddr,
    /// Zinit service name that provides the backend.
    pub service: String,
    /// Timeout in seconds to wait for backend socket after starting service.
    #[serde(default = "default_connect_timeout")]
    pub connect_timeout: u64,
    /// Idle timeout in seconds - stop service if no connections for this long.
    #[serde(default)]
    pub idle_timeout: u64,
    /// Whether to allow only one connection at a time.
    #[serde(default)]
    pub single_connection: bool,
}

fn default_connect_timeout() -> u64 {
    30
}

impl XinetConfig {
    /// Create a new xinet configuration with a single listener.
    pub fn new<S: Into<String>>(
        name: S,
        listen: SocketAddr,
        backend: SocketAddr,
        service: S,
    ) -> Self {
        Self {
            name: name.into(),
            listen: vec![listen],
            backend,
            service: service.into(),
            connect_timeout: default_connect_timeout(),
            idle_timeout: 0,
            single_connection: false,
        }
    }

    /// Add a listener address.
    pub fn add_listen(mut self, addr: SocketAddr) -> Self {
        self.listen.push(addr);
        self
    }

    /// Set the connect timeout.
    pub fn with_connect_timeout(mut self, seconds: u64) -> Self {
        self.connect_timeout = seconds;
        self
    }

    /// Set the idle timeout.
    pub fn with_idle_timeout(mut self, seconds: u64) -> Self {
        self.idle_timeout = seconds;
        self
    }

    /// Enable single connection mode.
    pub fn with_single_connection(mut self, single: bool) -> Self {
        self.single_connection = single;
        self
    }

    /// Get all listen addresses as a formatted string.
    pub fn listen_addrs_string(&self) -> String {
        self.listen
            .iter()
            .map(|a| a.to_string())
            .collect::<Vec<_>>()
            .join(", ")
    }
}

// ============================================================================
// Socket Paths
// ============================================================================

/// System-wide socket path.
const SYSTEM_SOCKET: &str = "/run/zinit.sock";

/// User socket path suffix.
const USER_SOCKET_SUFFIX: &str = "hero/var/zinit.sock";

/// Get the default socket path.
pub fn get_socket_path() -> Result<PathBuf> {
    let system = PathBuf::from(SYSTEM_SOCKET);
    if system.exists() {
        return Ok(system);
    }

    let home = dirs::home_dir().context("Could not determine home directory")?;
    Ok(home.join(USER_SOCKET_SUFFIX))
}

/// Get the user configuration directory.
pub fn get_config_dir() -> PathBuf {
    if let Some(home) = dirs::home_dir() {
        home.join("hero/cfg/zinit")
    } else {
        PathBuf::from("/tmp/zinit/services")
    }
}

// ============================================================================
// Zinit Client Builder - Factory Pattern
// ============================================================================

/// Builder for creating configured Zinit clients.
///
/// Provides fluent API: ZinitClientBuilder::new()
///     .socket("/run/zinit.sock")
///     .log_level(3)
/// Builder for configuring and creating a [`ZinitClient`].
///
/// Provides a fluent API for constructing a client with custom configuration.
/// Uses sensible defaults for all options.
///
/// # Examples
///
/// ```no_run
/// use zinit::client::client::{ZinitClientBuilder, LogLevel};
///
/// // Basic usage
/// let client = ZinitClientBuilder::new()
///     .socket("/run/zinit/zinit.sock")
///     .log_level(2)
///     .build()?;
///
/// // With default socket
/// let client = ZinitClientBuilder::new()
///     .log_level(3)
///     .build()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Default Behavior
///
/// - **Socket**: Auto-detects system or user socket
/// - **Log Level**: Minimal (1) - connection status only
#[derive(Debug, Clone)]
pub struct ZinitClientBuilder {
    socket_path: Option<String>,
    log_level: u32,
}

impl ZinitClientBuilder {
    /// Create a new builder with defaults.
    ///
    /// Defaults:
    /// - Socket: Auto-detected (system or user directory)
    /// - Log Level: Minimal (1)
    pub fn new() -> Self {
        Self {
            socket_path: None,
            log_level: 1,
        }
    }

    /// Set the Unix socket path for connection.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the Unix socket file
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zinit::client::client::ZinitClientBuilder;
    ///
    /// let client = ZinitClientBuilder::new()
    ///     .socket("/run/zinit/zinit.sock")
    ///     .build()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn socket(mut self, path: &str) -> Self {
        self.socket_path = Some(path.to_string());
        self
    }

    /// Set the logging level (0-3, clamped to 3).
    ///
    /// - **0 (Silent)**: No output
    /// - **1 (Minimal)**: Connection status only
    /// - **2 (Normal)**: Operations and status updates
    /// - **3 (Verbose)**: Detailed output
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zinit::client::client::ZinitClientBuilder;
    ///
    /// let client = ZinitClientBuilder::new()
    ///     .log_level(3)  // Verbose
    ///     .build()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn log_level(mut self, level: u32) -> Self {
        self.log_level = level.min(3);
        self
    }

    /// Log a message if level is sufficient
    fn log(&self, message: &str, min_level: u32) {
        if self.log_level >= min_level {
            println!("{}", message);
        }
    }

    /// Build and return the configured client
    pub fn build(self) -> Result<ZinitClient> {
        let client = if let Some(path) = &self.socket_path {
            self.log(&format!("✓ Connecting to socket: {}", path), 1);
            ZinitClient::unix(path)
        } else {
            self.log("✓ Connecting to default socket", 1);
            ZinitClient::try_default()?
        };

        self.log("✓ Connected to zinit server", 1);
        Ok(client)
    }
}

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

// ============================================================================
// Zinit RPC Client
// ============================================================================

/// Zinit RPC client.
///
/// Provides async methods for communicating with the zinit server.
/// Log level for controlling output verbosity.
///
/// Controls how much output is printed to stdout during operations.
/// Operations log based on their importance and the configured level.
///
/// # Examples
///
/// ```rust
/// use zinit::client::client::LogLevel;
///
/// let silent = LogLevel::Silent;    // 0 - No output
/// let minimal = LogLevel::Minimal;  // 1 - Connection status only
/// let normal = LogLevel::Normal;    // 2 - Operations (default)
/// let verbose = LogLevel::Verbose;  // 3 - All details
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum LogLevel {
    /// Silent - no output at all
    Silent = 0,
    /// Minimal - only connection status and critical operations
    Minimal = 1,
    /// Normal - operations and status updates (default)
    Normal = 2,
    /// Verbose - detailed output including all operations
    Verbose = 3,
}

impl LogLevel {
    /// Log a message if the current level allows it
    pub fn log(&self, min_level: LogLevel, message: &str) {
        if *self >= min_level {
            println!("{}", message);
        }
    }
}

/// Asynchronous Zinit RPC client.
///
/// Provides async methods for communicating with the zinit server over
/// either Unix socket or TCP connections.
///
/// Use [`ZinitClientBuilder`] for convenient configuration, or [`ZinitHandle`]
/// for a synchronous blocking wrapper suitable for Rhai scripts.
///
/// # Examples
///
/// Using the builder pattern:
/// ```no_run
/// use zinit::client::client::ZinitClientBuilder;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ZinitClientBuilder::new()
///     .socket("/run/zinit/zinit.sock")
///     .log_level(2)  // LogLevel::Normal
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// Direct construction:
/// ```no_run
/// use zinit::client::client::ZinitClient;
///
/// let client = ZinitClient::try_default()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone)]
pub struct ZinitClient {
    addr: String,
    log_level: LogLevel,
}

impl ZinitClient {
    /// Connect via Unix socket.
    pub fn unix<P: AsRef<Path>>(path: P) -> Self {
        Self {
            addr: format!("unix:{}", path.as_ref().display()),
            log_level: LogLevel::Normal,
        }
    }

    /// Connect via TCP.
    pub fn tcp(addr: &str) -> Self {
        Self {
            addr: format!("tcp:{}", addr),
            log_level: LogLevel::Normal,
        }
    }

    /// Connect to default socket.
    pub fn try_default() -> Result<Self> {
        let socket_path = get_socket_path()?;
        Ok(Self::unix(socket_path))
    }

    /// Set the log level for this client
    pub fn with_log_level(mut self, level: LogLevel) -> Self {
        self.log_level = level;
        self
    }

    /// Get the current log level
    pub fn log_level(&self) -> LogLevel {
        self.log_level
    }

    /// Make an RPC call.
    async fn call<T: DeserializeOwned>(&self, method: &str, params: Value) -> Result<T> {
        let request = RpcRequest {
            jsonrpc: "2.0",
            method: method.to_string(),
            params,
            id: 1,
        };

        let request_json = serde_json::to_string(&request)? + "\n";
        let connect_timeout = Duration::from_secs(3);

        let response_json = if self.addr.starts_with("unix:") {
            let path = self.addr.trim_start_matches("unix:");
            let mut stream = timeout(connect_timeout, UnixStream::connect(path))
                .await
                .context("Connection to zinit server timed out (server not running?)")?
                .context("Failed to connect to Unix socket")?;

            stream.write_all(request_json.as_bytes()).await?;
            stream.flush().await?;

            let mut reader = BufReader::new(stream);
            let mut line = String::new();
            reader.read_line(&mut line).await?;
            line
        } else {
            let addr = self.addr.trim_start_matches("tcp:");
            let mut stream = timeout(connect_timeout, TcpStream::connect(addr))
                .await
                .context("Connection to zinit server timed out (server not running?)")?
                .context("Failed to connect to TCP")?;

            stream.write_all(request_json.as_bytes()).await?;
            stream.flush().await?;

            let mut reader = BufReader::new(stream);
            let mut line = String::new();
            reader.read_line(&mut line).await?;
            line
        };

        let response: RpcResponse =
            serde_json::from_str(&response_json).context("Failed to parse response")?;

        if let Some(error) = response.error {
            anyhow::bail!("{}", error.message);
        }

        let result = response.result.unwrap_or(Value::Null);
        serde_json::from_value(result).context("Failed to parse result")
    }

    // ============ RPC Methods ============

    /// Returns the OpenRPC specification.
    pub async fn discover(&self) -> Result<Value> {
        self.call("rpc.discover", Value::Null).await
    }

    // ============ System Methods ============

    /// Ping the server and get version info.
    pub async fn ping(&self) -> Result<PingResponse> {
        self.call("system.ping", Value::Null).await
    }

    /// Test connection to the zinit server by performing a ping.
    ///
    /// Returns `Ok(version)` if the connection is successful, or an error
    /// with a descriptive message if the connection fails.
    ///
    /// This method should be called after creating a client to verify
    /// the server is reachable and responding.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zinit::ZinitClient;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = ZinitClient::try_default()?;
    /// let version = client.test_connection().await?;
    /// println!("Connected to zinit server version: {}", version);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn test_connection(&self) -> Result<String> {
        self.ping()
            .await
            .map(|resp| resp.version)
            .map_err(|e| anyhow::anyhow!("Failed to connect to zinit server: {}", e))
    }

    /// Request daemon shutdown.
    pub async fn shutdown(&self) -> Result<()> {
        let _: Value = self.call("system.shutdown", Value::Null).await?;
        Ok(())
    }

    /// Reboot the system (Linux only, requires PID 1).
    pub async fn reboot(&self) -> Result<()> {
        let _: Value = self.call("system.reboot", Value::Null).await?;
        Ok(())
    }

    /// Prepare for hot restart by saving state to disk.
    pub async fn prepare_restart(&self) -> Result<PrepareRestartResult> {
        self.call("system.prepare_restart", Value::Null).await
    }

    // ============ Service Methods ============

    /// Create or update a service (always persisted).
    pub async fn service_set(&self, config: &ServiceConfig) -> Result<AddServiceResult> {
        self.call("service.set", json!({ "config": config })).await
    }

    /// Get service configuration.
    pub async fn service_get(&self, name: &str) -> Result<ServiceConfig> {
        self.call("service.get", json!({ "name": name })).await
    }

    /// Delete a service (stop and remove).
    pub async fn service_delete(&self, name: &str) -> Result<()> {
        let _: Value = self.call("service.delete", json!({ "name": name })).await?;
        Ok(())
    }

    /// List all service names.
    pub async fn list(&self) -> Result<Vec<String>> {
        self.call("service.list", Value::Null).await
    }

    /// List all services with state information.
    pub async fn list_full(&self) -> Result<Vec<ServiceInfo>> {
        self.call("service.list_full", Value::Null).await
    }

    /// Start a service.
    pub async fn start(&self, name: &str) -> Result<()> {
        let _: Value = self.call("service.start", json!({ "name": name })).await?;
        Ok(())
    }

    /// Stop a service.
    pub async fn stop(&self, name: &str) -> Result<()> {
        let _: Value = self.call("service.stop", json!({ "name": name })).await?;
        Ok(())
    }

    /// Restart a service.
    pub async fn restart(&self, name: &str) -> Result<()> {
        let _: Value = self
            .call("service.restart", json!({ "name": name }))
            .await?;
        Ok(())
    }

    /// Send a signal to a service.
    pub async fn kill(&self, name: &str, signal: Option<&str>) -> Result<()> {
        let params = match signal {
            Some(sig) => json!({ "name": name, "signal": sig }),
            None => json!({ "name": name }),
        };
        let _: Value = self.call("service.kill", params).await?;
        Ok(())
    }

    /// Get service status (simplified).
    pub async fn status(&self, name: &str) -> Result<ServiceStatus> {
        self.call("service.status", json!({ "name": name })).await
    }

    /// Get detailed service status with dependencies and uptime.
    pub async fn status_full(&self, name: &str) -> Result<ServiceStatusFull> {
        self.call("service.status_full", json!({ "name": name }))
            .await
    }

    /// Get CPU and memory statistics for a service.
    pub async fn stats(&self, name: &str) -> Result<ServiceStats> {
        self.call("service.stats", json!({ "name": name })).await
    }

    /// Get child processes for a service.
    pub async fn children(&self, name: &str) -> Result<ChildrenResponse> {
        self.call("service.children", json!({ "name": name })).await
    }

    /// Check if a service is currently running.
    pub async fn is_running(&self, name: &str) -> Result<bool> {
        self.call("service.is_running", json!({ "name": name }))
            .await
    }

    /// Explain why a service is blocked.
    pub async fn why(&self, name: &str) -> Result<WhyBlocked> {
        self.call("service.why", json!({ "name": name })).await
    }

    /// Get ASCII dependency tree visualization.
    pub async fn tree(&self) -> Result<String> {
        let tree: TreeResponse = self.call("service.tree", Value::Null).await?;
        Ok(tree.ascii)
    }

    // ============ Log Methods ============

    /// Get logs (simplified, returns strings).
    pub async fn logs(&self, name: Option<&str>, lines: Option<usize>) -> Result<Vec<String>> {
        let mut params = json!({});
        if let Some(n) = name {
            params["name"] = json!(n);
        }
        if let Some(l) = lines {
            params["lines"] = json!(l);
        }
        self.call("logs.get", params).await
    }

    /// Get structured log entries.
    pub async fn logs_tail(
        &self,
        name: Option<&str>,
        lines: Option<usize>,
    ) -> Result<Vec<LogLine>> {
        let mut params = json!({});
        if let Some(n) = name {
            params["name"] = json!(n);
        }
        if let Some(l) = lines {
            params["lines"] = json!(l);
        }
        self.call("logs.tail", params).await
    }

    /// Get filtered log entries.
    pub async fn logs_filter(
        &self,
        name: Option<&str>,
        stream: Option<&str>,
        since: Option<u64>,
        lines: Option<usize>,
    ) -> Result<Vec<LogLine>> {
        let mut params = json!({});
        if let Some(n) = name {
            params["name"] = json!(n);
        }
        if let Some(s) = stream {
            params["stream"] = json!(s);
        }
        if let Some(s) = since {
            params["since"] = json!(s);
        }
        if let Some(l) = lines {
            params["lines"] = json!(l);
        }
        self.call("logs.filter", params).await
    }

    // ============ Debug Methods ============

    /// Get full supervisor state for debugging.
    pub async fn debug_state(&self) -> Result<String> {
        let output: DebugOutput = self.call("debug.state", Value::Null).await?;
        Ok(output.output)
    }

    /// Get process tree for a service.
    pub async fn debug_process_tree(&self, name: &str) -> Result<String> {
        let output: DebugOutput = self
            .call("debug.process_tree", json!({ "name": name }))
            .await?;
        Ok(output.output)
    }

    // ============ Xinet Methods ============

    /// Create or update an xinet proxy (replaces existing).
    pub async fn xinet_set(&self, config: &XinetConfig) -> Result<()> {
        let _: Value = self
            .call(
                "xinet.set",
                json!({ "config": serde_json::to_value(config)? }),
            )
            .await?;
        Ok(())
    }

    /// Delete an xinet proxy.
    pub async fn xinet_delete(&self, name: &str) -> Result<()> {
        let _: Value = self.call("xinet.delete", json!({ "name": name })).await?;
        Ok(())
    }

    /// List all xinet proxy names.
    pub async fn xinet_list(&self) -> Result<Vec<String>> {
        self.call("xinet.list", Value::Null).await
    }

    /// Get xinet proxy status (simplified).
    pub async fn xinet_status(&self, name: &str) -> Result<XinetStatus> {
        self.call("xinet.status", json!({ "name": name })).await
    }

    /// Get status of all xinet proxies.
    pub async fn xinet_status_all(&self) -> Result<Vec<XinetStatusFull>> {
        self.call("xinet.status_all", Value::Null).await
    }
}