erpc_analysis/
tasks.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
use std::collections::HashMap;
use std::sync::Arc;

use anyhow::Result;
use log::{error, info, warn};

use crate::algorithms::{
    CommunityAnalyzer, ComponentAnalyzer, PartitionClassifier,
};
use crate::args::Args;
use crate::db_trait::{
    AnalysisDatabase, AnalysisError, GraphProjectionParams,
};
use crate::models::metrics::{GraphMetrics, NodeMetrics};
use crate::models::partitions::ComponentAnalysisResult;

/// Handles task execution based on CLI arguments
pub struct TaskHandler {
    db_client: Arc<dyn AnalysisDatabase>,
    args: Args,
    config: crate::config::AnalysisConfig,
}

impl TaskHandler {
    pub fn new(
        db_client: Arc<dyn AnalysisDatabase>,
        args: Args,
        config: crate::config::AnalysisConfig,
    ) -> Self {
        Self {
            db_client,
            args,
            config,
        }
    }

    /// Execute the specified task or run default analysis
    pub async fn execute(&self) -> Result<(), Box<dyn std::error::Error>> {
        match &self.args.task {
            Some(task) => self.execute_specific_task(task).await,
            None => self.execute_default_analysis().await,
        }
    }

    async fn execute_specific_task(
        &self,
        task: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        match task {
            "projection-create" => self.handle_projection_create().await,
            "projection-delete" => self.handle_projection_delete().await,
            "projection-exists" => self.handle_projection_exists().await,
            "metrics-basic" => self.handle_metrics_basic().await,
            "metrics-degrees" => self.handle_metrics_degrees().await,
            "metrics-distribution" => self.handle_metrics_distribution().await,
            "components-analysis" => self.handle_components_analysis().await,
            "community-louvain-consensus" => {
                self.handle_community_louvain_consensus().await
            }
            "community-lpa" => self.handle_community_lpa().await,
            "partition-classify-geography" => {
                self.handle_partition_classify_geography().await
            }
            "partition-classify-asn" => {
                self.handle_partition_classify_asn().await
            }
            "partition-classify-family" => {
                self.handle_partition_classify_family().await
            }
            "partition-classify-all" => {
                self.handle_partition_classify_all().await
            }
            "centrality-betweenness" => {
                self.handle_centrality_betweenness().await
            }
            "centrality-closeness" => self.handle_centrality_closeness().await,
            "centrality-combined" => self.handle_centrality_combined().await,
            "path-connectivity" => self.handle_path_connectivity().await,
            "advanced-path-analysis" => {
                self.handle_advanced_path_analysis().await
            }
            "info-database" => self.handle_info_database().await,
            "web-server" => self.handle_web_server().await,
            "help" => self.handle_help().await,
            _ => {
                error!("Unknown task: {}", task);
                println!("{}", Args::task_help());
                std::process::exit(1);
            }
        }
    }

    /// Execute the default analysis workflow
    async fn execute_default_analysis(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running default analysis workflow...");

        let proj_params = self.create_default_projection_params();

        info!(
            "Creating/updating GDS graph projection: '{}' with node \
             label: '{}'",
            proj_params.projection_name, proj_params.node_label
        );

        self.db_client
            .create_graph_projection(&proj_params)
            .await
            .map_err(|e: AnalysisError| {
                error!(
                    "Failed to create GDS graph projection '{}': {:?}",
                    proj_params.projection_name, e
                );
                Box::new(e) as Box<dyn std::error::Error>
            })?;

        info!(
            "Successfully created/updated GDS graph projection: '{}'",
            proj_params.projection_name
        );

        self.calculate_and_display_metrics(&proj_params.projection_name)
            .await?;

        self.handle_components_analysis().await?;

        Ok(())
    }

    pub async fn handle_projection_create(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let proj_params = self.create_projection_params("tor_erpc_projection");

        if !self.args.force
            && self
                .db_client
                .check_graph_projection_exists(&proj_params.projection_name)
                .await?
        {
            println!(
                "Projection '{}' already exists. Use --force to recreate.",
                proj_params.projection_name
            );
            return Ok(());
        }

        info!(
            "Creating graph projection: '{}'",
            proj_params.projection_name
        );
        self.db_client.create_graph_projection(&proj_params).await?;
        println!(
            "✅ Successfully created projection: '{}'",
            proj_params.projection_name
        );

        Ok(())
    }

    pub async fn handle_projection_delete(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Deleting graph projection: tor_erpc_projection");
        self.db_client
            .delete_graph_projection("tor_erpc_projection")
            .await?;
        println!("✅ Successfully deleted projection: tor_erpc_projection");

        Ok(())
    }

    async fn handle_projection_exists(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let exists = self
            .db_client
            .check_graph_projection_exists("tor_erpc_projection")
            .await?;

        if exists {
            println!("✅ Projection: tor_erpc_projection exists");
        } else {
            println!("❌ Projection: tor_erpc_projection does not exist");
        }

        Ok(())
    }

    async fn handle_metrics_basic(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Calculating basic metrics for projection: tor_erpc_projection");
        let metrics = self
            .db_client
            .calculate_graph_metrics("tor_erpc_projection")
            .await
            .map_err(|e| {
                error!("Failed to calculate graph metrics: {:?}", e);
                e
            })?;
        info!("Successfully calculated metrics, displaying results...");
        self.display_basic_metrics(&metrics)?;
        Ok(())
    }

