raps-cli 4.15.0

RAPS (rapeseed) - Rust Autodesk Platform Services CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2025 Dmytro Yemelianov

//! Admin bulk operations tool implementations for the MCP server.

use std::sync::Arc;

use futures_util::stream::{self as stream_util, StreamExt as _};
use raps_admin::{BulkConfig, FolderType, PermissionLevel, ProjectFilter, StateManager};

use super::server::{MCP_BULK_CONCURRENCY, RapsServer};

impl RapsServer {
    pub(crate) async fn admin_project_list(
        &self,
        account_id: String,
        filter: Option<String>,
        limit: Option<usize>,
    ) -> String {
        let client = self.get_admin_client().await;
        let limit = Self::clamp_limit(limit, 100, 500);

        match client.list_all_projects(&account_id).await {
            Ok(projects) => {
                // Apply filter if specified
                let project_filter = if let Some(ref f) = filter {
                    match ProjectFilter::from_expression(f) {
                        Ok(pf) => pf,
                        Err(e) => return format!("Invalid filter expression: {}", e),
                    }
                } else {
                    ProjectFilter::new()
                };

                let filtered = project_filter.apply(projects);
                let filtered: Vec<_> = filtered.into_iter().take(limit).collect();

                let mut output = format!(
                    "Found {} project(s) in account {}:\n\n",
                    filtered.len(),
                    account_id
                );
                for proj in &filtered {
                    let status = proj.status.as_deref().unwrap_or("unknown");
                    let platform = if proj.is_acc() {
                        "ACC"
                    } else if proj.is_bim360() {
                        "BIM360"
                    } else {
                        "unknown"
                    };
                    output.push_str(&format!(
                        "* {} (id: {}, status: {}, platform: {})\n",
                        proj.name, proj.id, status, platform
                    ));
                }
                output
            }
            Err(e) => format!("Failed to list projects: {}", e),
        }
    }

    pub(crate) async fn admin_user_add(
        &self,
        account_id: String,
        email: String,
        role: Option<String>,
        filter: Option<String>,
        dry_run: bool,
    ) -> String {
        let admin_client = self.get_admin_client().await;
        let users_client = Arc::new(self.get_users_client().await);

        // Parse filter
        let project_filter = if let Some(ref f) = filter {
            match ProjectFilter::from_expression(f) {
                Ok(pf) => pf,
                Err(e) => return format!("Invalid filter expression: {}", e),
            }
        } else {
            ProjectFilter::new()
        };

        let bulk_config = BulkConfig {
            concurrency: MCP_BULK_CONCURRENCY,
            dry_run,
            ..Default::default()
        };

        // Progress callback (no-op for MCP)
        let on_progress = |_| {};

        match raps_admin::bulk_add_user(
            &admin_client,
            users_client,
            &account_id,
            &email,
            role.as_deref(),
            &project_filter,
            bulk_config,
            on_progress,
        )
        .await
        {
            Ok(result) => {
                let mut output = format!(
                    "Bulk add user operation {}:\n\n* Total: {}\n* Completed: {}\n* Skipped: {}\n* Failed: {}\n* Duration: {:.2}s\n",
                    if dry_run { "(DRY RUN)" } else { "completed" },
                    result.total,
                    result.completed,
                    result.skipped,
                    result.failed,
                    result.duration.as_secs_f64()
                );
                if result.failed > 0 {
                    output.push_str("\nFailed projects:\n");
                    for detail in &result.details {
                        if let raps_admin::ItemResult::Failed { error, .. } = &detail.result {
                            output.push_str(&format!(
                                "  * {}: {}\n",
                                detail.project_name.as_deref().unwrap_or(&detail.project_id),
                                error
                            ));
                        }
                    }
                }
                output
            }
            Err(e) => format!("Bulk add user failed: {}", e),
        }
    }

