erpc_analysis/
db_client.rs

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
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
//! Provides the `Neo4jAnalysisClient`, a concrete implementation of the
//! `AnalysisDatabase` trait for interacting with a Neo4j database for
//! eRPC's analysis tasks.
//!
//! This module includes:
//! - The client struct (`Neo4jAnalysisClient`) for executing queries.
//! - Methods for common analysis-related database operations, such as creating
//!   GDS graph projections.

use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use log::{debug, error, info, warn};

use neo4rs::{Error as Neo4rsDriverError, Graph, Query, RowStream};

use crate::config::Neo4jConfig;
use crate::graph::projections::{
    build_gds_drop_cypher, build_gds_project_cypher,
};
use crate::models::metrics::{
    CentralityAnalysisResult, CentralityDistribution, CentralityMetrics,
    GraphMetrics, NodeMetrics, PathAnalysisResult, PathResult,
};

use crate::db_trait::{
    AnalysisDatabase, AnalysisError, GraphProjectionParams,
};

use crate::models::partitions::{ComponentAnalysisResult, ConnectedComponent};

/// A client for interacting with Neo4j, tailored for eRPC analysis tasks.
pub struct Neo4jAnalysisClient {
    graph: Arc<Graph>,
}

impl Neo4jAnalysisClient {
    /// Creates a new `Neo4jAnalysisClient` instance.
    ///
    /// Establishes a connection to the Neo4j database using the provided
    /// configuration.
    ///
    /// # Arguments
    /// * `config` - A reference to `Neo4jConfig` containing the URI, username,
    ///   and password.
    ///
    /// # Errors
    /// Returns `AnalysisError::ConnectionFailed` if the connection cannot be
    /// established.
    pub async fn new(config: &Neo4jConfig) -> Result<Self, AnalysisError> {
        Graph::new(&config.uri, &config.username, &config.password)
            .await
            .map_err(|e: Neo4rsDriverError| {
                AnalysisError::ConnectionFailed(format!(
                    "Failed to connect to Neo4j at URI '{}': {}",
                    config.uri, e
                ))
            })
            .map(|graph_conn| Self {
                graph: Arc::new(graph_conn),
            })
    }
}

#[async_trait]
impl AnalysisDatabase for Neo4jAnalysisClient {
    /// Creates or recreates a GDS graph projection in Neo4j.
    ///
    /// This implementation first attempts to delete an existing projection
    /// with the same name to ensure idempotency, then creates a new one
    /// based on the provided parameters.
    ///
    /// # Arguments
    /// * `params` - A reference to `GraphProjectionParams` specifying the
    ///   projection name, node label, relationship types, and properties
    ///   to project.
    ///
    /// # Errors
    /// Returns `AnalysisError` if any step (deletion of old projection,
    /// creation of new projection) fails. This includes driver errors,
    /// query failures, or issues with GDS procedures
    async fn create_graph_projection(
        &self,
        params: &GraphProjectionParams,
    ) -> Result<(), AnalysisError> {
        // Attempt to delete existing projection first to ensure idempotency.
        // delete_graph_projection is designed to succeed even if the
        // projection doesn't exist.
        if let Err(e) =
            self.delete_graph_projection(&params.projection_name).await
        {
            warn!(
                "Attempt to delete old projection '{}' failed before \
                 creation: {:?}. Proceeding with creation attempt.",
                params.projection_name, e
            );
        }

        let project_query_cypher = build_gds_project_cypher(
            &params.projection_name,
            &params.node_label,
            &params.relationship_types,
            params.relationship_properties_to_project.as_deref(),
        );

        info!(
            "Executing GDS Projection for graph '{}' with node label '{}'",
            params.projection_name, params.node_label
        );
        debug!("GDS Projection Query: {}", project_query_cypher);
        let project_query = Query::new(project_query_cypher);

        let mut result_stream: RowStream = self
            .graph
            .execute(project_query)
            .await
            .map_err(AnalysisError::from)?;

        match result_stream.next().await {
            Ok(Some(row)) => {
                let projected_graph_name: String =
                    row.get::<String>("graphName").ok_or_else(|| {
                        AnalysisError::ProjectionCreationFailed {
                            projection_name: params.projection_name.clone(),
                            source_error:
                                "GDS projection report missing 'graphName'"
                                    .to_string(),
                        }
                    })?;

                let node_count: i64 =
                    row.get::<i64>("nodeCount").ok_or_else(|| {
                        AnalysisError::ProjectionCreationFailed {
                            projection_name: params.projection_name.clone(),
                            source_error:
                                "GDS projection report missing 'nodeCount'"
                                    .to_string(),
                        }
                    })?;

                let relationship_count: i64 =
                    row.get::<i64>("relationshipCount").ok_or_else(|| {
                        AnalysisError::ProjectionCreationFailed {
                            projection_name: params.projection_name.clone(),
                            source_error: "GDS projection report \
                                       missing 'relationshipCount'"
                                .to_string(),
                        }
                    })?;

                let project_millis: i64 =
                    row.get::<i64>("projectMillis").ok_or_else(|| {
                        AnalysisError::ProjectionCreationFailed {
                            projection_name: params.projection_name.clone(),
                            source_error:
                                "GDS projection report missing 'projectMillis'"
                                    .to_string(),
                        }
                    })?;

                info!(
                    "GDS Reported: Projected graph '{}' with {} nodes, \
                     {} relationships in {} ms.",
                    projected_graph_name,
                    node_count,
                    relationship_count,
                    project_millis
                );
                if projected_graph_name != params.projection_name {
                    warn!(
                        "Projected graph name from GDS ('{}') does not \
                         match requested name ('{}').",
                        projected_graph_name, params.projection_name
                    );
                }
            }
            Ok(None) => {
                return Err(AnalysisError::ProjectionCreationFailed {
                    projection_name: params.projection_name.clone(),
                    source_error: "GDS graph project query executed \
                                   but returned no rows."
                        .to_string(),
                });
            }
            Err(e) => {
                return Err(AnalysisError::ProjectionCreationFailed {
                    projection_name: params.projection_name.clone(),
                    source_error: format!(
                        "Failed to process result from GDS graph project \
                         query: {}",
                        e
                    ),
                });
            }
        }
        info!(
            "Graph projection command for '{}' completed.",
            params.projection_name
        );
        Ok(())
    }

    /// Deletes an existing GDS graph projection from Neo4j if it exists.
    ///
    /// This method first checks if the projection exists using
    /// `gds.graph.exists` (via `check_graph_projection_exists`).
    /// If it does, `gds.graph.drop` is called.
    ///
    /// The operation is idempotent and will succeed even if the
    /// projection does not initially exist.
    ///
    /// # Arguments
    /// * `projection_name` - The name of the GDS graph projection to delete.
    ///
    /// # Errors
    /// Returns `AnalysisError` if checking for existence or executing
    /// the drop query fails
    async fn delete_graph_projection(
        &self,
        projection_name: &str,
    ) -> Result<(), AnalysisError> {
        let exists =
            self.check_graph_projection_exists(projection_name).await?;

        if exists {
            info!(
                "GDS graph projection '{}' exists. Attempting to drop it.",
                projection_name
            );
            let drop_query_cypher = build_gds_drop_cypher(projection_name);
            let drop_query = Query::new(drop_query_cypher);

            match self.graph.execute(drop_query).await {
                Ok(mut drop_stream) => match drop_stream.next().await {
                    Ok(Some(row)) => {
                        let dropped_name_opt: Option<String> =
                            row.get::<String>("graphName");
                        info!(
                            "Successfully dropped GDS graph projection: '{}'. \
                             GDS returned: '{}'",
                            projection_name,
                            dropped_name_opt
                                .unwrap_or_else(|| "N/A".to_string())
                        );
                    }
                    Ok(None) => {
                        info!(
                            "GDS graph drop for '{}' returned no rows, \
                             assuming drop was successful.",
                            projection_name
                        );
                    }
                    Err(e) => {
                        warn!(
                            "Error processing result stream from GDS graph \
                             drop for '{}': {}. Assuming dropped.",
                            projection_name, e
                        );
                    }
                },
                Err(e_n4rs) => {
                    error!(
                        "Failed to execute GDS graph drop query for '{}': {}",
                        projection_name, e_n4rs
                    );
                    return Err(AnalysisError::ProjectionDropFailed {
                        projection_name: projection_name.to_string(),
                        source_error: format!(
                            "Failed to execute GDS graph drop query: {}",
                            e_n4rs
                        ),
                    });
                }
            }
        } else {
            info!(
                "GDS graph projection '{}' does not exist. No deletion \
                 needed.",
                projection_name
            );
        }
        Ok(())
    }