    async fn handle_metrics_degrees(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let node_degrees = self
            .db_client
            .calculate_node_degrees("tor_erpc_projection")
            .await
            .map_err(|e| {
                error!("Failed to calculate node degrees: {:?}", e);
                e
            })?;
        self.display_degree_metrics(&node_degrees)?;
        Ok(())
    }

    async fn handle_metrics_distribution(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let metrics = self
            .db_client
            .calculate_graph_metrics("tor_erpc_projection")
            .await
            .map_err(|e| {
                error!(
                    "Failed to calculate graph metrics for distribution: {:?}",
                    e
                );
                e
            })?;
        self.display_degree_distribution(&metrics)?;
        Ok(())
    }

    async fn handle_info_database(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // Test actual database connectivity
        let connection_status = match self
            .db_client
            .check_graph_projection_exists("test_connection")
            .await
        {
            Ok(_) => "Connected",
            Err(_) => "Connection Failed",
        };

        println!("Database Information:");
        println!("  Type: Neo4j");
        println!("  Status: {}", connection_status);
        Ok(())
    }

    async fn handle_help(&self) -> Result<(), Box<dyn std::error::Error>> {
        println!("{}", Args::task_help());
        Ok(())
    }

    /// Handle web server startup task
    async fn handle_web_server(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Starting eRPC Analysis web server...");

        let host = "127.0.0.1".to_string();
        let port = 8080;

        println!("Starting eRPC Analysis web server");
        println!(
            "   API endpoints available at http://{}:{}/erpc/",
            host, port
        );
        println!();
        println!("Analysis Endpoints (GET - Run & Return Results):");
        println!(
            "   Components analysis: http://{}:{}/erpc/components",
            host, port
        );
        println!(
            "   Partition classification: http://{}:{}/erpc/partitions",
            host, port
        );
        println!(
            "   Centrality analysis: http://{}:{}/erpc/centrality",
            host, port
        );
        println!("   Community detection (Louvain): http://{}:{}/erpc/community/louvain", host, port);
        println!("   Graph metrics: http://{}:{}/erpc/metrics", host, port);
        println!(
            "   Metrics degrees: http://{}:{}/erpc/metrics/degrees",
            host, port
        );
        println!(
            "   Metrics distribution: http://{}:{}/erpc/metrics/distribution",
            host, port
        );
        println!(
            "   Community LPA: http://{}:{}/erpc/community/lpa",
            host, port
        );
        println!(
            "   Path connectivity: http://{}:{}/erpc/path/connectivity",
            host, port
        );
        println!(
            "   Advanced path analysis: http://{}:{}/erpc/advanced-paths",
            host, port
        );
        println!();
        println!("Utility Endpoints:");
        println!("   Health check: http://{}:{}/erpc/health", host, port);
        println!(
            "   Database info: http://{}:{}/erpc/database/info",
            host, port
        );
        println!();
        println!("Press Ctrl+C to stop the server");

        let web_server = crate::web::WebServer::new(
            host,
            port,
            Arc::clone(&self.db_client),
            self.config.clone(),
        );

        web_server.start().await.map_err(|e| {
            error!("Failed to start web server: {}", e);
            Box::new(e) as Box<dyn std::error::Error>
        })?;

        Ok(())
    }

    /// Handle comprehensive component analysis task
    pub async fn handle_components_analysis(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // Create separate projection for partition detection (success-only)
        self.handle_connectivity_projection().await?;

        info!("Running weak connectivity analysis using WCC algorithm...");
        self.run_wcc_analysis("tor_erpc_connectivity_analysis")
            .await?;

        info!("Running strong connectivity analysis using SCC algorithm...");
        self.run_scc_analysis("tor_erpc_connectivity_analysis")
            .await?;

        Ok(())
    }

    /// Handle Louvain consensus community detection analysis task
    pub async fn handle_community_louvain_consensus(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!(
            "Running Louvain consensus community detection for projection: \
             tor_erpc_connectivity_analysis"
        );

        // Check if connectivity projection exists first
        self.handle_connectivity_projection().await?;

        self.run_louvain_consensus_analysis("tor_erpc_connectivity_analysis")
            .await?;

        println!(
            "✅ Successfully completed Louvain consensus community detection \
             analysis"
        );
        Ok(())
    }

    /// Handle Label Propagation Algorithm community detection analysis task
    pub async fn handle_community_lpa(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!(
            "Running Label Propagation community detection for projection: \
             tor_erpc_connectivity_analysis"
        );

        // Check if connectivity projection exists first
        self.handle_connectivity_projection().await?;

        self.run_lpa_analysis("tor_erpc_connectivity_analysis")
            .await?;

        println!(
            "✅ Successfully completed Label Propagation community detection \
             analysis"
        );
        Ok(())
    }

    async fn handle_partition_classify_geography(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running partition classification by geography...");

        // Ensure we have a graph projection
        self.handle_connectivity_projection().await?;

        // Get components first
        let component_analyzer =
            ComponentAnalyzer::new(Arc::clone(&self.db_client));
        let wcc_result = component_analyzer
            .analyze_weakly_connected_components(
                "tor_erpc_connectivity_analysis",
            )
            .await?;

        let classifier = PartitionClassifier::new(Arc::clone(&self.db_client));
        let result = classifier
            .classify_by_geography(&wcc_result.components)
            .await?;

        classifier.display_geographic_classification(
            &result,
            &self.config.analysis_params.analysis,
        )?;
        println!(
            "✅ Successfully completed geographic partition classification"
        );
        Ok(())
    }