    pub(crate) async fn admin_user_remove(
        &self,
        account_id: String,
        email: String,
        filter: Option<String>,
        dry_run: bool,
    ) -> String {
        let admin_client = self.get_admin_client().await;
        let users_client = Arc::new(self.get_users_client().await);

        let project_filter = if let Some(ref f) = filter {
            match ProjectFilter::from_expression(f) {
                Ok(pf) => pf,
                Err(e) => return format!("Invalid filter expression: {}", e),
            }
        } else {
            ProjectFilter::new()
        };

        let bulk_config = BulkConfig {
            concurrency: MCP_BULK_CONCURRENCY,
            dry_run,
            ..Default::default()
        };

        let on_progress = |_| {};

        match raps_admin::bulk_remove_user(
            &admin_client,
            users_client,
            &account_id,
            &email,
            &project_filter,
            bulk_config,
            on_progress,
        )
        .await
        {
            Ok(result) => {
                format!(
                    "Bulk remove user operation {}:\n\n* Total: {}\n* Completed: {}\n* Skipped: {}\n* Failed: {}\n* Duration: {:.2}s",
                    if dry_run { "(DRY RUN)" } else { "completed" },
                    result.total,
                    result.completed,
                    result.skipped,
                    result.failed,
                    result.duration.as_secs_f64()
                )
            }
            Err(e) => format!("Bulk remove user failed: {}", e),
        }
    }

    pub(crate) async fn admin_user_update_role(
        &self,
        account_id: String,
        email: String,
        role: String,
        filter: Option<String>,
        dry_run: bool,
    ) -> String {
        let admin_client = self.get_admin_client().await;
        let users_client = Arc::new(self.get_users_client().await);

        let project_filter = if let Some(ref f) = filter {
            match ProjectFilter::from_expression(f) {
                Ok(pf) => pf,
                Err(e) => return format!("Invalid filter expression: {}", e),
            }
        } else {
            ProjectFilter::new()
        };

        let bulk_config = BulkConfig {
            concurrency: MCP_BULK_CONCURRENCY,
            dry_run,
            ..Default::default()
        };

        let on_progress = |_| {};

        match raps_admin::bulk_update_role(
            &admin_client,
            users_client,
            &account_id,
            &email,
            &role,
            None, // from_role
            &project_filter,
            bulk_config,
            on_progress,
        )
        .await
        {
            Ok(result) => {
                format!(
                    "Bulk update role operation {}:\n\n* Total: {}\n* Completed: {}\n* Skipped: {}\n* Failed: {}\n* Duration: {:.2}s",
                    if dry_run { "(DRY RUN)" } else { "completed" },
                    result.total,
                    result.completed,
                    result.skipped,
                    result.failed,
                    result.duration.as_secs_f64()
                )
            }
            Err(e) => format!("Bulk update role failed: {}", e),
        }
    }

    pub(crate) async fn admin_folder_rights(
        &self,
        account_id: String,
        email: String,
        level: String,
        folder: Option<String>,
        filter: Option<String>,
        dry_run: bool,
    ) -> String {
        // Parse permission level
        let permission_level = match level.to_lowercase().as_str() {
            "view_only" => PermissionLevel::ViewOnly,
            "view_download" => PermissionLevel::ViewDownload,
            "upload_only" => PermissionLevel::UploadOnly,
            "view_download_upload" => PermissionLevel::ViewDownloadUpload,
            "view_download_upload_edit" => PermissionLevel::ViewDownloadUploadEdit,
            "folder_control" => PermissionLevel::FolderControl,
            _ => {
                return format!(
                    "Invalid permission level: '{}'. Valid: view_only, view_download, upload_only, view_download_upload, view_download_upload_edit, folder_control",
                    level
                );
            }
        };

        // Parse folder type
        let folder_type = match folder.as_deref().unwrap_or("project_files") {
            "project_files" => FolderType::ProjectFiles,
            "plans" => FolderType::Plans,
            id => FolderType::Custom(id.to_string()),
        };

        // Parse filter
        let project_filter = if let Some(ref f) = filter {
            match ProjectFilter::from_expression(f) {
                Ok(pf) => pf,
                Err(e) => return format!("Invalid filter expression: {}", e),
            }
        } else {
            ProjectFilter::new()
        };

        let admin_client = self.get_admin_client().await;
        let permissions_client = Arc::new(self.get_permissions_client().await);

        let bulk_config = BulkConfig {
            concurrency: MCP_BULK_CONCURRENCY,
            dry_run,
            ..Default::default()
        };

        let on_progress = |_| {};

        match raps_admin::bulk_update_folder_rights(
            &admin_client,
            permissions_client,
            &account_id,
            &email,
            permission_level,
            folder_type,
            &project_filter,
            bulk_config,
            on_progress,
        )
        .await
        {
            Ok(result) => {
                format!(
                    "Bulk folder rights operation {}:\n\n* Total: {}\n* Completed: {}\n* Skipped: {}\n* Failed: {}\n* Duration: {:.2}s",
                    if dry_run { "(DRY RUN)" } else { "completed" },
                    result.total,
                    result.completed,
                    result.skipped,
                    result.failed,
                    result.duration.as_secs_f64()
                )
            }
            Err(e) => format!("Bulk folder rights failed: {}", e),
        }
    }

