lnc-client 0.2.8

LANCE client library - Rust client for the LANCE streaming platform
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
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
//! Integration tests for LANCE client
//!
//! These tests require a running LANCE server.
//!
//! Run with:
//!   cargo test --package lnc-client --test integration -- --ignored --nocapture
//!
//! Or set the server address:
//!   LANCE_TEST_ADDR=127.0.0.1:9092 cargo test --package lnc-client --test integration -- --ignored --nocapture

use bytes::Bytes;
use lnc_client::{ClientConfig, LanceClient};
use std::time::{Duration, Instant};

fn get_test_addr() -> String {
    std::env::var("LANCE_TEST_ADDR").unwrap_or_else(|_| "127.0.0.1:1992".to_string())
}

fn test_config() -> ClientConfig {
    ClientConfig {
        addr: get_test_addr(),
        connect_timeout: Duration::from_secs(5),
        read_timeout: Duration::from_secs(10),
        write_timeout: Duration::from_secs(5),
        keepalive_interval: Duration::from_secs(10),
        tls: None,
    }
}

fn is_cluster_mode() -> bool {
    std::env::var("LANCE_NODE2_ADDR").is_ok()
        && std::env::var("LANCE_NODE2_ADDR")
            .map(|v| v != std::env::var("LANCE_TEST_ADDR").unwrap_or_default())
            .unwrap_or(false)
}

async fn wait_for_replication() {
    if is_cluster_mode() {
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

// ============================================================================
// Connection Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_connect_and_close() {
    println!("Testing connection to {:?}", get_test_addr());

    let client = LanceClient::connect(test_config()).await;
    assert!(client.is_ok(), "Failed to connect: {:?}", client.err());

    let client = client.unwrap();
    println!("Connected successfully: {:?}", client);

    let result = client.close().await;
    assert!(result.is_ok(), "Failed to close: {:?}", result.err());
    println!("Connection closed successfully");
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_connect_with_string_addr() {
    let addr = get_test_addr();
    println!("Testing connection to {}", addr);

    let client = LanceClient::connect_to(&addr).await;
    assert!(client.is_ok(), "Failed to connect: {:?}", client.err());

    client.unwrap().close().await.unwrap();
}

// ============================================================================
// Keepalive / Ping Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_ping_latency() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Warm-up ping
    let _ = client.ping().await;

    // Measure latency over multiple pings
    let mut latencies = Vec::new();
    for _ in 0..10 {
        let latency = client.ping().await.unwrap();
        latencies.push(latency);
    }

    let avg_latency: Duration = latencies.iter().sum::<Duration>() / latencies.len() as u32;
    let min_latency = latencies.iter().min().unwrap();
    let max_latency = latencies.iter().max().unwrap();

    println!("Ping latency (10 samples):");
    println!("  Min: {:?}", min_latency);
    println!("  Max: {:?}", max_latency);
    println!("  Avg: {:?}", avg_latency);

    assert!(
        avg_latency < Duration::from_millis(100),
        "Average ping latency too high: {:?}",
        avg_latency
    );

    client.close().await.unwrap();
}

// ============================================================================
// Ingest Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_single_ingest_sync() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a topic for this test
    let topic = client
        .create_topic(&unique_topic_name("ingest_sync"))
        .await
        .unwrap();
    let topic_id = topic.id;

    let payload = Bytes::from_static(b"Hello, LANCE!");
    let batch_id = client.send_ingest_sync(payload, topic_id).await;

    assert!(batch_id.is_ok(), "Ingest failed: {:?}", batch_id.err());
    println!("Ingested batch_id: {}", batch_id.unwrap());

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_sequential_ingests() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a topic for this test
    let topic = client
        .create_topic(&unique_topic_name("sequential"))
        .await
        .unwrap();
    let topic_id = topic.id;

    let count = 100;
    let start = Instant::now();

    for i in 1..=count {
        let payload = Bytes::from(format!("sequential message {}", i));
        let batch_id = client.send_ingest_sync(payload, topic_id).await.unwrap();
        assert_eq!(batch_id, i as u64);
    }

    let elapsed = start.elapsed();
    let rate = count as f64 / elapsed.as_secs_f64();

    println!("Sequential ingests:");
    println!("  Count: {}", count);
    println!("  Time: {:?}", elapsed);
    println!("  Rate: {:.2} msgs/sec", rate);

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_pipelined_ingests() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a topic for this test
    let topic = client
        .create_topic(&unique_topic_name("pipelined"))
        .await
        .unwrap();
    let topic_id = topic.id;

    let count = 1000;
    let payload_size = 1024;
    let start = Instant::now();

    // Send all without waiting for acks
    for _ in 0..count {
        let payload = Bytes::from(vec![0xAB; payload_size]);
        client.send_ingest(payload, topic_id).await.unwrap();
    }

    let send_elapsed = start.elapsed();

    // Now receive all acks
    for i in 1..=count {
        let acked_id = client.recv_ack().await.unwrap();
        assert_eq!(acked_id, i as u64);
    }

    let total_elapsed = start.elapsed();
    let total_bytes = count * payload_size;
    let throughput_mbps = (total_bytes as f64 / 1024.0 / 1024.0) / total_elapsed.as_secs_f64();

    println!("Pipelined ingests:");
    println!("  Count: {}", count);
    println!("  Payload size: {} bytes", payload_size);
    println!("  Send time: {:?}", send_elapsed);
    println!("  Total time: {:?}", total_elapsed);
    println!(
        "  Rate: {:.2} msgs/sec",
        count as f64 / total_elapsed.as_secs_f64()
    );
    println!("  Throughput: {:.2} MB/s", throughput_mbps);

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_large_payload() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a topic for this test
    let topic = client
        .create_topic(&unique_topic_name("large_payload"))
        .await
        .unwrap();
    let topic_id = topic.id;

    // 1 MB payload
    let payload_size = 1024 * 1024;
    let payload = Bytes::from(vec![0xCD; payload_size]);

    let start = Instant::now();
    let batch_id = client.send_ingest_sync(payload, topic_id).await;
    let elapsed = start.elapsed();

    assert!(
        batch_id.is_ok(),
        "Large payload ingest failed: {:?}",
        batch_id.err()
    );

    let throughput_mbps = (payload_size as f64 / 1024.0 / 1024.0) / elapsed.as_secs_f64();

    println!("Large payload ingest:");
    println!(
        "  Size: {} bytes ({} MB)",
        payload_size,
        payload_size / 1024 / 1024
    );
    println!("  Time: {:?}", elapsed);
    println!("  Throughput: {:.2} MB/s", throughput_mbps);

    client.close().await.unwrap();
}