    async fn handle_partition_classify_asn(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running partition classification by ASN...");

        // Ensure we have a graph projection
        self.handle_connectivity_projection().await?;

        // Get components first
        let component_analyzer =
            ComponentAnalyzer::new(Arc::clone(&self.db_client));
        let wcc_result = component_analyzer
            .analyze_weakly_connected_components(
                "tor_erpc_connectivity_analysis",
            )
            .await?;

        let classifier = PartitionClassifier::new(Arc::clone(&self.db_client));
        let result =
            classifier.classify_by_asn(&wcc_result.components).await?;

        classifier.display_asn_classification(
            &result,
            &self.config.analysis_params.analysis,
        )?;
        println!("✅ Successfully completed ASN partition classification");
        Ok(())
    }

    async fn handle_partition_classify_family(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running partition classification by family...");

        // Ensure we have a graph projection
        self.handle_connectivity_projection().await?;

        // Get components first
        let component_analyzer =
            ComponentAnalyzer::new(Arc::clone(&self.db_client));
        let wcc_result = component_analyzer
            .analyze_weakly_connected_components(
                "tor_erpc_connectivity_analysis",
            )
            .await?;

        let classifier = PartitionClassifier::new(Arc::clone(&self.db_client));
        let result = classifier
            .classify_by_family(&wcc_result.components)
            .await?;

        classifier.display_family_classification(
            &result,
            &self.config.analysis_params.analysis,
        )?;
        println!("✅ Successfully completed family partition classification");
        Ok(())
    }

    /// Handle partition classification by all types
    pub async fn handle_partition_classify_all(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running comprehensive partition classification...");

        // Ensure we have a graph projection
        self.handle_connectivity_projection().await?;

        // Get components first
        let component_analyzer =
            ComponentAnalyzer::new(Arc::clone(&self.db_client));
        let wcc_result = component_analyzer
            .analyze_weakly_connected_components(
                "tor_erpc_connectivity_analysis",
            )
            .await?;

        let classifier = PartitionClassifier::new(Arc::clone(&self.db_client));

        // Run all classifications
        info!("Running geographic classification...");
        let geo_result = classifier
            .classify_by_geography(&wcc_result.components)
            .await?;
        classifier.display_geographic_classification(
            &geo_result,
            &self.config.analysis_params.analysis,
        )?;

        info!("Running ASN classification...");
        let asn_result =
            classifier.classify_by_asn(&wcc_result.components).await?;
        classifier.display_asn_classification(
            &asn_result,
            &self.config.analysis_params.analysis,
        )?;

        info!("Running family classification...");
        let family_result = classifier
            .classify_by_family(&wcc_result.components)
            .await?;
        classifier.display_family_classification(
            &family_result,
            &self.config.analysis_params.analysis,
        )?;

        println!("✅ Successfully completed all partition classifications");
        Ok(())
    }

    async fn run_wcc_analysis(
        &self,
        projection_name: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let analyzer = ComponentAnalyzer::new(Arc::clone(&self.db_client));

        let result = analyzer
            .analyze_weakly_connected_components(projection_name)
            .await?;

        analyzer.display_weak_connectivity_analysis(
            &result,
            &self.config.analysis_params.analysis,
        )?;

        Ok(())
    }

    async fn run_scc_analysis(
        &self,
        projection_name: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let analyzer = ComponentAnalyzer::new(Arc::clone(&self.db_client));

        let result = analyzer
            .analyze_strongly_connected_components(projection_name)
            .await?;

        analyzer.display_strong_connectivity_analysis(
            &result,
            &self.config.analysis_params.analysis,
        )?;

        Ok(())
    }

    /// Run Louvain consensus community detection analysis (multiple runs for
    /// stability)
    async fn run_louvain_consensus_analysis(
        &self,
        projection_name: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let consensus_runs = self
            .config
            .analysis_params
            .community_detection
            .consensus_runs;
        info!(
            "Starting Louvain consensus community detection analysis ({} \
             runs)...",
            consensus_runs
        );

        let analyzer = CommunityAnalyzer::new(self.db_client.clone());
        let mut results = Vec::new();

        // Run Louvain algorithm multiple times to analyze stability
        for run_number in 1..=consensus_runs {
            info!(
                "Running Louvain iteration {}/{}...",
                run_number, consensus_runs
            );
            let result = analyzer
                .analyze_louvain_communities(
                    projection_name,
                    &self.config.analysis_params.community_detection.louvain,
                )
                .await?;

            // Display individual run results with modularity
            info!("=== Louvain Run {} Results ===", run_number);
            analyzer.display_louvain_community_analysis(
                &result,
                &self.config.analysis_params.analysis,
            )?;

            results.push(result);
        }

        // Analyze consensus across runs (including modularity)
        self.analyze_louvain_consensus(&results, consensus_runs);

        info!("✅ Louvain consensus analysis completed");
        Ok(())
    }