    pub(crate) async fn admin_operation_list(&self, limit: Option<usize>) -> String {
        let limit = Self::clamp_limit(limit, 10, 50);

        match StateManager::new() {
            Ok(state_manager) => match state_manager.list_operations(None).await {
                Ok(operations) => {
                    let operations: Vec<_> = operations.into_iter().take(limit).collect();
                    if operations.is_empty() {
                        return "No operations found.".to_string();
                    }

                    let mut output = format!("Found {} operation(s):\n\n", operations.len());
                    for op in &operations {
                        output.push_str(&format!(
                            "* {} ({:?}) - {:?} [{}/{}]\n",
                            op.operation_id,
                            op.operation_type,
                            op.status,
                            op.completed + op.skipped + op.failed,
                            op.total
                        ));
                    }
                    output
                }
                Err(e) => format!("Failed to list operations: {}", e),
            },
            Err(e) => format!("Failed to initialize state manager: {}", e),
        }
    }

    pub(crate) async fn admin_operation_status(&self, operation_id: Option<String>) -> String {
        match StateManager::new() {
            Ok(state_manager) => {
                let op_id = match operation_id {
                    Some(id) => match uuid::Uuid::parse_str(&id) {
                        Ok(uuid) => uuid,
                        Err(_) => return "Invalid operation ID format".to_string(),
                    },
                    None => {
                        // Get most recent
                        match state_manager.list_operations(None).await {
                            Ok(ops) if !ops.is_empty() => ops[0].operation_id,
                            _ => return "No operations found".to_string(),
                        }
                    }
                };

                match state_manager.load_operation(op_id).await {
                    Ok(state) => {
                        let completed = state
                            .results
                            .values()
                            .filter(|r| matches!(r.result, raps_admin::ItemResult::Success))
                            .count();
                        let skipped = state
                            .results
                            .values()
                            .filter(|r| matches!(r.result, raps_admin::ItemResult::Skipped { .. }))
                            .count();
                        let failed = state
                            .results
                            .values()
                            .filter(|r| matches!(r.result, raps_admin::ItemResult::Failed { .. }))
                            .count();

                        format!(
                            "Operation Status:\n\n* ID: {}\n* Type: {:?}\n* Status: {:?}\n* Progress: {}/{}\n* Completed: {}\n* Skipped: {}\n* Failed: {}\n* Created: {}\n* Updated: {}",
                            state.operation_id,
                            state.operation_type,
                            state.status,
                            completed + skipped + failed,
                            state.project_ids.len(),
                            completed,
                            skipped,
                            failed,
                            state.created_at.to_rfc3339(),
                            state.updated_at.to_rfc3339()
                        )
                    }
                    Err(e) => format!("Failed to load operation: {}", e),
                }
            }
            Err(e) => format!("Failed to initialize state manager: {}", e),
        }
    }

    pub(crate) async fn admin_operation_cancel(&self, operation_id: String) -> String {
        let op_id = match uuid::Uuid::parse_str(&operation_id) {
            Ok(uuid) => uuid,
            Err(_) => return "Invalid operation ID format".to_string(),
        };

        match StateManager::new() {
            Ok(state_manager) => match state_manager.cancel_operation(op_id).await {
                Ok(()) => format!("Operation {} cancelled successfully", operation_id),
                Err(e) => format!("Failed to cancel operation: {}", e),
            },
            Err(e) => format!("Failed to initialize state manager: {}", e),
        }
    }