    /// Checks if a GDS graph projection with the given name exists in Neo4j.
    ///
    /// This method calls the `gds.graph.exists` procedure.
    ///
    /// # Arguments
    /// * `projection_name` - The name of the GDS graph projection to check.
    ///
    /// # Returns
    /// `Ok(true)` if the projection exists, `Ok(false)` otherwise.
    ///
    /// # Errors
    /// Returns `AnalysisError` if the query to `gds.graph.exists` fails
    /// or the result cannot be parsed correctly.
    async fn check_graph_projection_exists(
        &self,
        projection_name: &str,
    ) -> Result<bool, AnalysisError> {
        debug!(
            "Checking if GDS graph projection '{}' exists.",
            projection_name
        );
        let query_str = "CALL gds.graph.exists($projection_name) YIELD \
             graphName, exists RETURN exists";
        let query = Query::new(query_str.to_string())
            .param("projection_name", projection_name);

        let mut stream: RowStream = self
            .graph
            .execute(query)
            .await
            .map_err(AnalysisError::from)?;
        let row = stream
            .next()
            .await
            .map_err(AnalysisError::from)?
            .ok_or_else(|| {
                AnalysisError::QueryFailed(format!(
                    "gds.graph.exists query for '{}' returned no rows",
                    projection_name
                ))
            })?;

        let exists: bool = row.get::<bool>("exists").ok_or_else(|| {
            AnalysisError::QueryFailed(format!(
                "Failed to get 'exists' field from gds.graph.exists \
                 for '{}' or field was null",
                projection_name
            ))
        })?;

        debug!(
            "GDS graph projection '{}' exists status: {}",
            projection_name, exists
        );
        Ok(exists)
    }

    /// Calculates comprehensive graph metrics for a given GDS projection
    /// including basic counts (node count, relationship count), degree
    /// distribution, and degree statistics.
    async fn calculate_graph_metrics(
        &self,
        projection_name: &str,
    ) -> Result<GraphMetrics, AnalysisError> {
        info!(
            "Calculating graph metrics for GDS projection: '{}'",
            projection_name
        );

        // First get basic metrics (node count, relationship count) from GDS
        let query_str = "CALL gds.graph.list($projection_name) YIELD \
                                    graphName, nodeCount, relationshipCount \
                                    RETURN nodeCount, relationshipCount";
        let query = Query::new(query_str.to_string())
            .param("projection_name", projection_name);

        let mut stream: RowStream = self
            .graph
            .execute(query)
            .await
            .map_err(AnalysisError::from)?;

        if let Some(row) = stream.next().await.map_err(AnalysisError::from)? {
            let node_count: i64 =
                row.get::<i64>("nodeCount").ok_or_else(|| {
                    AnalysisError::QueryFailed(format!(
                    "Failed to get 'nodeCount' for projection '{}' or field \
                     was null",
                    projection_name
                ))
                })?;

            let relationship_count: i64 =
                row.get::<i64>("relationshipCount").ok_or_else(|| {
                    AnalysisError::QueryFailed(format!(
                        "Failed to get 'relationshipCount' for projection \
                         '{}' or field was null",
                        projection_name
                    ))
                })?;

            info!(
                "Basic metrics retrieved: {} nodes, {} relationships",
                node_count, relationship_count
            );

            // Calculate node degrees for analysis
            let node_degrees =
                self.calculate_node_degrees(projection_name).await?;

            if node_degrees.is_empty() {
                return Ok(GraphMetrics {
                    node_count: Some(node_count),
                    relationship_count: Some(relationship_count),
                    degree_distribution: Some(HashMap::new()),
                    average_degree: Some(0.0),
                    max_degree: Some(0),
                    min_degree: Some(0),
                });
            }

            // Calculate degree distribution and statistics
            let mut degree_distribution = HashMap::new();
            let mut total_degree_sum = 0i64;
            let mut max_degree = 0i64;
            let mut min_degree = i64::MAX;

            for node in &node_degrees {
                let degree = node.total_degree;
                *degree_distribution.entry(degree).or_insert(0) += 1;
                total_degree_sum += degree;
                max_degree = max_degree.max(degree);
                min_degree = min_degree.min(degree);
            }

            // Handle edge case where all nodes have degree 0
            if min_degree == i64::MAX {
                min_degree = 0;
            }

            let average_degree = if !node_degrees.is_empty() {
                total_degree_sum as f64 / node_degrees.len() as f64
            } else {
                0.0
            };

            info!(
                "Comprehensive metrics calculated: avg_degree={:.2}, \
                 max_degree={}, min_degree={}, distribution_size={}",
                average_degree,
                max_degree,
                min_degree,
                degree_distribution.len()
            );

            Ok(GraphMetrics {
                node_count: Some(node_count),
                relationship_count: Some(relationship_count),
                degree_distribution: Some(degree_distribution),
                average_degree: Some(average_degree),
                max_degree: Some(max_degree),
                min_degree: Some(min_degree),
            })
        } else {
            // If gds.graph.list stream is empty for the projection,
            // it implies the projection doesn't exist.
            Err(AnalysisError::ProjectionNotFound(
                projection_name.to_string(),
            ))
        }
    }