    /// Analyze consensus and stability across multiple Louvain runs
    fn analyze_louvain_consensus(
        &self,
        results: &[ComponentAnalysisResult],
        consensus_runs: u32,
    ) {
        info!(
            "=== Louvain Consensus Analysis ({} Runs) ===",
            consensus_runs
        );

        let mut community_counts = Vec::new();
        let mut largest_sizes = Vec::new();
        let mut isolation_ratios = Vec::new();
        let mut modularity_scores = Vec::new();

        for (i, result) in results.iter().enumerate() {
            let count = result.total_components.unwrap_or(0);
            let largest = result.largest_component_size.unwrap_or(0);
            let isolation = result.isolation_ratio.unwrap_or(0.0);
            let modularity = result.modularity.unwrap_or(0.0);

            community_counts.push(count);
            largest_sizes.push(largest);
            isolation_ratios.push(isolation);
            modularity_scores.push(modularity);

            info!(
                "Run {}: {} communities, largest: {}, isolation: {:.2}%, \
                 modularity: {:.4}",
                i + 1,
                count,
                largest,
                isolation,
                modularity
            );
        }

        // Calculate statistics
        let avg_communities = community_counts.iter().sum::<usize>() as f64
            / community_counts.len() as f64;
        let min_communities = *community_counts.iter().min().unwrap();
        let max_communities = *community_counts.iter().max().unwrap();

        let avg_largest = largest_sizes.iter().sum::<usize>() as f64
            / largest_sizes.len() as f64;
        let min_largest = *largest_sizes.iter().min().unwrap();
        let max_largest = *largest_sizes.iter().max().unwrap();

        let avg_isolation = isolation_ratios.iter().sum::<f64>()
            / isolation_ratios.len() as f64;
        let min_isolation = isolation_ratios
            .iter()
            .min_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap();
        let max_isolation = isolation_ratios
            .iter()
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap();

        let avg_modularity = modularity_scores.iter().sum::<f64>()
            / modularity_scores.len() as f64;
        let min_modularity = modularity_scores
            .iter()
            .min_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap();
        let max_modularity = modularity_scores
            .iter()
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap();

        info!("=== Stability Analysis ===");
        info!(
            "Community Count - Avg: {:.1}, Range: {} - {}",
            avg_communities, min_communities, max_communities
        );
        info!(
            "Largest Community - Avg: {:.1}, Range: {} - {}",
            avg_largest, min_largest, max_largest
        );
        info!(
            "Isolation Ratio - Avg: {:.2}%, Range: {:.2}% - {:.2}%",
            avg_isolation, min_isolation, max_isolation
        );
        info!(
            "Modularity Score - Avg: {:.4}, Range: {:.4} - {:.4}",
            avg_modularity, min_modularity, max_modularity
        );

        // Calculate coefficient of variation for stability assessment
        let communities_variance = community_counts
            .iter()
            .map(|&x| (x as f64 - avg_communities).powi(2))
            .sum::<f64>()
            / community_counts.len() as f64;
        let communities_std = communities_variance.sqrt();
        let communities_cv = communities_std / avg_communities * 100.0;

        let isolation_variance = isolation_ratios
            .iter()
            .map(|&x| (x - avg_isolation).powi(2))
            .sum::<f64>()
            / isolation_ratios.len() as f64;
        let isolation_std = isolation_variance.sqrt();
        let isolation_cv = isolation_std / avg_isolation * 100.0;

        let modularity_variance = modularity_scores
            .iter()
            .map(|&x| (x - avg_modularity).powi(2))
            .sum::<f64>()
            / modularity_scores.len() as f64;
        let modularity_std = modularity_variance.sqrt();
        let modularity_cv = if avg_modularity != 0.0 {
            modularity_std / avg_modularity * 100.0
        } else {
            0.0
        };

        info!("=== Stability Metrics ===");
        info!(
            "Community Count Coefficient of Variation: {:.1}%",
            communities_cv
        );
        info!(
            "Isolation Ratio Coefficient of Variation: {:.1}%",
            isolation_cv
        );
        info!(
            "Modularity Score Coefficient of Variation: {:.1}%",
            modularity_cv
        );

        // Modularity quality assessment
        if avg_modularity >= 0.3 {
            info!("✅ STRONG community structure detected (modularity ≥ 0.3)");
        } else if avg_modularity >= 0.1 {
            info!(
                "⚠️  MODERATE community structure detected (0.1 ≤ modularity \
                 < 0.3)"
            );
        } else {
            info!("❌ WEAK community structure detected (modularity < 0.1)");
        }

        if communities_cv < 10.0 {
            info!("✅ Community structure is STABLE (CV < 10%)");
        } else if communities_cv < 20.0 {
            info!(
                "⚠️  Community structure is MODERATELY STABLE (10% ≤ CV < 20%)"
            );
        } else {
            info!("❌ Community structure is UNSTABLE (CV ≥ 20%)");
        }

        // Check isolation ratio against threshold
        let threshold = self
            .config
            .analysis_params
            .analysis
            .isolation_ratio_threshold;
        if avg_isolation < threshold {
            info!(
                "⚠️  Network fragmentation detected: Average isolation ratio \
                 {:.2}% is below threshold {:.1}%",
                avg_isolation, threshold
            );
        } else {
            info!(
                "✅ Network connectivity is healthy: Average isolation ratio \
                 {:.2}% is above threshold {:.1}%",
                avg_isolation, threshold
            );
        }
    }

    async fn run_lpa_analysis(
        &self,
        projection_name: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let analyzer = CommunityAnalyzer::new(Arc::clone(&self.db_client));

        let result = analyzer
            .analyze_label_propagation_communities(
                projection_name,
                &self
                    .config
                    .analysis_params
                    .community_detection
                    .label_propagation,
            )
            .await?;

        analyzer.display_label_propagation_community_analysis(
            &result,
            &self.config.analysis_params.analysis,
        )?;

        Ok(())
    }