    pub(crate) async fn admin_operation_resume(&self, operation_id: Option<String>) -> String {
        let state_manager = match StateManager::new() {
            Ok(sm) => sm,
            Err(e) => return format!("Failed to initialize state manager: {}", e),
        };

        // Get the operation ID (from param or most recent)
        let op_id = match operation_id {
            Some(id) => match uuid::Uuid::parse_str(&id) {
                Ok(uuid) => uuid,
                Err(_) => return "Invalid operation ID format".to_string(),
            },
            None => {
                // Get most recent incomplete operation
                match state_manager.list_operations(None).await {
                    Ok(ops) => {
                        match ops
                            .iter()
                            .find(|o| o.status == raps_admin::OperationStatus::InProgress)
                        {
                            Some(op) => op.operation_id,
                            None => return "No in-progress operations to resume".to_string(),
                        }
                    }
                    Err(e) => return format!("Failed to list operations: {}", e),
                }
            }
        };

        // Load the operation state
        let state = match state_manager.load_operation(op_id).await {
            Ok(s) => s,
            Err(e) => return format!("Failed to load operation: {}", e),
        };

        // Check operation status
        if state.status != raps_admin::OperationStatus::InProgress {
            return format!(
                "Operation {} has status {:?} and cannot be resumed",
                op_id, state.status
            );
        }

        let bulk_config = BulkConfig {
            concurrency: MCP_BULK_CONCURRENCY,
            dry_run: false,
            ..Default::default()
        };
        let on_progress = |_| {};

        // Resume based on operation type
        match state.operation_type {
            raps_admin::OperationType::AddUser => {
                let users_client = Arc::new(self.get_users_client().await);
                match raps_admin::resume_bulk_add_user(
                    users_client,
                    op_id,
                    bulk_config,
                    on_progress,
                )
                .await
                {
                    Ok(result) => format!(
                        "Resumed add user operation:\n\n* Total: {}\n* Completed: {}\n* Skipped: {}\n* Failed: {}\n* Duration: {:.2}s",
                        result.total,
                        result.completed,
                        result.skipped,
                        result.failed,
                        result.duration.as_secs_f64()
                    ),
                    Err(e) => format!("Failed to resume operation: {}", e),
                }
            }
            raps_admin::OperationType::RemoveUser => {
                let users_client = Arc::new(self.get_users_client().await);
                match raps_admin::resume_bulk_remove_user(
                    users_client,
                    op_id,
                    bulk_config,
                    on_progress,
                )
                .await
                {
                    Ok(result) => format!(
                        "Resumed remove user operation:\n\n* Total: {}\n* Completed: {}\n* Skipped: {}\n* Failed: {}\n* Duration: {:.2}s",
                        result.total,
                        result.completed,
                        result.skipped,
                        result.failed,
                        result.duration.as_secs_f64()
                    ),
                    Err(e) => format!("Failed to resume operation: {}", e),
                }
            }
            raps_admin::OperationType::UpdateRole => {
                let users_client = Arc::new(self.get_users_client().await);
                match raps_admin::resume_bulk_update_role(
                    users_client,
                    op_id,
                    bulk_config,
                    on_progress,
                )
                .await
                {
                    Ok(result) => format!(
                        "Resumed update role operation:\n\n* Total: {}\n* Completed: {}\n* Skipped: {}\n* Failed: {}\n* Duration: {:.2}s",
                        result.total,
                        result.completed,
                        result.skipped,
                        result.failed,
                        result.duration.as_secs_f64()
                    ),
                    Err(e) => format!("Failed to resume operation: {}", e),
                }
            }
            raps_admin::OperationType::UpdateFolderRights => {
                let permissions_client = Arc::new(self.get_permissions_client().await);
                match raps_admin::resume_bulk_update_folder_rights(
                    permissions_client,
                    op_id,
                    bulk_config,
                    on_progress,
                )
                .await
                {
                    Ok(result) => format!(
                        "Resumed folder rights operation:\n\n* Total: {}\n* Completed: {}\n* Skipped: {}\n* Failed: {}\n* Duration: {:.2}s",
                        result.total,
                        result.completed,
                        result.skipped,
                        result.failed,
                        result.duration.as_secs_f64()
                    ),
                    Err(e) => format!("Failed to resume operation: {}", e),
                }
            }
        }
    }