    /// Calculates node-level degree metrics for all nodes in a given
    /// GDS projection.
    /// Uses both Neo4j GDS library for total degree and direct Cypher
    /// for in/out degree calculation.
    async fn calculate_node_degrees(
        &self,
        projection_name: &str,
    ) -> Result<Vec<NodeMetrics>, AnalysisError> {
        info!(
            "Calculating node metrics for GDS projection: '{}'",
            projection_name
        );

        // Use direct Cypher query to calculate in-degree and out-degree
        // This approach counts actual relationships rather than using
        // GDS degree centrality
        let query_str = "
            MATCH (r:Relay)
            OPTIONAL MATCH (r)-[out:CIRCUIT_SUCCESS]->()
            OPTIONAL MATCH ()-[in:CIRCUIT_SUCCESS]->(r)
            RETURN r.fingerprint as fingerprint,
                   count(DISTINCT in) as in_degree,
                   count(DISTINCT out) as out_degree,
                   count(DISTINCT in) + count(DISTINCT out) as total_degree
            ORDER BY total_degree DESC
        ";

        let query = Query::new(query_str.to_string());
        let mut stream: RowStream = self
            .graph
            .execute(query)
            .await
            .map_err(AnalysisError::from)?;

        let mut node_metrics = Vec::new();

        while let Some(row) =
            stream.next().await.map_err(AnalysisError::from)?
        {
            let fingerprint: String =
                row.get::<String>("fingerprint").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'fingerprint' field from node degree \
                         calculation"
                            .to_string(),
                    )
                })?;

            let in_degree: i64 =
                row.get::<i64>("in_degree").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'in_degree' field from node degree \
                     calculation"
                            .to_string(),
                    )
                })?;

            let out_degree: i64 =
                row.get::<i64>("out_degree").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'out_degree' field from node degree \
                     calculation"
                            .to_string(),
                    )
                })?;

            let total_degree: i64 =
                row.get::<i64>("total_degree").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'total_degree' field from node degree \
                     calculation"
                            .to_string(),
                    )
                })?;

            node_metrics.push(NodeMetrics {
                fingerprint,
                in_degree,
                out_degree,
                total_degree,
            });
        }

        Ok(node_metrics)
    }

    /// Calculates weakly connected components using Neo4j GDS WCC algorithm.
    /// Returns analysis results containing components, sizes, and statistics.
    async fn calculate_weakly_connected_components(
        &self,
        projection_name: &str,
    ) -> Result<ComponentAnalysisResult, AnalysisError> {
        info!(
            "Calculating weakly connected components for projection: '{}'",
            projection_name
        );

        // Execute Neo4j GDS WCC algorithm
        let wcc_query = format!(
            "CALL gds.wcc.stream('{}')
             YIELD nodeId, componentId
             RETURN gds.util.asNode(nodeId).fingerprint AS relay_fingerprint,
                    componentId
             ORDER BY componentId, relay_fingerprint",
            projection_name
        );

        debug!("WCC Query: {}", wcc_query);
        let query = Query::new(wcc_query);
        let mut stream: RowStream =
            self.graph.execute(query).await.map_err(|e| {
                error!("Failed to execute WCC query: {:?}", e);
                AnalysisError::AlgorithmError(format!(
                    "WCC algorithm execution failed for projection '{}': {}",
                    projection_name, e
                ))
            })?;

        // Group results by component ID
        let mut component_map: HashMap<i64, Vec<String>> = HashMap::new();

        while let Some(row) =
            stream.next().await.map_err(AnalysisError::from)?
        {
            let relay_fingerprint: String =
                row.get::<String>("relay_fingerprint").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'relay_fingerprint' from WCC result"
                            .to_string(),
                    )
                })?;

            let component_id: i64 =
                row.get::<i64>("componentId").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'componentId' from WCC result"
                            .to_string(),
                    )
                })?;

            component_map
                .entry(component_id)
                .or_default()
                .push(relay_fingerprint);
        }

        // Convert to ConnectedComponent structs
        let mut components: Vec<ConnectedComponent> = component_map
            .into_iter()
            .map(|(component_id, relay_fingerprints)| {
                let size = relay_fingerprints.len();
                ConnectedComponent {
                    component_id,
                    relay_fingerprints,
                    size,
                }
            })
            .collect();

        // Sort components by size (largest first)
        components.sort_by(|a, b| b.size.cmp(&a.size));

        // Calculate statistics
        let total_components = components.len();
        let largest_component_size =
            components.first().map(|c| c.size).unwrap_or(0);
        let smallest_component_size =
            components.last().map(|c| c.size).unwrap_or(0);

        // Calculate size distribution
        let mut component_size_distribution = HashMap::new();
        for component in &components {
            *component_size_distribution
                .entry(component.size)
                .or_insert(0) += 1;
        }

        // Calculate isolation ratio (percentage of nodes in largest component)
        let total_nodes: usize = components.iter().map(|c| c.size).sum();
        let isolation_ratio = if total_nodes > 0 {
            (largest_component_size as f64 / total_nodes as f64) * 100.0
        } else {
            0.0
        };

        info!(
            "WCC analysis complete: {} components, largest: {}, \
             smallest: {}, isolation ratio: {:.2}%",
            total_components,
            largest_component_size,
            smallest_component_size,
            isolation_ratio
        );

        Ok(ComponentAnalysisResult {
            components,
            total_components: Some(total_components),
            largest_component_size: Some(largest_component_size),
            smallest_component_size: Some(smallest_component_size),
            component_size_distribution: Some(component_size_distribution),
            isolation_ratio: Some(isolation_ratio),
            modularity: None, // WCC analysis doesn't calculate modularity
        })
    }

    /// Calculates strongly connected components using Neo4j GDS SCC algorithm.
    /// Returns analysis results containing components, sizes, and statistics.
    async fn calculate_strongly_connected_components(
        &self,
        projection_name: &str,
    ) -> Result<ComponentAnalysisResult, AnalysisError> {
        info!(
            "Calculating strongly connected components for projection: '{}'",
            projection_name
        );

        // Execute Neo4j GDS SCC algorithm
        let scc_query = format!(
            "CALL gds.scc.stream('{}')
             YIELD nodeId, componentId
             RETURN gds.util.asNode(nodeId).fingerprint AS relay_fingerprint,
                    componentId
             ORDER BY componentId, relay_fingerprint",
            projection_name
        );

        debug!("SCC Query: {}", scc_query);
        let query = Query::new(scc_query);
        let mut stream: RowStream =
            self.graph.execute(query).await.map_err(|e| {
                error!("Failed to execute SCC query: {:?}", e);
                AnalysisError::AlgorithmError(format!(
                    "SCC algorithm execution failed for projection '{}': {}",
                    projection_name, e
                ))
            })?;

        // Group results by component ID
        let mut component_map: HashMap<i64, Vec<String>> = HashMap::new();

        while let Some(row) =
            stream.next().await.map_err(AnalysisError::from)?
        {
            let relay_fingerprint: String =
                row.get::<String>("relay_fingerprint").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'relay_fingerprint' from SCC result"
                            .to_string(),
                    )
                })?;

            let component_id: i64 =
                row.get::<i64>("componentId").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'componentId' from SCC result"
                            .to_string(),
                    )
                })?;

            component_map
                .entry(component_id)
                .or_default()
                .push(relay_fingerprint);
        }

        // Convert to ConnectedComponent structs
        let mut components: Vec<ConnectedComponent> = component_map
            .into_iter()
            .map(|(component_id, relay_fingerprints)| {
                let size = relay_fingerprints.len();
                ConnectedComponent {
                    component_id,
                    relay_fingerprints,
                    size,
                }
            })
            .collect();

        // Sort components by size (largest first)
        components.sort_by(|a, b| b.size.cmp(&a.size));

        // Calculate statistics
        let total_components = components.len();
        let largest_component_size =
            components.first().map(|c| c.size).unwrap_or(0);
        let smallest_component_size =
            components.last().map(|c| c.size).unwrap_or(0);

        // Calculate size distribution
        let mut component_size_distribution = HashMap::new();
        for component in &components {
            *component_size_distribution
                .entry(component.size)
                .or_insert(0) += 1;
        }

        // Calculate isolation ratio (percentage of nodes in largest component)
        let total_nodes: usize = components.iter().map(|c| c.size).sum();
        let isolation_ratio = if total_nodes > 0 {
            (largest_component_size as f64 / total_nodes as f64) * 100.0
        } else {
            0.0
        };

        info!(
            "SCC analysis complete: {} components, largest: {}, \
             smallest: {}, isolation ratio: {:.2}%",
            total_components,
            largest_component_size,
            smallest_component_size,
            isolation_ratio
        );

        Ok(ComponentAnalysisResult {
            components,
            total_components: Some(total_components),
            largest_component_size: Some(largest_component_size),
            smallest_component_size: Some(smallest_component_size),
            component_size_distribution: Some(component_size_distribution),
            isolation_ratio: Some(isolation_ratio),
            modularity: None, // SCC analysis doesn't calculate modularity
        })
    }

    /// Calculates communities using Neo4j GDS Louvain algorithm.
    /// Returns analysis results containing communities, sizes, and statistics.
    async fn calculate_louvain_communities(
        &self,
        projection_name: &str,
        params: &crate::config::LouvainConfig,
    ) -> Result<ComponentAnalysisResult, AnalysisError> {
        info!(
            "Calculating Louvain communities for projection: '{}'",
            projection_name
        );

        // First, run the Louvain algorithm and store community property
        let community_property = "louvainCommunity";
        let louvain_write_query = format!(
            "CALL gds.louvain.write('{}', {{
                writeProperty: '{}',
                maxIterations: {},
                tolerance: {},
                includeIntermediateCommunities: {}
            }})
            YIELD communityCount, ranLevels, modularity
            RETURN communityCount, ranLevels, modularity",
            projection_name,
            community_property,
            params.max_iterations,
            params.tolerance,
            params.include_intermediate_communities
        );

        debug!("Louvain Write Query: {}", louvain_write_query);
        let write_query = Query::new(louvain_write_query);
        let mut write_stream: RowStream =
            self.graph.execute(write_query).await.map_err(|e| {
                error!("Failed to execute Louvain write query: {:?}", e);
                AnalysisError::AlgorithmError(format!(
                "Louvain algorithm execution failed for projection '{}': {}",
                projection_name, e
            ))
            })?;

        // Get the modularity from the write operation
        let mut modularity_score = None;
        if let Some(row) =
            write_stream.next().await.map_err(AnalysisError::from)?
        {
            let community_count: i64 =
                row.get::<i64>("communityCount").unwrap_or(0);
            let ran_levels: i64 = row.get::<i64>("ranLevels").unwrap_or(0);
            let modularity: f64 = row.get::<f64>("modularity").unwrap_or(0.0);

            info!(
                "Louvain algorithm completed: {} communities, {} levels, \
                 modularity: {:.4}",
                community_count, ran_levels, modularity
            );
            modularity_score = Some(modularity);
        }

        // Now stream the results to get community assignments
        let louvain_stream_query = format!(
            "MATCH (n:Relay)
             WHERE n.{} IS NOT NULL
             RETURN n.fingerprint AS relay_fingerprint, n.{} AS communityId
             ORDER BY communityId, relay_fingerprint",
            community_property, community_property
        );

        debug!("Louvain Stream Query: {}", louvain_stream_query);
        let query = Query::new(louvain_stream_query);
        let mut stream: RowStream =
            self.graph.execute(query).await.map_err(|e| {
                error!("Failed to execute Louvain stream query: {:?}", e);
                AnalysisError::AlgorithmError(format!(
                    "Louvain results streaming failed for projection '{}': {}",
                    projection_name, e
                ))
            })?;

        // Group results by community ID
        let mut community_map: HashMap<i64, Vec<String>> = HashMap::new();

        while let Some(row) =
            stream.next().await.map_err(AnalysisError::from)?
        {
            let relay_fingerprint: String =
                row.get::<String>("relay_fingerprint").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'relay_fingerprint' from Louvain result"
                            .to_string(),
                    )
                })?;

            let community_id: i64 =
                row.get::<i64>("communityId").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'communityId' from Louvain result"
                            .to_string(),
                    )
                })?;

            community_map
                .entry(community_id)
                .or_default()
                .push(relay_fingerprint);
        }

        // Convert to ConnectedComponent structs (reusing the same
        // structure for communities)
        let mut communities: Vec<ConnectedComponent> = community_map
            .into_iter()
            .map(|(community_id, relay_fingerprints)| {
                let size = relay_fingerprints.len();
                ConnectedComponent {
                    component_id: community_id,
                    relay_fingerprints,
                    size,
                }
            })
            .collect();

        // Sort communities by size (largest first)
        communities.sort_by(|a, b| b.size.cmp(&a.size));

        // Calculate statistics
        let total_communities = communities.len();
        let largest_community_size =
            communities.first().map(|c| c.size).unwrap_or(0);
        let smallest_community_size =
            communities.last().map(|c| c.size).unwrap_or(0);

        // Calculate size distribution
        let mut community_size_distribution = HashMap::new();
        for community in &communities {
            *community_size_distribution
                .entry(community.size)
                .or_insert(0) += 1;
        }

        // Calculate isolation ratio (percentage of nodes in largest community)
        let total_nodes: usize = communities.iter().map(|c| c.size).sum();
        let isolation_ratio = if total_nodes > 0 {
            (largest_community_size as f64 / total_nodes as f64) * 100.0
        } else {
            0.0
        };

        // Clean up community property from nodes
        let cleanup_query =
            format!("MATCH (n:Relay) REMOVE n.{}", community_property);
        let _ = self.graph.execute(Query::new(cleanup_query)).await;

        info!(
            "Louvain analysis complete: {} communities, largest: {}, \
             smallest: {}, isolation ratio: {:.2}%, modularity: {:.4}",
            total_communities,
            largest_community_size,
            smallest_community_size,
            isolation_ratio,
            modularity_score.unwrap_or(0.0)
        );

        Ok(ComponentAnalysisResult {
            components: communities,
            total_components: Some(total_communities),
            largest_component_size: Some(largest_community_size),
            smallest_component_size: Some(smallest_community_size),
            component_size_distribution: Some(community_size_distribution),
            isolation_ratio: Some(isolation_ratio),
            modularity: modularity_score,
        })
    }

    /// Calculates communities using Neo4j GDS Label Propagation algorithm.
    /// Returns analysis results containing communities, sizes, and statistics.
    async fn calculate_label_propagation_communities(
        &self,
        projection_name: &str,
        params: &crate::config::LabelPropagationConfig,
    ) -> Result<ComponentAnalysisResult, AnalysisError> {
        info!(
            "Calculating Label Propagation communities for projection: '{}'",
            projection_name
        );

        // Use mutate mode to store community property in the projection for
        // modularity calculation
        // Use timestamp to create unique property name
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis();
        let community_property = format!("lpaCommunity_{}", timestamp);

        // Clean up any existing community properties first
        let cleanup_query = format!(
            "CALL gds.graph.nodeProperties.drop('{}', ['lpaCommunity'], \
             {{failIfMissing: false}}) YIELD propertiesRemoved",
            projection_name
        );
        let _ = self.graph.execute(Query::new(cleanup_query)).await;

        let lpa_mutate_query = format!(
            "CALL gds.labelPropagation.mutate('{}', {{
                maxIterations: {},
                mutateProperty: '{}'
            }})
            YIELD communityCount, ranIterations
            RETURN communityCount, ranIterations",
            projection_name, params.max_iterations, community_property
        );

        debug!("Label Propagation Mutate Query: {}", lpa_mutate_query);
        let mutate_query = Query::new(lpa_mutate_query);
        let mut mutate_stream: RowStream =
            self.graph.execute(mutate_query).await.map_err(|e| {
                error!(
                    "Failed to execute Label Propagation mutate query: {:?}",
                    e
                );
                AnalysisError::AlgorithmError(format!(
                    "Label Propagation algorithm execution failed for \
                 projection '{}': {}",
                    projection_name, e
                ))
            })?;

        // Get basic stats from the mutate operation
        if let Some(row) =
            mutate_stream.next().await.map_err(AnalysisError::from)?
        {
            let community_count: i64 =
                row.get::<i64>("communityCount").unwrap_or(0);
            let ran_iterations: i64 =
                row.get::<i64>("ranIterations").unwrap_or(0);

            info!(
                "Label Propagation algorithm completed: {} communities, \
                 {} iterations",
                community_count, ran_iterations
            );
        }

        // Calculate modularity using the stored community property
        let modularity_score = match self
            .calculate_modularity(projection_name, &community_property)
            .await
        {
            Ok(modularity) => {
                info!(
                    "Successfully calculated modularity for LPA \
                     communities: {:.4}",
                    modularity
                );
                Some(modularity)
            }
            Err(e) => {
                error!(
                    "Failed to calculate modularity for LPA communities: {}",
                    e
                );
                warn!(
                    "Modularity calculation failed despite community \
                     property being stored in projection"
                );
                None
            }
        };

        // Now stream the results from the projection to get community
        // assignments
        let lpa_stream_query = format!(
            "CALL gds.graph.nodeProperty.stream('{}', '{}')
             YIELD nodeId, propertyValue
             RETURN gds.util.asNode(nodeId).fingerprint AS relay_fingerprint,
                    propertyValue AS communityId
             ORDER BY communityId, relay_fingerprint",
            projection_name, community_property
        );

        debug!("Label Propagation Stream Query: {}", lpa_stream_query);
        let query = Query::new(lpa_stream_query);
        let mut stream: RowStream =
            self.graph.execute(query).await.map_err(|e| {
                error!(
                    "Failed to execute Label Propagation stream query: {:?}",
                    e
                );
                AnalysisError::AlgorithmError(format!(
                    "Label Propagation results streaming failed for \
                 projection '{}': {}",
                    projection_name, e
                ))
            })?;

        // Group results by community ID
        let mut community_map: HashMap<i64, Vec<String>> = HashMap::new();

        while let Some(row) =
            stream.next().await.map_err(AnalysisError::from)?
        {
            let relay_fingerprint: String =
                row.get::<String>("relay_fingerprint").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'relay_fingerprint' from Label \
                     Propagation result"
                            .to_string(),
                    )
                })?;

            let community_id: i64 =
                row.get::<i64>("communityId").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get 'communityId' from Label Propagation \
                     result"
                            .to_string(),
                    )
                })?;

            community_map
                .entry(community_id)
                .or_default()
                .push(relay_fingerprint);
        }

        // Convert to ConnectedComponent structs (reusing the same structure
        // for communities)
        let mut communities: Vec<ConnectedComponent> = community_map
            .into_iter()
            .map(|(community_id, relay_fingerprints)| {
                let size = relay_fingerprints.len();
                ConnectedComponent {
                    component_id: community_id,
                    relay_fingerprints,
                    size,
                }
            })
            .collect();

        // Sort communities by size (largest first)
        communities.sort_by(|a, b| b.size.cmp(&a.size));

        // Calculate statistics
        let total_communities = communities.len();
        let largest_community_size =
            communities.first().map(|c| c.size).unwrap_or(0);
        let smallest_community_size =
            communities.last().map(|c| c.size).unwrap_or(0);

        // Calculate size distribution
        let mut community_size_distribution = HashMap::new();
        for community in &communities {
            *community_size_distribution
                .entry(community.size)
                .or_insert(0) += 1;
        }

        // Calculate isolation ratio (percentage of nodes in largest community)
        let total_nodes: usize = communities.iter().map(|c| c.size).sum();
        let isolation_ratio = if total_nodes > 0 {
            (largest_community_size as f64 / total_nodes as f64) * 100.0
        } else {
            0.0
        };

        info!(
            "Label Propagation analysis complete: {} communities, \
             largest: {}, smallest: {}, isolation ratio: {:.2}%, \
             modularity: {}",
            total_communities,
            largest_community_size,
            smallest_community_size,
            isolation_ratio,
            modularity_score
                .map(|m| format!("{:.4}", m))
                .unwrap_or_else(|| "Not calculated".to_string())
        );

        Ok(ComponentAnalysisResult {
            components: communities,
            total_components: Some(total_communities),
            largest_component_size: Some(largest_community_size),
            smallest_component_size: Some(smallest_community_size),
            component_size_distribution: Some(community_size_distribution),
            isolation_ratio: Some(isolation_ratio),
            modularity: modularity_score,
        })
    }

    /// Calculates modularity score for a given community assignment.
    /// Higher modularity indicates better community structure.
    async fn calculate_modularity(
        &self,
        projection_name: &str,
        community_property: &str,
    ) -> Result<f64, AnalysisError> {
        info!(
            "Calculating modularity for projection: '{}' with community \
             property: '{}'",
            projection_name, community_property
        );

        // Use Neo4j GDS modularity stats to calculate overall modularity
        let modularity_query = format!(
            "CALL gds.modularity.stats('{}', {{
                communityProperty: '{}'
            }})
            YIELD modularity
            RETURN modularity",
            projection_name, community_property
        );

        debug!("Modularity Query: {}", modularity_query);
        let query = Query::new(modularity_query);
        let mut stream: RowStream =
            self.graph.execute(query).await.map_err(|e| {
                error!("Failed to execute modularity query: {:?}", e);
                AnalysisError::AlgorithmError(format!(
                    "Modularity calculation failed for projection '{}' with \
                     community property '{}': {}",
                    projection_name, community_property, e
                ))
            })?;

        if let Some(row) = stream.next().await.map_err(AnalysisError::from)? {
            let modularity: f64 =
                row.get::<f64>("modularity").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                    "Failed to get 'modularity' field from modularity stats \
                     result"
                        .to_string(),
                )
                })?;

            info!(
                "Modularity calculation complete: {:.4} for community \
                 property: '{}'",
                modularity, community_property
            );

            Ok(modularity)
        } else {
            Err(AnalysisError::AlgorithmError(
                "No modularity result returned from gds.modularity.stats"
                    .to_string(),
            ))
        }
    }

    /// Classifies connected components by geographic location (country)
    async fn classify_components_by_geography(
        &self,
        components: &[ConnectedComponent],
    ) -> Result<
        crate::models::partitions::PartitionClassificationResult,
        AnalysisError,
    > {
        info!("Classifying {} components by geography", components.len());

        if components.is_empty() {
            return Ok(
                crate::models::partitions::PartitionClassificationResult {
                    classification_type: crate::models::partitions::
                        ClassificationType::Geographic,
                    groups: Vec::new(),
                    metrics: crate::models::partitions::ClassificationMetrics {
                        total_groups: 0,
                        groups_with_partitions: 0,
                        classification_coverage: 0.0,
                        largest_group_size: 0,
                        average_group_size: 0.0,
                        diversity_score: 0.0,
                        partition_correlation: 0.0,
                    },
                    unclassified_relays: Vec::new(),
                },
            );
        }

        // Get geographic metadata for all relays in the components
        let mut all_fingerprints = Vec::new();
        for component in components {
            all_fingerprints
                .extend(component.relay_fingerprints.iter().cloned());
        }

        let total_relays = all_fingerprints.len();

        // Process in batches to handle large datasets efficiently
        const BATCH_SIZE: usize = 1000;
        let mut geography_map: HashMap<String, String> = HashMap::new();
        let mut total_processed = 0;

        for batch in all_fingerprints.chunks(BATCH_SIZE) {
            let geography_query = "UNWIND $fingerprints AS fingerprint
                 MATCH (r:Relay {fingerprint: fingerprint})
                 RETURN r.fingerprint AS relay_fingerprint,
                   r.country AS country
                 ORDER BY r.country, r.fingerprint"
                .to_string();

            debug!(
                "Geography Query batch {}: {} relays",
                total_processed / BATCH_SIZE + 1,
                batch.len()
            );

            let query = Query::new(geography_query)
                .param("fingerprints", batch.to_vec());
            let mut stream: RowStream =
                self.graph.execute(query).await.map_err(|e| {
                    error!("Failed to execute geography query: {:?}", e);
                    AnalysisError::QueryFailed(format!(
                        "Geography classification query failed: {}",
                        e
                    ))
                })?;

            // Process batch results
            let mut batch_count = 0;
            while let Some(row) =
                stream.next().await.map_err(AnalysisError::from)?
            {
                batch_count += 1;
                let fingerprint: String = row
                    .get::<String>("relay_fingerprint")
                    .ok_or_else(|| {
                        AnalysisError::QueryFailed(
                            "Failed to get relay_fingerprint from result"
                                .to_string(),
                        )
                    })?;

                let country: Option<String> = row.get::<String>("country");
                if let Some(country_code) = country {
                    geography_map.insert(fingerprint, country_code);
                }
            }

            total_processed += batch.len();
            debug!(
                "Processed batch: {} rows, total processed: {}",
                batch_count, total_processed
            );
        }

        debug!(
            "Geography classification: processed {} relays total, \
             found {} with country data",
            total_processed,
            geography_map.len()
        );

        // Group components by country
        let mut country_groups: HashMap<String, Vec<String>> = HashMap::new();
        let mut component_mapping: HashMap<String, HashMap<i64, usize>> =
            HashMap::new();
        let mut unclassified_relays = Vec::new();

        for component in components {
            let mut country_relays: HashMap<String, Vec<String>> =
                HashMap::new();

            for fingerprint in &component.relay_fingerprints {
                if let Some(country) = geography_map.get(fingerprint) {
                    country_relays
                        .entry(country.clone())
                        .or_default()
                        .push(fingerprint.clone());
                } else {
                    unclassified_relays.push(fingerprint.clone());
                }
            }

            // Add relays to country groups and track component mapping
            for (country, relays) in country_relays {
                country_groups
                    .entry(country.clone())
                    .or_default()
                    .extend(relays.clone());
                *component_mapping
                    .entry(country.clone())
                    .or_default()
                    .entry(component.component_id)
                    .or_insert(0) += relays.len();
            }
        }

        // Build classification groups
        let mut groups = Vec::new();
        let mut isolation_scores = Vec::new();

        for (country, relays) in country_groups {
            // Calculate isolation score: percentage of relays NOT in
            // largest component
            let isolation_score =
                if let Some(component_map) = component_mapping.get(&country) {
                    let total_relays_in_group = relays.len();
                    let largest_component_size =
                        component_map.values().max().unwrap_or(&0);

                    if total_relays_in_group > 0 {
                        let non_largest_component_relays =
                            total_relays_in_group - largest_component_size;
                        (non_largest_component_relays as f64
                            / total_relays_in_group as f64)
                            * 100.0
                    } else {
                        0.0
                    }
                } else {
                    0.0
                };

            isolation_scores.push(isolation_score);

            groups.push(crate::models::partitions::ClassificationGroup {
                identifier: country.clone(),
                relay_fingerprints: relays.clone(),
                component_mapping: component_mapping
                    .get(&country)
                    .cloned()
                    .unwrap_or_default(),
                isolation_score,
            });
        }

        // Calculate metrics
        let metrics = self.calculate_classification_metrics(
            &groups,
            total_relays,
            &isolation_scores,
        );

        info!(
            "Geographic classification complete: {} countries, {:.1}% \
             coverage, {} with partitions",
            groups.len(),
            metrics.classification_coverage,
            metrics.groups_with_partitions
        );

        Ok(crate::models::partitions::PartitionClassificationResult {
            classification_type:
                crate::models::partitions::ClassificationType::Geographic,
            groups,
            metrics,
            unclassified_relays,
        })
    }

    /// Classifies connected components by ASN
    async fn classify_components_by_asn(
        &self,
        components: &[ConnectedComponent],
    ) -> Result<
        crate::models::partitions::PartitionClassificationResult,
        AnalysisError,
    > {
        info!("Classifying {} components by ASN", components.len());

        if components.is_empty() {
            return Ok(
                crate::models::partitions::PartitionClassificationResult {
                    classification_type:
                        crate::models::partitions::ClassificationType::ASN,
                    groups: Vec::new(),
                    metrics:
                        crate::models::partitions::ClassificationMetrics {
                            total_groups: 0,
                            groups_with_partitions: 0,
                            classification_coverage: 0.0,
                            largest_group_size: 0,
                            average_group_size: 0.0,
                            diversity_score: 0.0,
                            partition_correlation: 0.0,
                        },
                    unclassified_relays: Vec::new(),
                },
            );
        }

        // Get ASN metadata for all relays in the components
        let mut all_fingerprints = Vec::new();
        for component in components {
            all_fingerprints
                .extend(component.relay_fingerprints.iter().cloned());
        }

        let total_relays = all_fingerprints.len();

        // Process in batches to handle large datasets efficiently
        const BATCH_SIZE: usize = 1000;
        let mut asn_map: HashMap<String, String> = HashMap::new();
        let mut total_processed = 0;

        for batch in all_fingerprints.chunks(BATCH_SIZE) {
            let asn_query = "UNWIND $fingerprints AS fingerprint
                 MATCH (r:Relay {fingerprint: fingerprint})
                 RETURN r.fingerprint AS relay_fingerprint, r.asn AS asn
                 ORDER BY r.asn, r.fingerprint"
                .to_string();

            debug!(
                "ASN Query batch {}: {} relays",
                total_processed / BATCH_SIZE + 1,
                batch.len()
            );

            let query =
                Query::new(asn_query).param("fingerprints", batch.to_vec());
            let mut stream: RowStream =
                self.graph.execute(query).await.map_err(|e| {
                    error!("Failed to execute ASN query: {:?}", e);
                    AnalysisError::QueryFailed(format!(
                        "ASN classification query failed: {}",
                        e
                    ))
                })?;

            // Process batch results
            let mut batch_count = 0;
            while let Some(row) =
                stream.next().await.map_err(AnalysisError::from)?
            {
                batch_count += 1;
                let fingerprint: String = row
                    .get::<String>("relay_fingerprint")
                    .ok_or_else(|| {
                        AnalysisError::QueryFailed(
                            "Failed to get relay_fingerprint from ASN result"
                                .to_string(),
                        )
                    })?;

                let asn: Option<String> =
                    row.get::<i64>("asn").map(|v| v.to_string());

                if let Some(asn_number) = asn {
                    // Only add ASNs that are not empty or null
                    if !asn_number.is_empty()
                        && asn_number != "null"
                        && asn_number != "0"
                    {
                        asn_map.insert(fingerprint, asn_number);
                    }
                }
            }

            total_processed += batch.len();
            debug!(
                "Processed batch: {} rows, total processed: {}",
                batch_count, total_processed
            );
        }

        debug!(
            "ASN classification: processed {} relays total, \
             found {} with ASN data",
            total_processed,
            asn_map.len()
        );

        // Group components by ASN
        let mut asn_groups: HashMap<String, Vec<String>> = HashMap::new();
        let mut component_mapping: HashMap<String, HashMap<i64, usize>> =
            HashMap::new();
        let mut unclassified_relays = Vec::new();

        for component in components {
            let mut asn_relays: HashMap<String, Vec<String>> = HashMap::new();

            for fingerprint in &component.relay_fingerprints {
                if let Some(asn) = asn_map.get(fingerprint) {
                    asn_relays
                        .entry(asn.clone())
                        .or_default()
                        .push(fingerprint.clone());
                } else {
                    unclassified_relays.push(fingerprint.clone());
                }
            }

            // Add relays to ASN groups and track component mapping
            for (asn, relays) in asn_relays {
                asn_groups
                    .entry(asn.clone())
                    .or_default()
                    .extend(relays.clone());
                *component_mapping
                    .entry(asn.clone())
                    .or_default()
                    .entry(component.component_id)
                    .or_insert(0) += relays.len();
            }
        }

        // Build classification groups with isolation score calculation
        let mut groups = Vec::new();
        let mut isolation_scores = Vec::new();

        for (asn, relays) in asn_groups {
            // Calculate isolation score: percentage of relays NOT in
            // largest component
            let isolation_score =
                if let Some(component_map) = component_mapping.get(&asn) {
                    let total_relays_in_group = relays.len();
                    let largest_component_size =
                        component_map.values().max().unwrap_or(&0);

                    if total_relays_in_group > 0 {
                        let non_largest_component_relays =
                            total_relays_in_group - largest_component_size;
                        (non_largest_component_relays as f64
                            / total_relays_in_group as f64)
                            * 100.0
                    } else {
                        0.0
                    }
                } else {
                    0.0
                };

            isolation_scores.push(isolation_score);

            groups.push(crate::models::partitions::ClassificationGroup {
                identifier: asn.clone(),
                relay_fingerprints: relays.clone(),
                component_mapping: component_mapping
                    .get(&asn)
                    .cloned()
                    .unwrap_or_default(),
                isolation_score,
            });
        }

        // Calculate metrics
        let metrics = self.calculate_classification_metrics(
            &groups,
            total_relays,
            &isolation_scores,
        );

        info!(
            "ASN classification complete: {} ASNs, {:.1}% coverage, \
             {} with partitions",
            groups.len(),
            metrics.classification_coverage,
            metrics.groups_with_partitions
        );

        Ok(crate::models::partitions::PartitionClassificationResult {
            classification_type:
                crate::models::partitions::ClassificationType::ASN,
            groups,
            metrics,
            unclassified_relays,
        })
    }

    /// Classifies connected components by relay family relationships
    async fn classify_components_by_family(
        &self,
        components: &[ConnectedComponent],
    ) -> Result<
        crate::models::partitions::PartitionClassificationResult,
        AnalysisError,
    > {
        info!("Classifying {} components by family", components.len());

        if components.is_empty() {
            return Ok(
                crate::models::partitions::PartitionClassificationResult {
                    classification_type:
                        crate::models::partitions::ClassificationType::Family,
                    groups: Vec::new(),
                    metrics:
                        crate::models::partitions::ClassificationMetrics {
                            total_groups: 0,
                            groups_with_partitions: 0,
                            classification_coverage: 0.0,
                            largest_group_size: 0,
                            average_group_size: 0.0,
                            diversity_score: 0.0,
                            partition_correlation: 0.0,
                        },
                    unclassified_relays: Vec::new(),
                },
            );
        }

        // Get family metadata for all relays in the components
        let mut all_fingerprints = Vec::new();
        for component in components {
            all_fingerprints
                .extend(component.relay_fingerprints.iter().cloned());
        }

        let total_relays = all_fingerprints.len();

        // Process in batches to handle large datasets efficiently
        const BATCH_SIZE: usize = 1000;
        let mut relay_families: HashMap<String, Vec<String>> = HashMap::new();
        let mut total_processed = 0;

        debug!(
            "Starting family data collection for {} relays",
            total_relays
        );

        for batch in all_fingerprints.chunks(BATCH_SIZE) {
            let family_query = "UNWIND $fingerprints AS fingerprint
                 MATCH (r:Relay {fingerprint: fingerprint})
                 WHERE r.family IS NOT NULL AND size(r.family) > 0
                 RETURN r.fingerprint AS relay_fingerprint,
                   r.family AS family_array
                 ORDER BY r.fingerprint"
                .to_string();

            debug!(
                "Family Query batch {}: {} relays",
                total_processed / BATCH_SIZE + 1,
                batch.len()
            );

            let query =
                Query::new(family_query).param("fingerprints", batch.to_vec());
            let mut stream: RowStream =
                self.graph.execute(query).await.map_err(|e| {
                    error!("Failed to execute family query: {:?}", e);
                    AnalysisError::QueryFailed(format!(
                        "Family classification query failed: {}",
                        e
                    ))
                })?;

            // Process batch results - collect all family relationships
            let mut batch_count = 0;
            while let Some(row) =
                stream.next().await.map_err(AnalysisError::from)?
            {
                batch_count += 1;
                let fingerprint: String = row
                    .get::<String>("relay_fingerprint")
                    .ok_or_else(|| {
                        AnalysisError::QueryFailed(
                            "Failed to get relay_fingerprint from result"
                                .to_string(),
                        )
                    })?;

                let family_array: Option<Vec<String>> =
                    row.get::<Vec<String>>("family_array");
                if let Some(family_members) = family_array {
                    if !family_members.is_empty() {
                        // Store the family members for this relay
                        relay_families.insert(fingerprint, family_members);
                    }
                }
            }

            total_processed += batch.len();
            debug!(
                "Processed batch: {} rows, total processed: {}",
                batch_count, total_processed
            );
        }

        info!(
            "Family data collection complete: {} relays with family data \
             out of {} total",
            relay_families.len(),
            total_relays
        );

        // Build a graph of family relationships and find connected components
        let family_groups =
            self.build_family_connected_components(&relay_families);

        debug!(
            "Found {} family groups using connected components analysis",
            family_groups.len()
        );

        // Group components by family and track component mapping
        let mut final_groups = Vec::new();
        let mut isolation_scores = Vec::new();
        let mut unclassified_relays = Vec::new();

        // Create a mapping from relay to family group
        let mut relay_to_family: HashMap<String, usize> = HashMap::new();
        for (family_idx, family_relays) in family_groups.iter().enumerate() {
            for relay in family_relays {
                relay_to_family.insert(relay.clone(), family_idx);
            }
        }

        // Process each family group
        for family_relays in family_groups.iter() {
            let mut component_mapping: HashMap<i64, usize> = HashMap::new();
            let mut group_relay_fingerprints = Vec::new();

            // Find which relays from this family are in our components
            for component in components {
                for fingerprint in &component.relay_fingerprints {
                    if family_relays.contains(fingerprint) {
                        group_relay_fingerprints.push(fingerprint.clone());
                        *component_mapping
                            .entry(component.component_id)
                            .or_insert(0) += 1;
                    }
                }
            }

            if !group_relay_fingerprints.is_empty() {
                // Calculate isolation score: percentage of relays NOT in largest component
                let isolation_score = if !component_mapping.is_empty() {
                    let total_relays_in_group = group_relay_fingerprints.len();
                    let largest_component_size =
                        component_mapping.values().max().unwrap_or(&0);

                    if total_relays_in_group > 0 {
                        let non_largest_component_relays =
                            total_relays_in_group - largest_component_size;
                        (non_largest_component_relays as f64
                            / total_relays_in_group as f64)
                            * 100.0
                    } else {
                        0.0
                    }
                } else {
                    0.0
                };

                isolation_scores.push(isolation_score);

                let family_identifier = if family_relays.len() <= 3 {
                    // For small families, use concatenated fingerprints
                    let mut sorted_relays = family_relays.clone();
                    sorted_relays.sort();
                    format!(
                        "family_{}",
                        sorted_relays
                            .iter()
                            .take(2)
                            .map(|r| &r[0..8.min(r.len())])
                            .collect::<Vec<_>>()
                            .join("_")
                    )
                } else {
                    // For large families, use size and hash-based identifier
                    format!(
                        "family_{}relays_{:x}",
                        family_relays.len(),
                        family_relays.iter().map(|s| s.as_bytes()).fold(
                            0u64,
                            |acc, bytes| {
                                acc.wrapping_mul(31).wrapping_add(
                                    bytes.iter().fold(0u64, |a, b| {
                                        a.wrapping_mul(31)
                                            .wrapping_add(*b as u64)
                                    }),
                                )
                            }
                        )
                    )
                };

                final_groups.push(
                    crate::models::partitions::ClassificationGroup {
                        identifier: family_identifier,
                        relay_fingerprints: group_relay_fingerprints,
                        component_mapping,
                        isolation_score,
                    },
                );
            }
        }

        // Identify unclassified relays (those not in any family)
        for component in components {
            for fingerprint in &component.relay_fingerprints {
                if !relay_to_family.contains_key(fingerprint) {
                    unclassified_relays.push(fingerprint.clone());
                }
            }
        }

        // Calculate metrics
        let metrics = self.calculate_classification_metrics(
            &final_groups,
            total_relays,
            &isolation_scores,
        );

        info!(
            "Family classification complete: {} families, {:.1}% coverage, \
             {} with partitions",
            final_groups.len(),
            metrics.classification_coverage,
            metrics.groups_with_partitions
        );
        info!(
            "Family analysis: {} unclassified relays, avg family size: \
             {:.1}, largest family: {}",
            unclassified_relays.len(),
            metrics.average_group_size,
            metrics.largest_group_size
        );

        Ok(crate::models::partitions::PartitionClassificationResult {
            classification_type:
                crate::models::partitions::ClassificationType::Family,
            groups: final_groups,
            metrics,
            unclassified_relays,
        })
    }

    async fn calculate_betweenness_centrality(
        &self,
        projection_name: &str,
        sampling_size: Option<usize>,
        sampling_seed: Option<u64>,
    ) -> Result<CentralityAnalysisResult, AnalysisError> {
        info!(
            "Calculating betweenness centrality for projection: '{}'",
            projection_name
        );

        // Build the betweenness centrality query with optional sampling
        // Use configurable seed for deterministic results
        let config_params = if let Some(sample_size) = sampling_size {
            let seed = sampling_seed.unwrap_or(42);
            format!(
                ", {{samplingSize: {}, samplingSeed: {}}}",
                sample_size, seed
            )
        } else {
            ", {}".to_string()
        };

        let betweenness_query = format!(
            "CALL gds.betweenness.stream('{}'{})
             YIELD nodeId, score
             RETURN gds.util.asNode(nodeId).fingerprint AS relay_fingerprint,
                    score AS betweenness_centrality
             ORDER BY score DESC",
            projection_name, config_params
        );

        debug!("Betweenness Centrality Query: {}", betweenness_query);
        let query = Query::new(betweenness_query);
        let mut stream: RowStream =
            self.graph.execute(query).await.map_err(|e| {
                error!(
                    "Failed to execute betweenness centrality query: {:?}",
                    e
                );
                AnalysisError::AlgorithmError(format!(
                    "Betweenness centrality failed for projection '{}': {}",
                    projection_name, e
                ))
            })?;

        let mut centrality_metrics = Vec::new();
        let mut scores = Vec::new();

        while let Some(row) =
            stream.next().await.map_err(AnalysisError::from)?
        {
            let fingerprint: String =
                row.get::<String>("relay_fingerprint").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get relay_fingerprint".to_string(),
                    )
                })?;

            let score: f64 =
                row.get::<f64>("betweenness_centrality").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get betweenness_centrality score"
                            .to_string(),
                    )
                })?;

            scores.push(score);
            centrality_metrics.push(CentralityMetrics {
                fingerprint,
                betweenness_centrality: Some(score),
                closeness_centrality: None,
            });
        }

        // Calculate distribution
        let betweenness_distribution = if !scores.is_empty() {
            let min = scores.iter().copied().fold(f64::INFINITY, f64::min);
            let max = scores.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            let mean = scores.iter().sum::<f64>() / scores.len() as f64;

            let mut sorted_scores = scores.clone();
            sorted_scores.sort_by(|a, b| a.partial_cmp(b).unwrap());
            let len = sorted_scores.len();

            let get_percentile = |p: f64| -> f64 {
                let index = ((len as f64 - 1.0) * p).round() as usize;
                sorted_scores[index.min(len - 1)]
            };

            Some(CentralityDistribution {
                min,
                max,
                mean,
                p50: get_percentile(0.50),
                p75: get_percentile(0.75),
                p90: get_percentile(0.90),
                p95: get_percentile(0.95),
                p99: get_percentile(0.99),
                p999: get_percentile(0.999),
            })
        } else {
            None
        };

        let total_nodes = centrality_metrics.len();
        info!(
            "Betweenness centrality complete: {} nodes analyzed",
            total_nodes
        );

        Ok(CentralityAnalysisResult {
            centrality_metrics,
            total_nodes_analyzed: Some(total_nodes),
            betweenness_distribution,
            closeness_distribution: None,
        })
    }

    async fn calculate_closeness_centrality(
        &self,
        projection_name: &str,
        use_wasserman_faust: Option<bool>,
    ) -> Result<CentralityAnalysisResult, AnalysisError> {
        info!(
            "Calculating closeness centrality for projection: '{}'",
            projection_name
        );

        let config_params = if let Some(use_wf) = use_wasserman_faust {
            format!(", {{useWassermanFaust: {}}}", use_wf)
        } else {
            ", {}".to_string()
        };

        let closeness_query = format!(
            "CALL gds.closeness.stream('{}'{})
             YIELD nodeId, score
             RETURN gds.util.asNode(nodeId).fingerprint AS relay_fingerprint,
                    score AS closeness_centrality
             ORDER BY score DESC",
            projection_name, config_params
        );

        debug!("Closeness Centrality Query: {}", closeness_query);
        let query = Query::new(closeness_query);
        let mut stream: RowStream =
            self.graph.execute(query).await.map_err(|e| {
                error!(
                    "Failed to execute closeness centrality query: {:?}",
                    e
                );
                AnalysisError::AlgorithmError(format!(
                    "Closeness centrality failed for projection '{}': {}",
                    projection_name, e
                ))
            })?;

        let mut centrality_metrics = Vec::new();
        let mut scores = Vec::new();

        while let Some(row) =
            stream.next().await.map_err(AnalysisError::from)?
        {
            let fingerprint: String =
                row.get::<String>("relay_fingerprint").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get relay_fingerprint".to_string(),
                    )
                })?;

            let score: f64 =
                row.get::<f64>("closeness_centrality").ok_or_else(|| {
                    AnalysisError::QueryFailed(
                        "Failed to get closeness_centrality score".to_string(),
                    )
                })?;

            scores.push(score);
            centrality_metrics.push(CentralityMetrics {
                fingerprint,
                betweenness_centrality: None,
                closeness_centrality: Some(score),
            });
        }

        // Calculate distribution
        let closeness_distribution = if !scores.is_empty() {
            let min = scores.iter().copied().fold(f64::INFINITY, f64::min);
            let max = scores.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            let mean = scores.iter().sum::<f64>() / scores.len() as f64;

            let mut sorted_scores = scores.clone();
            sorted_scores.sort_by(|a, b| a.partial_cmp(b).unwrap());
            let len = sorted_scores.len();

            let get_percentile = |p: f64| -> f64 {
                let index = ((len as f64 - 1.0) * p).round() as usize;
                sorted_scores[index.min(len - 1)]
            };

            Some(CentralityDistribution {
                min,
                max,
                mean,
                p50: get_percentile(0.50),
                p75: get_percentile(0.75),
                p90: get_percentile(0.90),
                p95: get_percentile(0.95),
                p99: get_percentile(0.99),
                p999: get_percentile(0.999),
            })
        } else {
            None
        };

        let total_nodes = centrality_metrics.len();
        info!(
            "Closeness centrality complete: {} nodes analyzed",
            total_nodes
        );

        Ok(CentralityAnalysisResult {
            centrality_metrics,
            total_nodes_analyzed: Some(total_nodes),
            betweenness_distribution: None,
            closeness_distribution,
        })
    }

    /// Calculates both betweenness and closeness centrality.
    async fn calculate_combined_centrality(
        &self,
        projection_name: &str,
        betweenness_sampling_size: Option<usize>,
        betweenness_sampling_seed: Option<u64>,
        use_wasserman_faust: Option<bool>,
    ) -> Result<CentralityAnalysisResult, AnalysisError> {
        info!(
            "Calculating combined centrality for projection: '{}'",
            projection_name
        );

        let betweenness_result = self
            .calculate_betweenness_centrality(
                projection_name,
                betweenness_sampling_size,
                betweenness_sampling_seed,
            )
            .await?;

        let closeness_result = self
            .calculate_closeness_centrality(
                projection_name,
                use_wasserman_faust,
            )
            .await?;

        let mut combined_metrics = HashMap::new();
        for metric in betweenness_result.centrality_metrics {
            combined_metrics.insert(metric.fingerprint.clone(), metric);
        }
        for metric in closeness_result.centrality_metrics {
            if let Some(existing) =
                combined_metrics.get_mut(&metric.fingerprint)
            {
                existing.closeness_centrality = metric.closeness_centrality;
            } else {
                combined_metrics.insert(metric.fingerprint.clone(), metric);
            }
        }

        let final_metrics: Vec<CentralityMetrics> =
            combined_metrics.into_values().collect();
        let total_nodes = final_metrics.len();

        Ok(CentralityAnalysisResult {
            centrality_metrics: final_metrics,
            total_nodes_analyzed: Some(total_nodes),
            betweenness_distribution: betweenness_result
                .betweenness_distribution,
            closeness_distribution: closeness_result.closeness_distribution,
        })
    }

    /// Analyzes shortest paths between nodes from different communities.
    async fn analyze_paths_between_communities(
        &self,
        projection_name: &str,
        source_nodes: &[String],
        target_nodes: &[String],
    ) -> Result<PathAnalysisResult, AnalysisError> {
        info!(
            "Analyzing paths between {} sources and {} targets",
            source_nodes.len(),
            target_nodes.len()
        );

        let mut path_results = Vec::new();
        let mut connected_pairs = 0;

        let path_query = format!(
            "UNWIND $sources as source_fingerprint
             UNWIND $targets as target_fingerprint
             WITH source_fingerprint, target_fingerprint
             WHERE source_fingerprint <> target_fingerprint
             MATCH (s:Relay {{fingerprint: source_fingerprint}})
             MATCH (t:Relay {{fingerprint: target_fingerprint}})
             WITH s, t, source_fingerprint, target_fingerprint
             CALL gds.shortestPath.dijkstra.stream('{}', {{
                 sourceNode: id(s),
                 targetNode: id(t)
             }})
             YIELD totalCost, nodeIds
             RETURN source_fingerprint, target_fingerprint,
                    totalCost, size(nodeIds) as pathLength,
                    [nodeId in nodeIds | gds.util.asNode(nodeId).fingerprint] as
                    pathNodes",
            projection_name
        );

        let query = Query::new(path_query)
            .param("sources", source_nodes)
            .param("targets", target_nodes);

        match self.graph.execute(query).await {
            Ok(mut stream) => {
                let mut found_pairs = std::collections::HashSet::new();

                while let Ok(Some(row)) = stream.next().await {
                    let source_fingerprint: String = row
                        .get("source_fingerprint")
                        .unwrap_or_else(|| "unknown".to_string());
                    let target_fingerprint: String = row
                        .get("target_fingerprint")
                        .unwrap_or_else(|| "unknown".to_string());
                    let total_cost: f64 = row.get("totalCost").unwrap_or(0.0);
                    let path_length: i64 = row.get("pathLength").unwrap_or(0);
                    let path_nodes: Vec<String> =
                        row.get("pathNodes").unwrap_or_else(Vec::new);

                    found_pairs.insert((
                        source_fingerprint.clone(),
                        target_fingerprint.clone(),
                    ));

                    if total_cost > 0.0 {
                        connected_pairs += 1;
                    }

                    path_results.push(PathResult {
                        source_fingerprint,
                        target_fingerprint,
                        path_exists: total_cost > 0.0,
                        path_length: Some(path_length as usize),
                        path_cost: Some(total_cost),
                        intermediate_nodes: Some(path_nodes),
                    });
                }

                // Add disconnected pairs that weren't found
                for source in source_nodes {
                    for target in target_nodes {
                        if source != target
                            && !found_pairs
                                .contains(&(source.clone(), target.clone()))
                        {
                            path_results.push(PathResult {
                                source_fingerprint: source.clone(),
                                target_fingerprint: target.clone(),
                                path_exists: false,
                                path_length: None,
                                path_cost: None,
                                intermediate_nodes: None,
                            });
                        }
                    }
                }

                let total_pairs = source_nodes.len() * target_nodes.len()
                    - source_nodes
                        .iter()
                        .filter(|s| target_nodes.contains(s))
                        .count();

                let avg_path_length = if connected_pairs > 0 {
                    path_results
                        .iter()
                        .filter(|p| p.path_exists)
                        .map(|p| p.path_length.unwrap_or(0))
                        .sum::<usize>() as f64
                        / connected_pairs as f64
                } else {
                    0.0
                };

                let max_path_length = path_results
                    .iter()
                    .filter(|p| p.path_exists)
                    .map(|p| p.path_length.unwrap_or(0))
                    .max();

                let min_path_length = path_results
                    .iter()
                    .filter(|p| p.path_exists)
                    .map(|p| p.path_length.unwrap_or(0))
                    .min();

                info!(
                    "Path analysis complete: {}/{} paths exist, avg: {:.2}",
                    connected_pairs, total_pairs, avg_path_length
                );

                Ok(PathAnalysisResult {
                    path_results,
                    total_paths_analyzed: Some(total_pairs),
                    connected_community_pairs: Some(connected_pairs),
                    disconnected_community_pairs: Some(
                        total_pairs - connected_pairs,
                    ),
                    average_path_length: Some(avg_path_length),
                    max_path_length,
                    min_path_length,
                })
            }
            Err(e) => {
                error!("Path analysis query failed: {:?}", e);
                Err(AnalysisError::AlgorithmError(format!(
                    "Path analysis failed for projection '{}': {}. \
                     This likely indicates a graph projection issue.",
                    projection_name, e
                )))
            }
        }
    }
}