// ============================================================================
// Throughput Benchmark
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_throughput_benchmark() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a topic for this test
    let topic = client
        .create_topic(&unique_topic_name("throughput"))
        .await
        .unwrap();
    let topic_id = topic.id;

    let duration_secs = 5;
    let payload_size = 10 * 1024; // 10 KB per message
    let payload = Bytes::from(vec![0xEF; payload_size]);

    println!(
        "Running throughput benchmark for {} seconds...",
        duration_secs
    );
    println!("Payload size: {} bytes", payload_size);

    let start = Instant::now();
    let deadline = start + Duration::from_secs(duration_secs);

    let mut sent_count = 0u64;
    let mut acked_count = 0u64;

    // Pipeline: send as fast as possible, receive acks
    while Instant::now() < deadline {
        // Send a batch
        for _ in 0..100 {
            if Instant::now() >= deadline {
                break;
            }
            client.send_ingest(payload.clone(), topic_id).await.unwrap();
            sent_count += 1;
        }

        // Receive available acks (non-blocking drain)
        while acked_count < sent_count {
            match tokio::time::timeout(Duration::from_millis(1), client.recv_ack()).await {
                Ok(Ok(_)) => acked_count += 1,
                Ok(Err(e)) => panic!("Ack error: {:?}", e),
                Err(_) => break, // Timeout, continue sending
            }
        }
    }

    // Drain remaining acks
    while acked_count < sent_count {
        client.recv_ack().await.unwrap();
        acked_count += 1;
    }

    let elapsed = start.elapsed();
    let total_bytes = sent_count * payload_size as u64;
    let throughput_mbps = (total_bytes as f64 / 1024.0 / 1024.0) / elapsed.as_secs_f64();
    let msgs_per_sec = sent_count as f64 / elapsed.as_secs_f64();

    println!("\nBenchmark Results:");
    println!("  Duration: {:?}", elapsed);
    println!("  Messages sent: {}", sent_count);
    println!("  Messages acked: {}", acked_count);
    println!(
        "  Total data: {:.2} MB",
        total_bytes as f64 / 1024.0 / 1024.0
    );
    println!("  Throughput: {:.2} MB/s", throughput_mbps);
    println!("  Message rate: {:.2} msgs/sec", msgs_per_sec);

    client.close().await.unwrap();
}

// ============================================================================
// Topic Management Tests
// ============================================================================