    /// Create default projection parameters (includes both success & failure)
    /// This maintains all relationship data for analysis
    fn create_default_projection_params(&self) -> GraphProjectionParams {
        let mut rel_types_map = HashMap::new();
        rel_types_map
            .insert("CIRCUIT_SUCCESS".to_string(), "NATURAL".to_string());
        rel_types_map
            .insert("CIRCUIT_FAILURE".to_string(), "NATURAL".to_string());

        GraphProjectionParams {
            projection_name: "tor_erpc_projection".to_string(),
            node_label: "Relay".to_string(),
            relationship_types: rel_types_map,
            // Properties are not used for current analysis
            relationship_properties_to_project: None,
        }
    }

    /// Create projection parameters with custom name (includes both success
    /// and failure)
    fn create_projection_params(&self, name: &str) -> GraphProjectionParams {
        let mut rel_types_map = HashMap::new();
        rel_types_map
            .insert("CIRCUIT_SUCCESS".to_string(), "NATURAL".to_string());
        rel_types_map
            .insert("CIRCUIT_FAILURE".to_string(), "NATURAL".to_string());

        GraphProjectionParams {
            projection_name: name.to_string(),
            node_label: "Relay".to_string(),
            relationship_types: rel_types_map,
            // Properties are not used for current analysis
            relationship_properties_to_project: None,
        }
    }

    /// Create projection for partition detection (success-only)
    /// Excludes CIRCUIT_FAILURE to detect actual connectivity partitions
    fn create_partition_detection_params(
        &self,
        name: &str,
    ) -> GraphProjectionParams {
        let mut rel_types_map = HashMap::new();
        rel_types_map
            // CIRCUIT_FAILURE intentionally excluded for partition detection
            .insert("CIRCUIT_SUCCESS".to_string(), "NATURAL".to_string());

        GraphProjectionParams {
            projection_name: name.to_string(),
            node_label: "Relay".to_string(),
            relationship_types: rel_types_map,
            relationship_properties_to_project: None,
        }
    }

    /// Create projection specifically for path analysis (UNDIRECTED)
    fn create_path_analysis_params(
        &self,
        name: &str,
    ) -> GraphProjectionParams {
        let mut rel_types_map = HashMap::new();
        rel_types_map
            // Use UNDIRECTED for path analysis to improve connectivity detection
            .insert("CIRCUIT_SUCCESS".to_string(), "UNDIRECTED".to_string());

        GraphProjectionParams {
            projection_name: name.to_string(),
            node_label: "Relay".to_string(),
            relationship_types: rel_types_map,
            relationship_properties_to_project: None,
        }
    }

    async fn handle_connectivity_projection(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let exists = self
            .db_client
            .check_graph_projection_exists("tor_erpc_connectivity_analysis")
            .await?;

        if !exists {
            info!(
                "❌ Connectivity projection 'tor_erpc_connectivity_analysis' \
                 does not exist."
            );

            // Create the connectivity projection (SUCCESS-only) for analysis
            info!("Creating projection with SUCCESS edges only...");

            let partition_params = self.create_partition_detection_params(
                "tor_erpc_connectivity_analysis",
            );

            self.db_client
                .create_graph_projection(&partition_params)
                .await
                .map_err(|e| {
                    error!(
                        "Failed to create connectivity projection: {:?}",
                        e
                    );
                    e
                })?;

            info!(
                "✅ Created connectivity projection - tor_erpc_connectivity_analysis"
            );
        }

        Ok(())
    }

    /// Handle path analysis projection creation (UNDIRECTED orientation)
    pub async fn handle_path_analysis_projection(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let projection_name = "tor_erpc_path_analysis";

        let exists = self
            .db_client
            .check_graph_projection_exists(projection_name)
            .await?;

        if !exists {
            info!(
                "❌ Path analysis projection '{}' does not exist.",
                projection_name
            );

            // Create the path analysis projection (UNDIRECTED) for path finding
            info!("Creating projection with UNDIRECTED edges for analysis...");

            let path_params =
                self.create_path_analysis_params(projection_name);

            self.db_client
                .create_graph_projection(&path_params)
                .await
                .map_err(|e| {
                    error!(
                        "Failed to create path analysis projection: {:?}",
                        e
                    );
                    e
                })?;

            info!("✅ Created path analysis projection - {}", projection_name);
        }

        Ok(())
    }

    /// Calculate and display metrics
    async fn calculate_and_display_metrics(
        &self,
        projection_name: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("=== Starting Graph Metrics Calculation ===");

        let graph_metrics = self
            .db_client
            .calculate_graph_metrics(projection_name)
            .await
            .map_err(|e: AnalysisError| {
                error!("Failed to calculate graph metrics: {:?}", e);
                Box::new(e) as Box<dyn std::error::Error>
            })?;

        self.display_basic_metrics(&graph_metrics)?;
        self.display_degree_distribution(&graph_metrics)?;

        let node_degrees = self
            .db_client
            .calculate_node_degrees(projection_name)
            .await
            .map_err(|e: AnalysisError| {
                error!("Failed to calculate node degrees: {:?}", e);
                Box::new(e) as Box<dyn std::error::Error>
            })?;

        self.display_degree_metrics(&node_degrees)?;

        info!("=== Graph Metrics Calculation Complete ===");
        Ok(())
    }

    fn display_basic_metrics(
        &self,
        metrics: &GraphMetrics,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Basic Graph Metrics:");
        info!("  Nodes: {}", metrics.node_count.unwrap_or(0));
        info!(
            "  Relationships: {}",
            metrics.relationship_count.unwrap_or(0)
        );
        info!(
            "  Average degree: {:.2}",
            metrics.average_degree.unwrap_or(0.0)
        );
        info!("  Maximum degree: {}", metrics.max_degree.unwrap_or(0));
        info!("  Minimum degree: {}", metrics.min_degree.unwrap_or(0));
        Ok(())
    }