    // ================================================================
    // Admin User Listing (v4.6)
    // ================================================================

    pub(crate) async fn admin_user_list(
        &self,
        account_id: String,
        project_id: Option<String>,
        search: Option<String>,
        role: Option<String>,
        status: Option<String>,
    ) -> String {
        if let Some(pid) = project_id {
            // Project-level user listing
            let client = self.get_users_client().await;
            match client.list_all_project_users(&pid).await {
                Ok(users) => {
                    let filtered: Vec<_> = users
                        .into_iter()
                        .filter(|u| {
                            if let Some(ref r) = role {
                                if let Some(ref rn) = u.role_name {
                                    if !rn.to_lowercase().contains(&r.to_lowercase()) {
                                        return false;
                                    }
                                } else {
                                    return false;
                                }
                            }
                            if let Some(ref s) = search {
                                let sl = s.to_lowercase();
                                let email_match = u
                                    .email
                                    .as_ref()
                                    .map(|e| e.to_lowercase().contains(&sl))
                                    .unwrap_or(false);
                                let name_match = u
                                    .name
                                    .as_ref()
                                    .map(|n| n.to_lowercase().contains(&sl))
                                    .unwrap_or(false);
                                if !email_match && !name_match {
                                    return false;
                                }
                            }
                            true
                        })
                        .collect();

                    let mut output =
                        format!("Found {} user(s) in project {}:\n\n", filtered.len(), pid);
                    for u in &filtered {
                        let email = u.email.as_deref().unwrap_or("N/A");
                        let name = u.name.as_deref().unwrap_or("N/A");
                        let role_name = u.role_name.as_deref().unwrap_or("N/A");
                        output.push_str(&format!("* {} ({}) - role: {}\n", email, name, role_name));
                    }
                    output
                }
                Err(e) => format!("Failed to list project users: {}", e),
            }
        } else {
            // Account-level user listing
            let client = self.get_admin_client().await;
            match client.list_all_users(&account_id).await {
                Ok(users) => {
                    let filtered: Vec<_> = users
                        .into_iter()
                        .filter(|u| {
                            if let Some(ref s) = status {
                                if let Some(ref us) = u.status {
                                    if !us.to_lowercase().eq(&s.to_lowercase()) {
                                        return false;
                                    }
                                } else {
                                    return false;
                                }
                            }
                            if let Some(ref s) = search {
                                let sl = s.to_lowercase();
                                let email_match = u.email.to_lowercase().contains(&sl);
                                let name_match = u
                                    .name
                                    .as_ref()
                                    .map(|n| n.to_lowercase().contains(&sl))
                                    .unwrap_or(false);
                                if !email_match && !name_match {
                                    return false;
                                }
                            }
                            true
                        })
                        .collect();

                    let mut output = format!(
                        "Found {} user(s) in account {}:\n\n",
                        filtered.len(),
                        account_id
                    );
                    for u in &filtered {
                        let name = u.display_name();
                        let status_str = u.status.as_deref().unwrap_or("unknown");
                        let company = u.company_id.as_deref().unwrap_or("N/A");
                        output.push_str(&format!(
                            "* {} ({}) - status: {}, company: {}\n",
                            u.email, name, status_str, company
                        ));
                    }
                    output
                }
                Err(e) => format!("Failed to list account users: {}", e),
            }
        }
    }

    // ================================================================
    // Portfolio Reports (v4.6)
    // ================================================================