fn unique_topic_name(prefix: &str) -> String {
    format!(
        "{}_{}",
        prefix,
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_micros()
    )
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_create_and_list_topics() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a new topic
    let topic_name = unique_topic_name("create_list_test");
    let created = client.create_topic(&topic_name).await.unwrap();

    // Wait for topic to replicate in cluster mode
    wait_for_replication().await;

    println!("Created topic: id={}, name={}", created.id, created.name);
    assert_eq!(created.name, topic_name);
    assert!(created.id > 0);

    // Verify topic exists in list
    let topics = client.list_topics().await.unwrap();
    assert!(
        topics.iter().any(|t| t.id == created.id),
        "Created topic should appear in list"
    );
    println!(
        "Topic {} found in list of {} topics",
        created.id,
        topics.len()
    );

    // Cleanup
    client.delete_topic(created.id).await.unwrap();

    // Wait for delete to replicate in cluster mode
    wait_for_replication().await;

    // Verify topic no longer in list
    let topics_after = client.list_topics().await.unwrap();
    assert!(
        !topics_after.iter().any(|t| t.id == created.id),
        "Deleted topic should not be in list"
    );

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_get_topic_by_id() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a topic
    let topic_name = unique_topic_name("get_by_id_test");
    let created = client.create_topic(&topic_name).await.unwrap();

    // Wait for topic to replicate in cluster mode
    wait_for_replication().await;

    // Get it by ID
    let fetched = client.get_topic(created.id).await.unwrap();
    assert_eq!(fetched.id, created.id);
    assert_eq!(fetched.name, topic_name);
    println!("Fetched topic: id={}, name={}", fetched.id, fetched.name);

    // Cleanup
    client.delete_topic(created.id).await.unwrap();

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_delete_topic() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a topic
    let topic_name = unique_topic_name("delete_test");
    let created = client.create_topic(&topic_name).await.unwrap();
    println!("Created topic for deletion: id={}", created.id);

    // Wait for topic to replicate in cluster mode
    wait_for_replication().await;

    // Delete it
    client.delete_topic(created.id).await.unwrap();
    println!("Deleted topic id={}", created.id);

    // Wait for delete to replicate in cluster mode
    wait_for_replication().await;

    // Verify it's gone (should error)
    let result = client.get_topic(created.id).await;
    assert!(result.is_err(), "Topic should not exist after deletion");
    println!("Expected error after deletion: {:?}", result.err());

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_topic_lifecycle_with_data() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // 1. Create topic
    let topic_name = unique_topic_name("lifecycle_test");
    let topic = client.create_topic(&topic_name).await.unwrap();
    println!("1. Created topic: id={}, name={}", topic.id, topic.name);

    // Wait for topic to replicate in cluster mode
    wait_for_replication().await;

    // 2. Ingest data to the topic
    let mut total_bytes = 0usize;
    let batch_count = 10;
    for i in 0..batch_count {
        let payload = Bytes::from(format!(
            "lifecycle test message {} for topic {}",
            i, topic.id
        ));
        total_bytes += payload.len();
        client
            .send_ingest_to_topic_sync(topic.id, payload, 1, None)
            .await
            .unwrap();
    }
    println!(
        "2. Ingested {} batches ({} bytes) to topic {}",
        batch_count, total_bytes, topic.id
    );

    // 3. Verify topic still exists
    let fetched = client.get_topic(topic.id).await.unwrap();
    assert_eq!(fetched.id, topic.id);
    println!("3. Topic still exists: id={}", fetched.id);

    // 4. Delete the topic
    client.delete_topic(topic.id).await.unwrap();
    println!("4. Deleted topic id={}", topic.id);

    // Wait for delete to replicate in cluster mode
    wait_for_replication().await;

    // 5. Verify deletion
    let result = client.get_topic(topic.id).await;
    assert!(result.is_err());
    println!("5. Topic confirmed deleted");

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_multiple_topics_concurrent_ingest() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create multiple topics
    let topic_count = 3;
    let mut topics = Vec::new();
    for i in 0..topic_count {
        let name = unique_topic_name(&format!("concurrent_{}", i));
        let topic = client.create_topic(&name).await.unwrap();
        topics.push(topic);
    }
    println!("Created {} topics", topics.len());

    // Ingest to all topics in round-robin
    let messages_per_topic = 100;
    let start = Instant::now();

    for msg_idx in 0..(messages_per_topic * topic_count) {
        let topic_idx = msg_idx % topic_count;
        let topic_id = topics[topic_idx].id;
        let payload = Bytes::from(format!("msg {} to topic {}", msg_idx, topic_id));
        client
            .send_ingest_to_topic_sync(topic_id, payload, 1, None)
            .await
            .unwrap();
    }

    let elapsed = start.elapsed();
    let total_msgs = messages_per_topic * topic_count;
    println!(
        "Ingested {} messages to {} topics in {:?}",
        total_msgs, topic_count, elapsed
    );
    println!(
        "Rate: {:.2} msgs/sec",
        total_msgs as f64 / elapsed.as_secs_f64()
    );

    // Cleanup
    for topic in &topics {
        client.delete_topic(topic.id).await.unwrap();
    }
    println!("Cleaned up {} topics", topics.len());

    client.close().await.unwrap();
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[tokio::test]
async fn test_connect_to_invalid_address() {
    let config = ClientConfig {
        addr: "127.0.0.1:19999".to_string(), // Unlikely to be listening
        connect_timeout: Duration::from_secs(1),
        ..Default::default()
    };

    let result = LanceClient::connect(config).await;
    assert!(result.is_err(), "Should fail to connect to invalid address");
    println!("Expected error: {:?}", result.err());
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_get_nonexistent_topic() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Try to get a topic that doesn't exist
    let result = client.get_topic(999999).await;
    assert!(result.is_err(), "Should fail to get nonexistent topic");
    println!("Expected error: {:?}", result.err());

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_delete_nonexistent_topic() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Try to delete a topic that doesn't exist
    let result = client.delete_topic(999999).await;
    assert!(result.is_err(), "Should fail to delete nonexistent topic");
    println!("Expected error: {:?}", result.err());

    client.close().await.unwrap();
}

// ============================================================================
// Multi-Subscriber Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_multiple_subscribers_single_topic() {
    // Create 3 separate clients to simulate multiple subscribers
    let mut client1 = LanceClient::connect(test_config()).await.unwrap();
    let mut client2 = LanceClient::connect(test_config()).await.unwrap();
    let mut client3 = LanceClient::connect(test_config()).await.unwrap();

    // Create a shared topic
    let topic_name = unique_topic_name("multi_subscriber");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    let topic_id = topic.id;
    println!("Created shared topic: id={}, name={}", topic_id, topic_name);

    // Wait for topic to replicate in cluster mode
    wait_for_replication().await;

    // Subscribe all clients to the same topic at different offsets
    let consumer_id1 = 1001u64;
    let consumer_id2 = 1002u64;
    let consumer_id3 = 1003u64;
    let max_batch_bytes = 64 * 1024u32; // 64KB batch size

    let result1 = client1
        .subscribe(topic_id, 0, max_batch_bytes, consumer_id1)
        .await;
    assert!(
        result1.is_ok(),
        "Client 1 subscribe failed: {:?}",
        result1.err()
    );
    let sub1 = result1.unwrap();
    println!(
        "Subscriber 1 (consumer_id={}) subscribed at offset {}",
        consumer_id1, sub1.start_offset
    );

    let result2 = client2
        .subscribe(topic_id, 0, max_batch_bytes, consumer_id2)
        .await;
    assert!(
        result2.is_ok(),
        "Client 2 subscribe failed: {:?}",
        result2.err()
    );
    let sub2 = result2.unwrap();
    println!(
        "Subscriber 2 (consumer_id={}) subscribed at offset {}",
        consumer_id2, sub2.start_offset
    );

    let result3 = client3
        .subscribe(topic_id, 0, max_batch_bytes, consumer_id3)
        .await;
    assert!(
        result3.is_ok(),
        "Client 3 subscribe failed: {:?}",
        result3.err()
    );
    let sub3 = result3.unwrap();
    println!(
        "Subscriber 3 (consumer_id={}) subscribed at offset {}",
        consumer_id3, sub3.start_offset
    );

    // Ingest some data to the topic
    let mut producer = LanceClient::connect(test_config()).await.unwrap();
    let message_count = 20;
    for i in 0..message_count {
        let payload = Bytes::from(format!("multi-sub message {}", i));
        producer
            .send_ingest_to_topic_sync(topic_id, payload, 1, None)
            .await
            .unwrap();
    }
    println!("Ingested {} messages to topic {}", message_count, topic_id);

    // Each subscriber commits at different offsets (simulating different progress)
    client1
        .commit_offset(topic_id, consumer_id1, 5)
        .await
        .unwrap();
    println!("Subscriber 1 committed offset 5");

    client2
        .commit_offset(topic_id, consumer_id2, 10)
        .await
        .unwrap();
    println!("Subscriber 2 committed offset 10");

    client3
        .commit_offset(topic_id, consumer_id3, 15)
        .await
        .unwrap();
    println!("Subscriber 3 committed offset 15");

    // Unsubscribe all
    client1.unsubscribe(topic_id, consumer_id1).await.unwrap();
    client2.unsubscribe(topic_id, consumer_id2).await.unwrap();
    client3.unsubscribe(topic_id, consumer_id3).await.unwrap();
    println!("All subscribers unsubscribed");

    // Cleanup
    producer.delete_topic(topic_id).await.unwrap();
    println!("Deleted topic {}", topic_id);

    client1.close().await.unwrap();
    client2.close().await.unwrap();
    client3.close().await.unwrap();
    producer.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_subscriber_resume_after_disconnect() {
    let mut client1 = LanceClient::connect(test_config()).await.unwrap();

    // Create topic and subscribe
    let topic_name = unique_topic_name("resume_test");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    let topic_id = topic.id;
    let consumer_id = 2001u64;

    // Wait for topic to replicate in cluster mode
    wait_for_replication().await;

    let max_batch_bytes = 64 * 1024u32;
    client1
        .subscribe(topic_id, 0, max_batch_bytes, consumer_id)
        .await
        .unwrap();
    println!("1. Subscribed to topic {}", topic_id);

    // Ingest some data
    for i in 0..10 {
        let payload = Bytes::from(format!("resume test message {}", i));
        client1
            .send_ingest_to_topic_sync(topic_id, payload, 1, None)
            .await
            .unwrap();
    }
    println!("2. Ingested 10 messages");

    // Commit progress
    client1
        .commit_offset(topic_id, consumer_id, 5)
        .await
        .unwrap();
    println!("3. Committed offset 5");

    // Disconnect (simulate crash/disconnect)
    client1.unsubscribe(topic_id, consumer_id).await.unwrap();
    client1.close().await.unwrap();
    println!("4. Disconnected");

    // Reconnect with new client
    let mut client2 = LanceClient::connect(test_config()).await.unwrap();

    // Re-subscribe - should resume from committed offset
    let result = client2
        .subscribe(topic_id, 5, max_batch_bytes, consumer_id)
        .await;
    assert!(result.is_ok(), "Re-subscribe failed: {:?}", result.err());
    let sub_result = result.unwrap();
    println!(
        "5. Re-subscribed, resumed at offset {}",
        sub_result.start_offset
    );

    // Cleanup
    client2.delete_topic(topic_id).await.unwrap();
    client2.close().await.unwrap();
    println!("6. Cleanup complete");
}

/// Test that Consumer with OffsetStore loads stored offset on restart
/// and commit() persists offset correctly
#[tokio::test]
#[ignore] // Requires running server
async fn test_consumer_offset_store_persistence() {
    use lnc_client::{Consumer, ConsumerConfig, LockFileOffsetStore, OffsetStore};
    use std::sync::Arc;

    let temp_dir = tempfile::tempdir().unwrap();
    let offset_dir = temp_dir.path();

    let mut client1 = LanceClient::connect(test_config()).await.unwrap();

    // Create topic
    let topic_name = unique_topic_name("offset_store_test");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    let topic_id = topic.id;
    let consumer_id = 3001u64;
    let consumer_name = "test-consumer";

    wait_for_replication().await;

    // Ingest some data
    for i in 0..20 {
        let payload = Bytes::from(format!("offset store message {}", i));
        client1
            .send_ingest_to_topic_sync(topic_id, payload, 1, None)
            .await
            .unwrap();
    }
    println!("1. Ingested 20 messages to topic {}", topic_id);

    // Create consumer with offset store, consume and commit
    {
        let client2 = LanceClient::connect(test_config()).await.unwrap();
        let offset_store = LockFileOffsetStore::open(offset_dir, consumer_name).unwrap();
        let config = ConsumerConfig::new(topic_id);
        let mut consumer = Consumer::with_offset_store(
            client2,
            &get_test_addr(),
            config,
            consumer_id,
            Arc::new(offset_store),
        )
        .unwrap();

        // Poll to ensure consumer is ready
        drop(consumer.poll());
        println!("2. Consumer created and polled");

        // Seek to offset 10 and commit
        consumer.seek_to_offset(10).await.unwrap();
        consumer.commit().await.unwrap();
        println!("3. Committed offset at position 10");

        // Drop consumer (simulates disconnect)
    }
    println!("4. Consumer disconnected");

    // Verify offset was persisted
    {
        let offset_store = LockFileOffsetStore::open(offset_dir, consumer_name).unwrap();
        let stored = offset_store.load(topic_id, consumer_id).unwrap();
        assert_eq!(stored, Some(10), "Offset should be persisted to file");
        println!("5. Verified persisted offset = 10");
    }

    // Create new consumer - should resume from stored offset
    {
        let client3 = LanceClient::connect(test_config()).await.unwrap();
        let offset_store = LockFileOffsetStore::open(offset_dir, consumer_name).unwrap();
        let config = ConsumerConfig::new(topic_id);
        let consumer = Consumer::with_offset_store(
            client3,
            &get_test_addr(),
            config,
            consumer_id, // Same consumer ID to load saved offset
            Arc::new(offset_store),
        )
        .unwrap();

        // Check that consumer loaded the stored offset
        assert_eq!(
            consumer.current_offset(),
            10,
            "Consumer should resume from stored offset"
        );
        println!(
            "6. New consumer resumed at offset {}",
            consumer.current_offset()
        );
    }

    // Cleanup
    client1.delete_topic(topic_id).await.unwrap();
    client1.close().await.unwrap();
    println!("7. Cleanup complete");
}

// ============================================================================
// Multi-Node Replication Tests
// ============================================================================
// These tests require a 3-node cluster running. Start with:
//   ./scripts/start-cluster.ps1 (Windows)
//   ./scripts/start-cluster.sh (Linux/Mac)
//
// Set environment variables:
//   LANCE_NODE1_ADDR=127.0.0.1:1992
//   LANCE_NODE2_ADDR=127.0.0.1:1993
//   LANCE_NODE3_ADDR=127.0.0.1:1994

fn get_node_addr(node: u8) -> Option<String> {
    let var_name = format!("LANCE_NODE{}_ADDR", node);
    std::env::var(&var_name).ok()
}

fn cluster_config(node: u8) -> Option<ClientConfig> {
    get_node_addr(node).map(|addr| ClientConfig {
        addr,
        connect_timeout: Duration::from_secs(5),
        read_timeout: Duration::from_secs(10),
        write_timeout: Duration::from_secs(5),
        keepalive_interval: Duration::from_secs(10),
        tls: None,
    })
}

#[tokio::test]
#[ignore = "requires 3-node LANCE cluster"]
async fn test_cluster_write_to_leader_read_from_follower() {
    let node1_config = cluster_config(1).expect("LANCE_NODE1_ADDR not set");
    let node2_config = cluster_config(2).expect("LANCE_NODE2_ADDR not set");

    // Connect to both nodes
    let mut client1 = LanceClient::connect(node1_config).await.unwrap();
    let mut client2 = LanceClient::connect(node2_config).await.unwrap();
    println!("Connected to node 1 and node 2");

    // Create topic on node 1 (leader)
    let topic_name = unique_topic_name("cluster_test");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    let topic_id = topic.id;
    println!("Created topic {} on node 1", topic_id);

    // Ingest data to node 1
    let message_count = 10;
    for i in 0..message_count {
        let payload = Bytes::from(format!("cluster message {}", i));
        client1
            .send_ingest_to_topic_sync(topic_id, payload, 1, None)
            .await
            .unwrap();
    }
    println!("Ingested {} messages to node 1", message_count);

    // Wait for replication
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Verify topic exists on node 2 (should be replicated)
    let result = client2.get_topic(topic_id).await;
    if result.is_ok() {
        println!("Topic {} found on node 2 (replicated)", topic_id);
    } else {
        println!(
            "Topic {} not yet replicated to node 2: {:?}",
            topic_id,
            result.err()
        );
    }

    // List topics on node 2
    let topics = client2.list_topics().await.unwrap();
    println!("Node 2 has {} topics", topics.len());

    // Cleanup
    client1.delete_topic(topic_id).await.unwrap();
    client1.close().await.unwrap();
    client2.close().await.unwrap();
    println!("Cleanup complete");
}

#[tokio::test]
#[ignore = "requires 3-node LANCE cluster"]
async fn test_cluster_all_nodes_see_topics() {
    let node1_config = cluster_config(1).expect("LANCE_NODE1_ADDR not set");
    let node2_config = cluster_config(2).expect("LANCE_NODE2_ADDR not set");
    let node3_config = cluster_config(3).expect("LANCE_NODE3_ADDR not set");

    // Connect to all 3 nodes
    let mut client1 = LanceClient::connect(node1_config).await.unwrap();
    let mut client2 = LanceClient::connect(node2_config).await.unwrap();
    let mut client3 = LanceClient::connect(node3_config).await.unwrap();
    println!("Connected to all 3 nodes");

    // Create topic on node 1
    let topic_name = unique_topic_name("cluster_visibility");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    let topic_id = topic.id;
    println!("Created topic {} on node 1", topic_id);

    // Wait for replication
    tokio::time::sleep(Duration::from_secs(1)).await;

    // Check visibility on all nodes
    let topics1 = client1.list_topics().await.unwrap();
    let topics2 = client2.list_topics().await.unwrap();
    let topics3 = client3.list_topics().await.unwrap();

    println!(
        "Topic counts: node1={}, node2={}, node3={}",
        topics1.len(),
        topics2.len(),
        topics3.len()
    );

    // Verify topic is visible on all nodes
    let visible_on_1 = topics1.iter().any(|t| t.id == topic_id);
    let visible_on_2 = topics2.iter().any(|t| t.id == topic_id);
    let visible_on_3 = topics3.iter().any(|t| t.id == topic_id);

    println!(
        "Topic {} visible: node1={}, node2={}, node3={}",
        topic_id, visible_on_1, visible_on_2, visible_on_3
    );

    assert!(visible_on_1, "Topic should be visible on node 1");
    // Note: visibility on followers depends on replication mode and timing

    // Cleanup
    client1.delete_topic(topic_id).await.unwrap();
    client1.close().await.unwrap();
    client2.close().await.unwrap();
    client3.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires 3-node LANCE cluster"]
async fn test_cluster_topic_delete_replication() {
    let node1_config = cluster_config(1).expect("LANCE_NODE1_ADDR not set");
    let node2_config = cluster_config(2).expect("LANCE_NODE2_ADDR not set");

    let mut client1 = LanceClient::connect(node1_config).await.unwrap();
    let mut client2 = LanceClient::connect(node2_config).await.unwrap();
    println!("Connected to node 1 and node 2");

    // Create topic on node 1 (leader)
    let topic_name = unique_topic_name("delete_replication");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    let topic_id = topic.id;
    println!("Created topic {} on node 1", topic_id);

    // Wait for create replication
    tokio::time::sleep(Duration::from_secs(1)).await;

    // Verify topic exists on node 2
    let topics_before = client2.list_topics().await.unwrap();
    let exists_on_node2 = topics_before.iter().any(|t| t.id == topic_id);
    println!(
        "Topic {} exists on node 2 before delete: {}",
        topic_id, exists_on_node2
    );

    // Delete topic on node 1 (leader)
    client1.delete_topic(topic_id).await.unwrap();
    println!("Deleted topic {} on node 1", topic_id);

    // Wait for delete replication
    tokio::time::sleep(Duration::from_secs(1)).await;

    // Verify topic is gone on node 2
    let topics_after = client2.list_topics().await.unwrap();
    let still_exists = topics_after.iter().any(|t| t.id == topic_id);
    println!(
        "Topic {} exists on node 2 after delete: {}",
        topic_id, still_exists
    );

    // Cleanup
    client1.close().await.unwrap();
    client2.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires 3-node LANCE cluster"]
async fn test_cluster_write_routing_from_follower() {
    let node1_config = cluster_config(1).expect("LANCE_NODE1_ADDR not set");
    let node2_config = cluster_config(2).expect("LANCE_NODE2_ADDR not set");

    let mut client1 = LanceClient::connect(node1_config).await.unwrap();
    let mut client2 = LanceClient::connect(node2_config).await.unwrap();
    println!("Connected to node 1 and node 2");

    // First, create a topic on node 1 (leader) so we have something to test with
    let topic_name = unique_topic_name("write_routing");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    let topic_id = topic.id;
    println!("Created topic {} on node 1", topic_id);

    // Try to create another topic on node 2 (follower)
    // This should either succeed (if redirected) or return NOT_LEADER error
    let topic2_name = unique_topic_name("follower_create");
    let result = client2.create_topic(&topic2_name).await;

    match result {
        Ok(topic2) => {
            println!(
                "Topic {} created via node 2 (redirected to leader)",
                topic2.id
            );
            client1.delete_topic(topic2.id).await.unwrap();
        },
        Err(e) => {
            let err_str = format!("{:?}", e);
            println!("Create from follower returned: {}", err_str);
            // Expected: NOT_LEADER error with redirect info
            assert!(
                err_str.contains("NOT_LEADER") || err_str.contains("redirect"),
                "Expected NOT_LEADER error, got: {}",
                err_str
            );
        },
    }

    // Cleanup
    client1.delete_topic(topic_id).await.unwrap();
    client1.close().await.unwrap();
    client2.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires 3-node LANCE cluster"]
async fn test_cluster_concurrent_writes_multiple_nodes() {
    let node1_config = cluster_config(1).expect("LANCE_NODE1_ADDR not set");
    let node2_config = cluster_config(2).expect("LANCE_NODE2_ADDR not set");

    let mut client1 = LanceClient::connect(node1_config.clone()).await.unwrap();
    let mut client2 = LanceClient::connect(node2_config.clone()).await.unwrap();

    // Create topics on different nodes
    let topic1_name = unique_topic_name("concurrent_node1");
    let topic2_name = unique_topic_name("concurrent_node2");

    let topic1 = client1.create_topic(&topic1_name).await.unwrap();
    let topic2 = client2.create_topic(&topic2_name).await.unwrap();
    println!(
        "Created topic {} on node 1, topic {} on node 2",
        topic1.id, topic2.id
    );

    // Concurrent writes from multiple clients
    let start = Instant::now();
    let messages_per_client = 50;

    // Spawn concurrent write tasks
    let client1_handle = {
        let topic_id = topic1.id;
        let config = node1_config.clone();
        tokio::spawn(async move {
            let mut c = LanceClient::connect(config).await.unwrap();
            for i in 0..messages_per_client {
                let payload = Bytes::from(format!("node1 msg {}", i));
                c.send_ingest_to_topic_sync(topic_id, payload, 1, None)
                    .await
                    .unwrap();
            }
            c.close().await.unwrap();
        })
    };

    let client2_handle = {
        let topic_id = topic2.id;
        let config = node2_config.clone();
        tokio::spawn(async move {
            let mut c = LanceClient::connect(config).await.unwrap();
            for i in 0..messages_per_client {
                let payload = Bytes::from(format!("node2 msg {}", i));
                c.send_ingest_to_topic_sync(topic_id, payload, 1, None)
                    .await
                    .unwrap();
            }
            c.close().await.unwrap();
        })
    };

    // Wait for both to complete
    client1_handle.await.unwrap();
    client2_handle.await.unwrap();

    let elapsed = start.elapsed();
    let total_messages = messages_per_client * 2;
    println!(
        "Concurrent writes complete: {} messages in {:?}",
        total_messages, elapsed
    );
    println!(
        "Rate: {:.2} msgs/sec",
        total_messages as f64 / elapsed.as_secs_f64()
    );

    // Cleanup
    client1.delete_topic(topic1.id).await.unwrap();
    client2.delete_topic(topic2.id).await.unwrap();
    client1.close().await.unwrap();
    client2.close().await.unwrap();
}

// ============================================================================
// Retention Policy Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_set_retention_policy() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a topic
    let topic_name = unique_topic_name("retention_set");
    let topic = client.create_topic(&topic_name).await.unwrap();
    println!("Created topic {} with id {}", topic_name, topic.id);

    // Set retention policy: 1 hour, 100MB
    let max_age_secs = 3600;
    let max_bytes = 100 * 1024 * 1024; // 100MB
    let result = client
        .set_retention(topic.id, max_age_secs, max_bytes)
        .await;
    assert!(
        result.is_ok(),
        "Failed to set retention: {:?}",
        result.err()
    );
    println!(
        "Set retention policy: max_age={}s, max_bytes={}",
        max_age_secs, max_bytes
    );

    // Verify by getting topic info (retention should be reflected)
    let info = client.get_topic(topic.id).await;
    assert!(info.is_ok(), "Failed to get topic: {:?}", info.err());
    let info = info.unwrap();
    println!("Topic info after retention set: {:?}", info);

    // Cleanup
    client.delete_topic(topic.id).await.unwrap();
    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_create_topic_with_retention() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create a topic with retention policy
    let topic_name = unique_topic_name("retention_create");
    let max_age_secs = 7200; // 2 hours
    let max_bytes = 50 * 1024 * 1024; // 50MB

    let result = client
        .create_topic_with_retention(&topic_name, max_age_secs, max_bytes)
        .await;
    assert!(
        result.is_ok(),
        "Failed to create topic with retention: {:?}",
        result.err()
    );

    let topic = result.unwrap();
    println!(
        "Created topic {} with id {} and retention policy",
        topic_name, topic.id
    );

    // Verify topic exists
    let info = client.get_topic(topic.id).await;
    assert!(info.is_ok(), "Failed to get topic: {:?}", info.err());

    // Cleanup
    client.delete_topic(topic.id).await.unwrap();
    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_retention_policy_update() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create topic without retention
    let topic_name = unique_topic_name("retention_update");
    let topic = client.create_topic(&topic_name).await.unwrap();

    // Set initial retention
    let result = client.set_retention(topic.id, 3600, 100_000_000).await;
    assert!(result.is_ok());
    println!("Initial retention set");

    // Update retention to different values
    let result = client.set_retention(topic.id, 1800, 50_000_000).await;
    assert!(
        result.is_ok(),
        "Failed to update retention: {:?}",
        result.err()
    );
    println!("Retention updated successfully");

    // Cleanup
    client.delete_topic(topic.id).await.unwrap();
    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_retention_on_nonexistent_topic() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Try to set retention on a topic that doesn't exist
    let result = client.set_retention(99999, 3600, 100_000_000).await;

    // Should fail gracefully
    assert!(result.is_err(), "Expected error for nonexistent topic");
    println!(
        "Correctly rejected retention on nonexistent topic: {:?}",
        result.err()
    );

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires 3-node LANCE cluster"]
async fn test_cluster_retention_replication() {
    let node1_config = cluster_config(1).expect("LANCE_NODE1_ADDR not set");
    let node2_config = cluster_config(2).expect("LANCE_NODE2_ADDR not set");

    let mut client1 = LanceClient::connect(node1_config).await.unwrap();
    let mut client2 = LanceClient::connect(node2_config).await.unwrap();

    // Create topic on node 1
    let topic_name = unique_topic_name("retention_cluster");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    println!("Created topic {} on node 1", topic.id);

    // Set retention on node 1
    let result = client1.set_retention(topic.id, 3600, 100_000_000).await;
    assert!(
        result.is_ok(),
        "Failed to set retention: {:?}",
        result.err()
    );
    println!("Set retention on node 1");

    // Wait for replication
    wait_for_replication().await;

    // Verify topic exists on node 2 (retention is part of metadata)
    let info = client2.get_topic(topic.id).await;
    assert!(
        info.is_ok(),
        "Topic should be visible on node 2: {:?}",
        info.err()
    );
    println!("Topic with retention visible on node 2");

    // Cleanup
    client1.delete_topic(topic.id).await.unwrap();
    client1.close().await.unwrap();
    client2.close().await.unwrap();
}

// ============================================================================
// Cluster Status Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_get_cluster_status() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    let status = client.get_cluster_status().await.unwrap();
    println!("Cluster status: {:?}", status);

    // Verify basic fields are present
    println!("Node ID: {}", status.node_id);
    println!("Is Leader: {}", status.is_leader);
    println!("Node Count: {}", status.node_count);

    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires 3-node LANCE cluster"]
async fn test_cluster_status_from_multiple_nodes() {
    let node1_config = cluster_config(1).expect("LANCE_NODE1_ADDR not set");
    let node2_config = cluster_config(2).expect("LANCE_NODE2_ADDR not set");
    let node3_config = cluster_config(3).expect("LANCE_NODE3_ADDR not set");

    let mut client1 = LanceClient::connect(node1_config).await.unwrap();
    let mut client2 = LanceClient::connect(node2_config).await.unwrap();
    let mut client3 = LanceClient::connect(node3_config).await.unwrap();

    let status1 = client1.get_cluster_status().await.unwrap();
    let status2 = client2.get_cluster_status().await.unwrap();
    let status3 = client3.get_cluster_status().await.unwrap();

    println!("Node 1: is_leader={}", status1.is_leader);
    println!("Node 2: is_leader={}", status2.is_leader);
    println!("Node 3: is_leader={}", status3.is_leader);

    // Exactly one node should be leader
    let leader_count = [status1.is_leader, status2.is_leader, status3.is_leader]
        .iter()
        .filter(|&&x| x)
        .count();
    assert_eq!(leader_count, 1, "Exactly one node should be leader");

    client1.close().await.unwrap();
    client2.close().await.unwrap();
    client3.close().await.unwrap();
}

// Duplicate retention policy tests removed - see earlier definitions above

// ============================================================================
// Cluster Failover and Recovery Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires 3-node LANCE cluster"]
async fn test_cluster_failover_write_continuity() {
    let node1_config = cluster_config(1).expect("LANCE_NODE1_ADDR not set");
    let node2_config = cluster_config(2).expect("LANCE_NODE2_ADDR not set");

    let mut client1 = LanceClient::connect(node1_config.clone()).await.unwrap();
    let mut client2 = LanceClient::connect(node2_config.clone()).await.unwrap();

    // Create a topic
    let topic_name = unique_topic_name("failover_test");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    println!("Created topic {} for failover test", topic.id);

    wait_for_replication().await;

    // Find which node is leader
    let status1 = client1.get_cluster_status().await.unwrap();
    let status2 = client2.get_cluster_status().await.unwrap();

    println!("Node 1 is_leader: {}", status1.is_leader);
    println!("Node 2 is_leader: {}", status2.is_leader);

    // Write data before simulated failover
    let test_data = bytes::Bytes::from_static(b"pre-failover data");
    let write_result = if status1.is_leader {
        client1
            .send_ingest_to_topic_sync(topic.id, test_data.clone(), 1, None)
            .await
    } else {
        client2
            .send_ingest_to_topic_sync(topic.id, test_data, 1, None)
            .await
    };
    assert!(write_result.is_ok(), "Pre-failover write should succeed");
    println!("Pre-failover write succeeded");

    // Note: Actual failover testing requires stopping a node,
    // which would need Docker/process control integration.
    // This test validates the cluster status API works correctly.

    // Cleanup
    client1.delete_topic(topic.id).await.unwrap();
    client1.close().await.unwrap();
    client2.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires 3-node LANCE cluster"]
async fn test_write_forwarding_from_follower() {
    let node1_config = cluster_config(1).expect("LANCE_NODE1_ADDR not set");
    let node2_config = cluster_config(2).expect("LANCE_NODE2_ADDR not set");
    let node3_config = cluster_config(3).expect("LANCE_NODE3_ADDR not set");

    let mut client1 = LanceClient::connect(node1_config).await.unwrap();
    let mut client2 = LanceClient::connect(node2_config).await.unwrap();
    let mut client3 = LanceClient::connect(node3_config).await.unwrap();

    // Create topic
    let topic_name = unique_topic_name("forward_test");
    let topic = client1.create_topic(&topic_name).await.unwrap();
    println!("Created topic {} for write forwarding test", topic.id);

    wait_for_replication().await;

    // Find a follower node
    let status1 = client1.get_cluster_status().await.unwrap();
    let status2 = client2.get_cluster_status().await.unwrap();
    let _status3 = client3.get_cluster_status().await.unwrap();

    let follower_client = if !status1.is_leader {
        &mut client1
    } else if !status2.is_leader {
        &mut client2
    } else {
        &mut client3
    };

    // Write to follower - should be forwarded to leader
    let test_data = bytes::Bytes::from_static(b"forwarded write data");
    let result = follower_client
        .send_ingest_to_topic_sync(topic.id, test_data, 1, None)
        .await;

    // Write forwarding should either succeed or return NotLeader with redirect
    match &result {
        Ok(_) => println!("Write forwarded successfully"),
        Err(e) => println!("Write forward result: {:?}", e),
    }

    // Cleanup
    client1.delete_topic(topic.id).await.unwrap();
    client1.close().await.unwrap();
    client2.close().await.unwrap();
    client3.close().await.unwrap();
}

// ============================================================================
// WAL Recovery Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server with WAL enabled"]
async fn test_wal_replay_after_restart() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    // Create topic and write data
    let topic_name = unique_topic_name("wal_test");
    let topic = client.create_topic(&topic_name).await.unwrap();
    println!("Created topic {} for WAL test", topic.id);

    // Write multiple batches
    for i in 0..10 {
        let data = bytes::Bytes::from(format!("wal_test_batch_{}", i));
        let result = client
            .send_ingest_to_topic_sync(topic.id, data, 1, None)
            .await;
        assert!(result.is_ok(), "Write {} should succeed", i);
    }
    println!("Wrote 10 batches to topic");

    // Force flush to ensure WAL entries are written
    // Note: Actual WAL replay test would require server restart
    // which needs Docker/process control integration

    // Verify data can be read back
    let info = client.get_topic(topic.id).await.unwrap();
    println!("Topic info after writes: {:?}", info);

    // Cleanup
    client.delete_topic(topic.id).await.unwrap();
    client.close().await.unwrap();
}

// ============================================================================
// Backpressure Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_backpressure_under_load() {
    let mut client = LanceClient::connect(test_config()).await.unwrap();

    let topic_name = unique_topic_name("backpressure_test");
    let topic = client.create_topic(&topic_name).await.unwrap();
    println!("Created topic {} for backpressure test", topic.id);

    // Generate load with many concurrent writes
    let mut success_count = 0u32;
    let mut backpressure_count = 0u32;

    // Write 1000 small messages as fast as possible
    let data = bytes::Bytes::from(vec![0u8; 256]); // 256 byte payload
    for i in 0..1000 {
        match client
            .send_ingest_to_topic_sync(topic.id, data.clone(), 1, None)
            .await
        {
            Ok(_) => success_count += 1,
            Err(e) => {
                // Check if it's a backpressure signal
                let err_str = format!("{:?}", e);
                if err_str.contains("backpressure") || err_str.contains("Backpressure") {
                    backpressure_count += 1;
                } else {
                    println!("Write {} failed: {:?}", i, e);
                }
            },
        }
    }

    println!(
        "Backpressure test: {} succeeded, {} backpressured",
        success_count, backpressure_count
    );

    // At minimum, some writes should succeed
    assert!(success_count > 0, "At least some writes should succeed");

    // Cleanup
    client.delete_topic(topic.id).await.unwrap();
    client.close().await.unwrap();
}

// ============================================================================
// TLS Connection Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires LANCE server with TLS enabled and certificates"]
async fn test_tls_encrypted_connection() {
    // This test requires:
    // - LANCE server running with TLS enabled
    // - Valid certificate and key files
    // - CA certificate for client verification

    let config = test_config();

    let result = LanceClient::connect(config).await;
    match result {
        Ok(mut client) => {
            // Test basic operations over TLS connection
            let topic_name = unique_topic_name("tls_test");
            let topic_result = client.create_topic(&topic_name).await;
            assert!(
                topic_result.is_ok(),
                "Should create topic over TLS: {:?}",
                topic_result.err()
            );

            let topic = topic_result.unwrap();
            println!("Created topic {} over TLS connection", topic.id);

            // Write data over TLS
            let test_data = bytes::Bytes::from_static(b"TLS encrypted data");
            let write_result = client
                .send_ingest_to_topic_sync(topic.id, test_data, 1, None)
                .await;
            assert!(
                write_result.is_ok(),
                "Should write over TLS: {:?}",
                write_result.err()
            );
            println!("Wrote data over TLS connection");

            // Cleanup
            client.delete_topic(topic.id).await.unwrap();
            client.close().await.unwrap();
            println!("TLS connection test passed");
        },
        Err(e) => {
            println!(
                "TLS connection failed (expected if server not TLS-enabled): {:?}",
                e
            );
        },
    }
}

#[tokio::test]
#[ignore = "requires LANCE server with mTLS enabled"]
async fn test_mtls_client_certificate() {
    // This test validates mutual TLS where client presents certificate

    let config = test_config();

    let result = LanceClient::connect(config).await;
    match result {
        Ok(mut client) => {
            println!("mTLS connection established");

            // Verify connection works
            let ping_result = client.ping().await;
            assert!(ping_result.is_ok(), "Ping should succeed over mTLS");
            println!("Ping latency: {:?}", ping_result.unwrap());

            client.close().await.unwrap();
        },
        Err(e) => {
            println!("mTLS connection failed: {:?}", e);
        },
    }
}

#[tokio::test]
#[ignore = "requires LANCE server with TLS enabled"]
async fn test_tls_with_client_config_integration() {
    use lnc_client::TlsClientConfig;

    // Test TLS configuration via ClientConfig.with_tls()
    let addr = get_test_addr();
    let tls = TlsClientConfig::new();
    let config = ClientConfig::new(addr).with_tls(tls);

    assert!(config.is_tls_enabled(), "TLS should be enabled in config");

    // Connect using unified config (auto-detects TLS)
    match LanceClient::connect(config).await {
        Ok(mut client) => {
            // Verify connection is functional
            let ping = client.ping().await;
            assert!(ping.is_ok(), "Ping over TLS should succeed");
            println!("TLS via ClientConfig integration: ping {:?}", ping.unwrap());
            client.close().await.unwrap();
        },
        Err(e) => {
            println!("TLS connection via ClientConfig failed: {:?}", e);
        },
    }
}

#[tokio::test]
#[ignore = "requires LANCE server with TLS enabled"]
async fn test_tls_certificate_validation() {
    use lnc_client::TlsClientConfig;

    // Test that invalid CA certificate fails validation
    let addr = get_test_addr();
    let tls = TlsClientConfig::new().with_ca_cert("/nonexistent/ca.pem");

    let config = ClientConfig::new(addr).with_tls(tls);

    let result = LanceClient::connect(config).await;

    // Should fail because CA cert doesn't exist
    assert!(result.is_err(), "Connection with invalid CA should fail");
    println!("Certificate validation correctly rejected invalid CA");
}

#[tokio::test]
#[ignore = "requires LANCE cluster with TLS enabled"]
async fn test_tls_cluster_communication() {
    // Test TLS works with cluster status queries
    let config = test_config();

    match LanceClient::connect(config).await {
        Ok(mut client) => {
            // Query cluster status over TLS
            let status = client.get_cluster_status().await;
            match status {
                Ok(cluster) => {
                    println!(
                        "Cluster status over TLS: {} nodes, leader: {:?}",
                        cluster.node_count, cluster.leader_id
                    );
                    assert!(cluster.node_count >= 1, "Should have at least one node");
                },
                Err(e) => {
                    println!("Cluster query failed (may be single-node): {:?}", e);
                },
            }
            client.close().await.unwrap();
        },
        Err(e) => {
            println!("Cluster TLS connection failed: {:?}", e);
        },
    }
}

// ============================================================================
// Connection Management Integration Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_connection_pool_basic() {
    use lnc_client::{ConnectionPool, ConnectionPoolConfig};

    let addr = get_test_addr();
    let config = ConnectionPoolConfig::new()
        .with_max_connections(5)
        .with_min_idle(1);

    let pool = ConnectionPool::new(&addr, config).await.unwrap();

    // Get a connection from pool
    let mut conn = pool.get().await.unwrap();

    // Verify connection works
    let latency = conn.ping().await.unwrap();
    println!("Pool connection ping latency: {:?}", latency);

    // Check pool stats
    let stats = pool.stats();
    assert!(
        stats.connections_created >= 1,
        "Should have created at least one connection"
    );
    println!("Pool stats: {:?}", stats);

    // Connection returned to pool on drop
    drop(conn);

    // Close pool
    pool.close().await;
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_connection_pool_concurrent_access() {
    use lnc_client::{ConnectionPool, ConnectionPoolConfig};
    use std::sync::Arc;

    let addr = get_test_addr();
    let config = ConnectionPoolConfig::new()
        .with_max_connections(3)
        .with_acquire_timeout(Duration::from_secs(5));

    let pool = Arc::new(ConnectionPool::new(&addr, config).await.unwrap());

    // Spawn multiple tasks that use connections concurrently
    let mut handles = vec![];
    for i in 0..5 {
        let pool = pool.clone();
        handles.push(tokio::spawn(async move {
            let mut conn = pool.get().await.unwrap();
            let latency = conn.ping().await.unwrap();
            println!("Task {} ping latency: {:?}", i, latency);
        }));
    }

    // Wait for all tasks
    for handle in handles {
        handle.await.unwrap();
    }

    let stats = pool.stats();
    println!("Concurrent access stats: {:?}", stats);

    pool.close().await;
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_reconnecting_client_basic() {
    use lnc_client::ReconnectingClient;

    let addr = get_test_addr();
    let mut client = ReconnectingClient::connect(&addr).await.unwrap();

    // Use the client
    let inner = client.client().await.unwrap();
    let latency = inner.ping().await.unwrap();
    println!("ReconnectingClient ping latency: {:?}", latency);

    // Check original address tracking
    assert_eq!(client.original_addr(), &addr);
    assert_eq!(client.reconnect_attempts(), 0);
}

#[tokio::test]
#[ignore = "requires LANCE cluster for failover testing"]
async fn test_reconnecting_client_leader_failover() {
    use lnc_client::ReconnectingClient;
    use std::net::SocketAddr;

    let addr = get_test_addr();
    let mut client = ReconnectingClient::connect(&addr)
        .await
        .unwrap()
        .with_max_attempts(3)
        .with_follow_leader(true);

    // Simulate leader address update
    let new_leader: SocketAddr = "127.0.0.1:1993".parse().unwrap();
    client.set_leader_addr(new_leader);

    assert_eq!(client.leader_addr(), Some(new_leader));
    println!("Leader address updated to {:?}", client.leader_addr());
}

#[tokio::test]
async fn test_connection_to_invalid_address() {
    // Test that connection to invalid address fails gracefully
    let config = ClientConfig {
        addr: "127.0.0.1:59999".parse().unwrap(), // Non-existent server
        connect_timeout: Duration::from_millis(100),
        read_timeout: Duration::from_secs(1),
        write_timeout: Duration::from_secs(1),
        keepalive_interval: Duration::from_secs(10),
        tls: None,
    };

    let result = LanceClient::connect(config).await;
    assert!(result.is_err(), "Should fail to connect to invalid address");
    println!("Connection to invalid address correctly failed");
}

// ============================================================================
// Producer Integration Tests
// ============================================================================

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_producer_connect_and_send() {
    use lnc_client::{Producer, ProducerConfig};

    let config = ProducerConfig::new()
        .with_batch_size(1024)
        .with_linger_ms(10);

    let addr = get_test_addr();
    let producer = Producer::connect(&addr, config).await.unwrap();

    // Create a topic first
    let mut client = LanceClient::connect(test_config()).await.unwrap();
    let topic_name = unique_topic_name("producer_test");
    let topic_info = client.create_topic(&topic_name).await.unwrap();
    let topic_id = topic_info.id;

    // Send some records
    for i in 0..10 {
        let ack = producer
            .send(topic_id, format!("message-{}", i).as_bytes())
            .await
            .unwrap();
        assert!(ack.batch_id > 0);
        assert_eq!(ack.topic_id, topic_id);
    }

    // Check metrics
    let metrics = producer.metrics();
    assert!(metrics.records_sent >= 10);
    assert!(metrics.bytes_sent > 0);

    // Cleanup
    producer.close().await.unwrap();
    client.delete_topic(topic_id).await.unwrap();
    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_producer_batching_and_flush() {
    use lnc_client::{Producer, ProducerConfig};

    let config = ProducerConfig::new()
        .with_batch_size(16 * 1024)  // Large batch
        .with_linger_ms(1000); // Long linger

    let addr = get_test_addr();
    let producer = Producer::connect(&addr, config).await.unwrap();

    // Create a topic
    let mut client = LanceClient::connect(test_config()).await.unwrap();
    let topic_name = unique_topic_name("producer_batch_test");
    let topic_info = client.create_topic(&topic_name).await.unwrap();
    let topic_id = topic_info.id;

    // Send records (should batch due to long linger)
    let start = Instant::now();
    for i in 0..5 {
        producer
            .send_async(topic_id, format!("batch-message-{}", i).as_bytes())
            .await
            .unwrap();
    }

    // Should be quick since async send doesn't wait for batch
    assert!(start.elapsed() < Duration::from_millis(100));

    // Explicit flush should send the batch
    producer.flush().await.unwrap();

    let metrics = producer.metrics();
    assert!(metrics.batches_sent >= 1);

    // Cleanup
    producer.close().await.unwrap();
    client.delete_topic(topic_id).await.unwrap();
    client.close().await.unwrap();
}

#[tokio::test]
#[ignore = "requires running LANCE server"]
async fn test_producer_metrics_tracking() {
    use lnc_client::{Producer, ProducerConfig};

    let config = ProducerConfig::new()
        .with_batch_size(1024)
        .with_linger_ms(5);

    let addr = get_test_addr();
    let producer = Producer::connect(&addr, config).await.unwrap();

    // Create a topic
    let mut client = LanceClient::connect(test_config()).await.unwrap();
    let topic_name = unique_topic_name("producer_metrics_test");
    let topic_info = client.create_topic(&topic_name).await.unwrap();
    let topic_id = topic_info.id;

    // Initial metrics should be zero
    let initial = producer.metrics();
    assert_eq!(initial.records_sent, 0);
    assert_eq!(initial.bytes_sent, 0);
    assert_eq!(initial.errors, 0);

    // Send records
    let record_count: u64 = 20;
    let record_size: u64 = 100;
    for i in 0..record_count {
        let data = format!("{:0>width$}", i, width = record_size as usize);
        producer.send(topic_id, data.as_bytes()).await.unwrap();
    }

    // Check metrics
    let final_metrics = producer.metrics();
    assert_eq!(final_metrics.records_sent, record_count);
    assert!(final_metrics.bytes_sent >= record_count * record_size);
    assert!(final_metrics.batches_sent >= 1);
    assert_eq!(final_metrics.errors, 0);

    // Cleanup
    producer.close().await.unwrap();
    client.delete_topic(topic_id).await.unwrap();
    client.close().await.unwrap();
}