impl Neo4jAnalysisClient {
    /// Build connected components of family relationships using Union-Find algorithm
    /// This handles multi-family relays by connecting all relays that share
    /// any family members, creating accurate family groups for partition analysis
    fn build_family_connected_components(
        &self,
        relay_families: &HashMap<String, Vec<String>>,
    ) -> Vec<Vec<String>> {
        debug!(
            "Building family connected components from {} relays \
             with family data",
            relay_families.len()
        );

        // Create a Union-Find data structure for efficient connected components
        let mut parent: HashMap<String, String> = HashMap::new();
        let mut rank: HashMap<String, usize> = HashMap::new();

        // Initialize Union-Find: each relay is its own parent initially
        for relay in relay_families.keys() {
            parent.insert(relay.clone(), relay.clone());
            rank.insert(relay.clone(), 0);
        }

        // Union-Find helper functions
        fn find_root(x: &str, parent: &mut HashMap<String, String>) -> String {
            let parent_x = parent.get(x).unwrap().clone();
            if parent_x != *x {
                let root = find_root(&parent_x, parent);
                parent.insert(x.to_string(), root.clone());
                root
            } else {
                x.to_string()
            }
        }

        fn union_sets(
            x: &str,
            y: &str,
            parent: &mut HashMap<String, String>,
            rank: &mut HashMap<String, usize>,
        ) {
            let root_x = find_root(x, parent);
            let root_y = find_root(y, parent);

            if root_x != root_y {
                let rank_x = rank.get(&root_x).unwrap_or(&0);
                let rank_y = rank.get(&root_y).unwrap_or(&0);

                match rank_x.cmp(rank_y) {
                    std::cmp::Ordering::Less => {
                        parent.insert(root_x, root_y);
                    }
                    std::cmp::Ordering::Greater => {
                        parent.insert(root_y, root_x);
                    }
                    std::cmp::Ordering::Equal => {
                        parent.insert(root_y, root_x.clone());
                        rank.insert(root_x, rank_x + 1);
                    }
                }
            }
        }

        // Build family member to relays mapping for efficient lookups
        let mut family_member_to_relays: HashMap<String, Vec<String>> =
            HashMap::new();
        for (relay, family_members) in relay_families {
            for family_member in family_members {
                family_member_to_relays
                    .entry(family_member.clone())
                    .or_default()
                    .push(relay.clone());
            }
        }

        debug!(
            "Built family member index with {} unique family members",
            family_member_to_relays.len()
        );

        // Connect all relays that share family members
        let mut connections_made = 0;
        let mut large_member_groups = 0;
        let mut total_family_groups = 0;

        for relays_in_family in family_member_to_relays.values() {
            if relays_in_family.len() > 1 {
                total_family_groups += 1;

                if relays_in_family.len() >= 50 {
                    large_member_groups += 1;
                }

                // Connect all pairs of relays that share this family member
                for i in 0..relays_in_family.len() {
                    for j in (i + 1)..relays_in_family.len() {
                        let relay1 = &relays_in_family[i];
                        let relay2 = &relays_in_family[j];

                        union_sets(relay1, relay2, &mut parent, &mut rank);
                        connections_made += 1;
                    }
                }
            }
        }

        info!(
            "Family relationship analysis: {} total family groups, {} large member groups (≥50 relays), {} connections made",
            total_family_groups, large_member_groups, connections_made
        );

        // Group relays by their root (connected component)
        let mut components: HashMap<String, Vec<String>> = HashMap::new();
        for relay in relay_families.keys() {
            let root = find_root(relay, &mut parent);
            components.entry(root).or_default().push(relay.clone());
        }

        // Convert to vector and sort for consistent output
        let mut result: Vec<Vec<String>> = components.into_values().collect();

        // Sort each component internally and sort components by size (largest first)
        for component in &mut result {
            component.sort();
        }
        result.sort_by_key(|b| std::cmp::Reverse(b.len()));

        info!(
            "Connected components analysis complete: {} family groups found, \
             largest: {} relays",
            result.len(),
            result.first().map(|c| c.len()).unwrap_or(0)
        );

        // Log some statistics about family groups
        let single_relay_families =
            result.iter().filter(|c| c.len() == 1).count();
        let medium_families = result.iter().filter(|c| c.len() >= 10).count();
        let large_families = result.iter().filter(|c| c.len() >= 50).count();
        info!(
            "Family group statistics: {} single-relay, {} medium (≥10 relays), {} large (≥50 relays)",
            single_relay_families, medium_families, large_families
        );

        result
    }