    fn display_degree_metrics(
        &self,
        node_degrees: &[NodeMetrics],
    ) -> Result<(), Box<dyn std::error::Error>> {
        let mut sorted_degrees = node_degrees.to_vec();
        sorted_degrees.sort_by(|a, b| b.total_degree.cmp(&a.total_degree));

        info!(
            "Top {} Most Connected Relays:",
            self.config.analysis_params.analysis.max_display_components
        );
        for (i, node) in sorted_degrees
            .iter()
            .take(self.config.analysis_params.analysis.max_display_components)
            .enumerate()
        {
            info!(
                "  {}. {} - Total: {}, In: {}, Out: {}",
                i + 1,
                &node.fingerprint,
                node.total_degree,
                node.in_degree,
                node.out_degree
            );
        }
        Ok(())
    }

    fn display_degree_distribution(
        &self,
        metrics: &GraphMetrics,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(degree_dist) = &metrics.degree_distribution {
            info!(
                "Degree Distribution ({} unique values):",
                degree_dist.len()
            );
            let mut dist_vec: Vec<(i64, i64)> =
                degree_dist.iter().map(|(&k, &v)| (k, v)).collect();
            dist_vec.sort_by(|a, b| b.1.cmp(&a.1)); // Sort by count descending

            info!("  Top 5 Most Common Degrees:");
            for (i, (degree, count)) in dist_vec
                .iter()
                .take(
                    self.config
                        .analysis_params
                        .analysis
                        .max_display_components
                        .min(5),
                )
                .enumerate()
            {
                info!(
                    "    {}. {} relays have degree {}",
                    i + 1,
                    count,
                    degree
                );
            }
        } else {
            warn!("No degree distribution data available");
        }
        Ok(())
    }

    /// Handle betweenness centrality analysis
    async fn handle_centrality_betweenness(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running betweenness centrality analysis...");

        // Ensure we have a graph projection
        self.handle_connectivity_projection().await?;

        let centrality_analyzer =
            crate::algorithms::centrality::CentralityAnalyzer::new(
                Arc::clone(&self.db_client),
            );

        let centrality_config = &self.config.analysis_params.centrality;
        let result = centrality_analyzer
            .analyze_betweenness_centrality(
                "tor_erpc_connectivity_analysis",
                centrality_config.betweenness_sampling_size,
                centrality_config.betweenness_sampling_seed,
            )
            .await?;

        centrality_analyzer.display_centrality_results(
            &result,
            "betweenness",
            &self.config.analysis_params.analysis,
        );

        println!("✅ Successfully completed betweenness centrality analysis");
        Ok(())
    }

    /// Handle closeness centrality analysis
    async fn handle_centrality_closeness(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running closeness centrality analysis...");

        // Ensure we have a graph projection
        self.handle_connectivity_projection().await?;

        let centrality_analyzer =
            crate::algorithms::centrality::CentralityAnalyzer::new(
                Arc::clone(&self.db_client),
            );

        let centrality_config = &self.config.analysis_params.centrality;
        let result = centrality_analyzer
            .analyze_closeness_centrality(
                "tor_erpc_connectivity_analysis",
                centrality_config.use_wasserman_faust,
            )
            .await?;

        centrality_analyzer.display_centrality_results(
            &result,
            "closeness",
            &self.config.analysis_params.analysis,
        );

        println!("✅ Successfully completed closeness centrality analysis");
        Ok(())
    }

    /// Handle combined centrality analysis
    pub async fn handle_centrality_combined(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running combined centrality analysis...");

        // Ensure we have a graph projection
        self.handle_connectivity_projection().await?;

        let centrality_analyzer =
            crate::algorithms::centrality::CentralityAnalyzer::new(
                Arc::clone(&self.db_client),
            );

        let centrality_config = &self.config.analysis_params.centrality;
        let result = centrality_analyzer
            .analyze_combined_centrality(
                "tor_erpc_connectivity_analysis",
                centrality_config.betweenness_sampling_size,
                centrality_config.betweenness_sampling_seed,
                centrality_config.use_wasserman_faust,
            )
            .await?;

        centrality_analyzer.display_centrality_results(
            &result,
            "combined",
            &self.config.analysis_params.analysis,
        );

        println!("✅ Successfully completed combined centrality analysis");
        Ok(())
    }