    pub(crate) async fn report_rfi_summary(
        &self,
        account_id: String,
        filter: Option<String>,
        status_filter: Option<String>,
    ) -> String {
        let admin_client = self.get_admin_client().await;

        let project_filter = if let Some(ref f) = filter {
            match ProjectFilter::from_expression(f) {
                Ok(pf) => pf,
                Err(e) => return format!("Invalid filter expression: {}", e),
            }
        } else {
            ProjectFilter::new()
        };

        let projects = match admin_client.list_all_projects(&account_id).await {
            Ok(p) => project_filter.apply(p),
            Err(e) => return format!("Failed to list projects: {}", e),
        };

        if projects.is_empty() {
            return "No projects found matching filter.".to_string();
        }

        let rfi_client = self.get_rfi_client().await;
        let project_count = projects.len();

        // Fetch RFIs in parallel (bounded concurrency) instead of serial N+1
        let futs: Vec<_> = projects
            .into_iter()
            .map(|proj| {
                let client = rfi_client.clone();
                let sf = status_filter.clone();
                let proj_id = proj.id;
                let proj_name = proj.name;
                async move {
                    let res = client.list_rfis(&proj_id).await;
                    (proj_name, sf, res)
                }
            })
            .collect();

        let results: Vec<_> = stream_util::iter(futs)
            .buffer_unordered(MCP_BULK_CONCURRENCY)
            .collect()
            .await;

        let mut output = format!("RFI Summary for {} project(s):\n\n", project_count);
        let mut grand_total = 0usize;
        let mut grand_open = 0usize;

        for (proj_name, sf, res) in &results {
            match res {
                Ok(rfis) => {
                    let filtered: Vec<_> = if let Some(sf) = sf {
                        rfis.iter()
                            .filter(|r| r.status.to_lowercase() == sf.to_lowercase())
                            .collect()
                    } else {
                        rfis.iter().collect()
                    };
                    let total = filtered.len();
                    let open = filtered
                        .iter()
                        .filter(|r| r.status.to_lowercase() == "open")
                        .count();
                    grand_total += total;
                    grand_open += open;
                    if total > 0 {
                        output.push_str(&format!(
                            "* {} - {} RFIs ({} open)\n",
                            proj_name, total, open
                        ));
                    }
                }
                Err(_) => {
                    output.push_str(&format!("* {} - (access denied)\n", proj_name));
                }
            }
        }

        output.push_str(&format!(
            "\nTotal: {} RFIs across {} projects ({} open)",
            grand_total, project_count, grand_open
        ));
        output
    }

    pub(crate) async fn report_issues_summary(
        &self,
        account_id: String,
        filter: Option<String>,
        status_filter: Option<String>,
    ) -> String {
        let admin_client = self.get_admin_client().await;

        let project_filter = if let Some(ref f) = filter {
            match ProjectFilter::from_expression(f) {
                Ok(pf) => pf,
                Err(e) => return format!("Invalid filter expression: {}", e),
            }
        } else {
            ProjectFilter::new()
        };

        let projects = match admin_client.list_all_projects(&account_id).await {
            Ok(p) => project_filter.apply(p),
            Err(e) => return format!("Failed to list projects: {}", e),
        };

        if projects.is_empty() {
            return "No projects found matching filter.".to_string();
        }

        let issues_client = self.get_issues_client().await;
        let project_count = projects.len();

        // Fetch issues in parallel (bounded concurrency) instead of serial N+1
        let futs: Vec<_> = projects
            .into_iter()
            .map(|proj| {
                let client = issues_client.clone();
                let sf = status_filter.clone();
                let proj_id = proj.id;
                let proj_name = proj.name;
                async move {
                    let res = client.list_issues(&proj_id, None).await;
                    (proj_name, sf, res)
                }
            })
            .collect();

        let results: Vec<_> = stream_util::iter(futs)
            .buffer_unordered(MCP_BULK_CONCURRENCY)
            .collect()
            .await;

        let mut output = format!("Issues Summary for {} project(s):\n\n", project_count);
        let mut grand_total = 0usize;
        let mut grand_open = 0usize;

        for (proj_name, sf, res) in &results {
            match res {
                Ok(issues) => {
                    let filtered: Vec<_> = if let Some(sf) = sf {
                        issues
                            .iter()
                            .filter(|i| i.status.to_lowercase() == sf.to_lowercase())
                            .collect()
                    } else {
                        issues.iter().collect()
                    };
                    let total = filtered.len();
                    let open = filtered
                        .iter()
                        .filter(|i| i.status.to_lowercase() == "open")
                        .count();
                    grand_total += total;
                    grand_open += open;
                    if total > 0 {
                        output.push_str(&format!(
                            "* {} - {} issues ({} open)\n",
                            proj_name, total, open
                        ));
                    }
                }
                Err(_) => {
                    output.push_str(&format!("* {} - (access denied)\n", proj_name));
                }
            }
        }

        output.push_str(&format!(
            "\nTotal: {} issues across {} projects ({} open)",
            grand_total, project_count, grand_open
        ));
        output
    }
}