    /// Calculates classification metrics for partition analysis groups
    fn calculate_classification_metrics(
        &self,
        groups: &[crate::models::partitions::ClassificationGroup],
        total_relays: usize,
        isolation_scores: &[f64],
    ) -> crate::models::partitions::ClassificationMetrics {
        // Calculate basic metrics
        let total_classified = groups
            .iter()
            .map(|g| g.relay_fingerprints.len())
            .sum::<usize>();
        let coverage = if total_relays > 0 {
            (total_classified as f64 / total_relays as f64) * 100.0
        } else {
            0.0
        };

        let groups_with_partitions = groups
            .iter()
            .filter(|g| g.component_mapping.len() > 1)
            .count();

        let largest_group_size = groups
            .iter()
            .map(|g| g.relay_fingerprints.len())
            .max()
            .unwrap_or(0);

        let average_group_size = if !groups.is_empty() {
            total_classified as f64 / groups.len() as f64
        } else {
            0.0
        };

        // Calculate partition correlation
        let partition_correlation = if !isolation_scores.is_empty() {
            isolation_scores.iter().sum::<f64>()
                / isolation_scores.len() as f64
                / 100.0
        } else {
            0.0
        };

        // Calculate diversity score (Shannon entropy-like metric)
        let diversity_score = if !groups.is_empty() && total_classified > 0 {
            let total_relays_f64 = total_classified as f64;
            let entropy = groups
                .iter()
                .map(|g| g.relay_fingerprints.len() as f64 / total_relays_f64)
                .filter(|&p| p > 0.0)
                .map(|p| -p * p.ln())
                .sum::<f64>();

            entropy / (groups.len() as f64).ln()
        } else {
            0.0
        };

        crate::models::partitions::ClassificationMetrics {
            total_groups: groups.len(),
            groups_with_partitions,
            classification_coverage: coverage,
            largest_group_size,
            average_group_size,
            diversity_score,
            partition_correlation,
        }
    }
}