    /// Handle internal connectivity analysis within communities
    pub async fn handle_path_connectivity(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running internal connectivity analysis within communities...");

        // Ensure we have a path analysis projection
        self.handle_path_analysis_projection().await?;

        info!("Validating graph projection...");
        let projection_info = self
            .db_client
            .calculate_graph_metrics("tor_erpc_path_analysis")
            .await?;
        info!(
            "Projection has {} nodes and {} relationships",
            projection_info.node_count.unwrap_or(0),
            projection_info.relationship_count.unwrap_or(0)
        );

        if projection_info.node_count.unwrap_or(0) == 0 {
            return Err(
                "Graph projection is empty! Cannot perform connectivity analysis."
                    .into(),
            );
        }

        // Step 1: Use Louvain community detection
        info!("🔍 Detecting communities using Louvain algorithm...");
        let community_analyzer =
            crate::algorithms::communities::CommunityAnalyzer::new(
                Arc::clone(&self.db_client),
            );

        let louvain_result = community_analyzer
            .analyze_louvain_communities(
                "tor_erpc_path_analysis",
                &self.config.analysis_params.community_detection.louvain,
            )
            .await?;

        let total_communities = louvain_result.total_components.unwrap_or(0);
        if total_communities == 0 {
            info!("No communities found for connectivity analysis");
            return Ok(());
        }

        info!(
            "Found {} communities with modularity: {:.4}",
            total_communities,
            louvain_result.modularity.unwrap_or(0.0)
        );

        // Step 2: Analyze internal connectivity within the largest community
        let largest_community = &louvain_result.components[0];
        info!(
            "Analyzing internal connectivity of largest community with {} nodes",
            largest_community.relay_fingerprints.len()
        );

        let nodes_per_group = self
            .config
            .analysis_params
            .path_analysis
            .internal_component_sample_size;

        // Sample nodes from the largest community for internal connectivity analysis
        let (source_samples, target_samples) = self
            .sample_nodes_for_path_analysis(
                &largest_community.relay_fingerprints,
                &largest_community.relay_fingerprints,
                nodes_per_group,
            )?;

        info!(
            "Analyzing internal paths between {} source and {} target nodes",
            source_samples.len(),
            target_samples.len()
        );

        // Perform internal connectivity analysis
        let path_analyzer = crate::algorithms::path::PathAnalyzer::new(
            Arc::clone(&self.db_client),
        );

        let result = path_analyzer
            .analyze_inter_community_paths(
                "tor_erpc_path_analysis",
                &source_samples,
                &target_samples,
            )
            .await?;

        path_analyzer.display_path_results(&result);

        let connectivity_ratio = if let (Some(connected), Some(total)) = (
            result.connected_community_pairs,
            result.total_paths_analyzed,
        ) {
            if total > 0 {
                (connected as f64 / total as f64) * 100.0
            } else {
                0.0
            }
        } else {
            0.0
        };

        info!("=== Internal Community Connectivity Analysis ===");
        info!("Internal connectivity ratio: {:.2}%", connectivity_ratio);

        if connectivity_ratio > 90.0 {
            info!("✅ Good internal connectivity within largest community");
        } else if connectivity_ratio > 50.0 {
            info!(
                "⚠️  Moderate internal connectivity within largest community"
            );
        } else {
            info!("❌ Poor internal connectivity within largest community");
        }

        if let Some(avg_length) = result.average_path_length {
            info!("📏 Average internal path length: {:.2}", avg_length);
        }

        // Provide context about community structure
        info!("=== Community Structure Analysis ===");
        info!("Network has {} communities total", total_communities);
        info!(
            "Largest community: {} nodes ({:.2}% of network)",
            largest_community.relay_fingerprints.len(),
            (largest_community.relay_fingerprints.len() as f64
                / projection_info.node_count.unwrap_or(1) as f64)
                * 100.0
        );

        if louvain_result.components.len() > 1 {
            info!(
                "Second largest community: {} nodes",
                louvain_result.components[1].relay_fingerprints.len()
            );
        }

        let modularity = louvain_result.modularity.unwrap_or(0.0);
        if modularity > 0.3 {
            info!(
                "✅ Strong community structure (modularity: {:.4})",
                modularity
            );
        } else {
            info!(
                "⚠️  Weak community structure (modularity: {:.4})",
                modularity
            );
        }

        println!("✅ Successfully completed internal connectivity analysis");
        Ok(())
    }

    /// Handle advanced path analysis using community detection
    pub async fn handle_advanced_path_analysis(
        &self,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("Running advanced path analysis using community detection...");

        // Ensure we have a path analysis projection
        self.handle_path_analysis_projection().await?;

        let projection_info = self
            .db_client
            .calculate_graph_metrics("tor_erpc_path_analysis")
            .await?;
        info!(
            "Projection has {} nodes and {} relationships",
            projection_info.node_count.unwrap_or(0),
            projection_info.relationship_count.unwrap_or(0)
        );

        if projection_info.node_count.unwrap_or(0) == 0 {
            return Err("Graph projection is empty!".into());
        }

        // Step 1: Use Louvain community detection
        info!("🔍 Step 1: Detecting communities using Louvain algorithm...");
        let community_analyzer =
            crate::algorithms::communities::CommunityAnalyzer::new(
                Arc::clone(&self.db_client),
            );
        let louvain_result = community_analyzer
            .analyze_louvain_communities(
                "tor_erpc_path_analysis",
                &self.config.analysis_params.community_detection.louvain,
            )
            .await?;

        let total_communities = louvain_result.total_components.unwrap_or(0);
        if total_communities < 2 {
            info!(
                "Found only {} community - advanced path analysis requires >= 2",
                total_communities
            );
            return Ok(());
        }

        info!(
            "Found {} communities with modularity: {:.4}",
            total_communities,
            louvain_result.modularity.unwrap_or(0.0)
        );

        // Step 2: Analyze inter-community paths
        info!("🔍 Step 2: Analyzing paths between communities...");
        let path_analyzer = crate::algorithms::path::PathAnalyzer::new(
            Arc::clone(&self.db_client),
        );

        let num_top = self
            .config
            .analysis_params
            .path_analysis
            .num_top_communities;
        let top_communities = louvain_result
            .components
            .iter()
            .take(num_top)
            .collect::<Vec<_>>();

        for (i, source_community) in top_communities.iter().enumerate() {
            for (j, target_community) in top_communities.iter().enumerate() {
                if i >= j {
                    continue;
                }

                info!(
                    "Analyzing paths: Community {} ({} nodes) → Community {} ({} nodes)",
                    source_community.component_id,
                    source_community.relay_fingerprints.len(),
                    target_community.component_id,
                    target_community.relay_fingerprints.len()
                );

                // Sample nodes from each community using randomization
                let sample_size = self
                    .config
                    .analysis_params
                    .path_analysis
                    .sample_size_communities;
                let (source_samples, target_samples) = self
                    .sample_nodes_for_path_analysis(
                        &source_community.relay_fingerprints,
                        &target_community.relay_fingerprints,
                        sample_size,
                    )?;

                match path_analyzer
                    .analyze_inter_community_paths(
                        "tor_erpc_path_analysis",
                        &source_samples,
                        &target_samples,
                    )
                    .await
                {
                    Ok(result) => {
                        let connectivity_ratio =
                            if let (Some(connected), Some(total)) = (
                                result.connected_community_pairs,
                                result.total_paths_analyzed,
                            ) {
                                if total > 0 {
                                    (connected as f64 / total as f64) * 100.0
                                } else {
                                    0.0
                                }
                            } else {
                                0.0
                            };

                        info!(
                            "  Inter-community connectivity: {:.2}%",
                            connectivity_ratio
                        );
                        if let Some(avg_length) = result.average_path_length {
                            info!("  Average path length: {:.2}", avg_length);
                        }
                    }
                    Err(e) => {
                        error!("  Path analysis failed: {}", e);
                    }
                }
            }
        }

        // Step 3: Enhanced analysis with ASN-based partitioning
        info!("🔍 Step 3: Analyzing paths by ASN partitioning...");
        let classifier =
            crate::algorithms::classification::PartitionClassifier::new(
                Arc::clone(&self.db_client),
            );

        // Use communities from Louvain algorithm
        let asn_result = classifier
            .classify_by_asn(&louvain_result.components)
            .await?;

        info!(
            "Found {} ASN groups with {:.1}% coverage",
            asn_result.metrics.total_groups,
            asn_result.metrics.classification_coverage
        );

        // Analyze paths between different ASNs
        let num_top_asn =
            self.config.analysis_params.path_analysis.num_top_asn_groups;
        let top_asn_groups = asn_result
            .groups
            .iter()
            .take(num_top_asn)
            .collect::<Vec<_>>();

        for (i, source_asn) in top_asn_groups.iter().enumerate() {
            for (j, target_asn) in top_asn_groups.iter().enumerate() {
                if i >= j {
                    continue;
                }

                info!(
                    "Analyzing paths: ASN {} ({} relays) → ASN {} ({} relays)",
                    source_asn.identifier,
                    source_asn.relay_fingerprints.len(),
                    target_asn.identifier,
                    target_asn.relay_fingerprints.len()
                );

                let sample_size = self
                    .config
                    .analysis_params
                    .path_analysis
                    .sample_size_asn_groups;
                let (source_samples, target_samples) = self
                    .sample_nodes_for_path_analysis(
                        &source_asn.relay_fingerprints,
                        &target_asn.relay_fingerprints,
                        sample_size,
                    )?;

                match path_analyzer
                    .analyze_inter_community_paths(
                        "tor_erpc_path_analysis",
                        &source_samples,
                        &target_samples,
                    )
                    .await
                {
                    Ok(result) => {
                        let connectivity_ratio =
                            if let (Some(connected), Some(total)) = (
                                result.connected_community_pairs,
                                result.total_paths_analyzed,
                            ) {
                                if total > 0 {
                                    (connected as f64 / total as f64) * 100.0
                                } else {
                                    0.0
                                }
                            } else {
                                0.0
                            };

                        info!(
                            "  Inter-ASN connectivity: {:.2}%",
                            connectivity_ratio
                        );
                        if connectivity_ratio > 0.0 {
                            if let Some(avg_length) =
                                result.average_path_length
                            {
                                info!(
                                    "  Average path length: {:.2}",
                                    avg_length
                                );
                            }
                        }
                    }
                    Err(e) => {
                        error!("  Path analysis failed: {}", e);
                    }
                }
            }
        }

        info!("=== Advanced Path Analysis Summary ===");
        info!(
            "✅ Modularity score: {:.4} (>0.3 indicates strong community structure)",
            louvain_result.modularity.unwrap_or(0.0)
        );

        println!("✅ Successfully completed advanced path analysis");
        Ok(())
    }

    /// Sample nodes from collections with randomization and balanced groups
    fn sample_nodes_for_path_analysis(
        &self,
        source_collection: &[String],
        target_collection: &[String],
        nodes_per_group: usize,
    ) -> Result<(Vec<String>, Vec<String>), Box<dyn std::error::Error>> {
        use rand::prelude::*;

        if source_collection.is_empty() || target_collection.is_empty() {
            return Err("Cannot sample from empty collections".into());
        }

        // Sample from source collection with randomization
        let mut source_nodes = source_collection.to_vec();
        source_nodes.shuffle(&mut thread_rng());
        let source_samples =
            source_nodes.into_iter().take(nodes_per_group).collect();

        // Sample from target collection with randomization
        let mut target_nodes = target_collection.to_vec();
        target_nodes.shuffle(&mut thread_rng());
        let target_samples =
            target_nodes.into_iter().take(nodes_per_group).collect();

        Ok((source_samples, target_samples))
    }
}