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
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2025 Dmytro Yemelianov

//! TUI Dashboard — k9s-style resource browser for APS
//!
//! Provides a keyboard-driven terminal interface for browsing APS resources:
//! - Buckets + Objects (OSS)
//! - Hubs > Projects > Folders > Items (Data Management)
//! - Issues + RFIs + Assets + Submittals + Checklists (ACC)
//! - Engines, Activities, Work Items, AppBundles (Design Automation)
//! - Manifests + Derivatives (Model Derivative)
//! - Webhooks
//! - Photoscenes (Reality Capture)

mod fetch;
mod keys;
mod render;
mod util;

use std::collections::{HashMap, VecDeque};
use std::io;
use std::sync::Arc;
use std::time::{Duration, Instant};

use anyhow::Result;
use crossterm::{
    event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{
    Frame, Terminal,
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Cell, Clear, Paragraph, Row, Table, TableState, Wrap},
};
use tokio::sync::mpsc;

use raps_acc::{AccClient, IssuesClient, Rfi, RfiClient};
use raps_da::DesignAutomationClient;
use raps_derivative::DerivativeClient;
use raps_dm::DataManagementClient;
use raps_kernel::auth::AuthClient;
use raps_kernel::config::Config;
use raps_kernel::http::HttpClientConfig;
use raps_oss::OssClient;
use raps_reality::RealityCaptureClient;
use raps_webhooks::WebhooksClient;

// ============================================================================
// Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Eq)]
enum InputMode {
    Normal,
    Filter(String),
    Command(String),
    Confirm(String),
}

/// Actions that require special handling in the event loop (e.g. leaving TUI).
#[derive(Debug)]
enum PendingAction {
    Login,
    Logout,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ResourceTab {
    Buckets,
    DataManagement,
    Issues,
    DesignAutomation,
    ModelDerivative,
    Webhooks,
    RealityCapture,
}

impl ResourceTab {
    const ALL: [ResourceTab; 7] = [
        ResourceTab::Buckets,
        ResourceTab::DataManagement,
        ResourceTab::Issues,
        ResourceTab::DesignAutomation,
        ResourceTab::ModelDerivative,
        ResourceTab::Webhooks,
        ResourceTab::RealityCapture,
    ];

    fn index(self) -> usize {
        match self {
            ResourceTab::Buckets => 0,
            ResourceTab::DataManagement => 1,
            ResourceTab::Issues => 2,
            ResourceTab::DesignAutomation => 3,
            ResourceTab::ModelDerivative => 4,
            ResourceTab::Webhooks => 5,
            ResourceTab::RealityCapture => 6,
        }
    }

    fn label(self) -> &'static str {
        match self {
            ResourceTab::Buckets => "F1 Buckets",
            ResourceTab::DataManagement => "F2 Data Mgmt",
            ResourceTab::Issues => "F3 ACC",
            ResourceTab::DesignAutomation => "F4 Design Auto",
            ResourceTab::ModelDerivative => "F5 Derivative",
            ResourceTab::Webhooks => "F6 Webhooks",
            ResourceTab::RealityCapture => "F7 Reality",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum ViewKind {
    // Buckets tab (F1)
    BucketList,
    BucketDetail {
        bucket_key: String,
    },
    ObjectList {
        bucket_key: String,
    },
    ObjectDetail {
        bucket_key: String,
        object_key: String,
    },
    // Data Management tab (F2)
    HubList,
    ProjectList {
        hub_id: String,
    },
    FolderList {
        project_id: String,
        folder_id: String,
    },
    ItemDetail {
        project_id: String,
        item_id: String,
    },
    // ACC tab (F3) — Issues, RFIs, Assets, Submittals, Checklists
    IssueList {
        project_id: String,
    },
    IssueDetail {
        project_id: String,
        issue_id: String,
    },
    IssueCommentList {
        project_id: String,
        issue_id: String,
    },
    IssueAttachmentList {
        project_id: String,
        issue_id: String,
    },
    IssueTypeList {
        project_id: String,
    },
    RfiList {
        project_id: String,
    },
    RfiDetail {
        project_id: String,
        rfi_id: String,
    },
    AssetList {
        project_id: String,
    },
    AssetDetail {
        project_id: String,
        asset_id: String,
    },
    SubmittalList {
        project_id: String,
    },
    SubmittalDetail {
        project_id: String,
        submittal_id: String,
    },
    ChecklistList {
        project_id: String,
    },
    ChecklistDetail {
        project_id: String,
        checklist_id: String,
    },
    // DA tab (F4)
    EngineList,
    ActivityList,
    WorkItemList,
    WorkItemDetail {
        id: String,
    },
    AppBundleList,
    // Model Derivative tab (F5)
    ManifestView {
        urn: String,
    },
    DerivativeList {
        urn: String,
    },
    DerivativeDetail {
        urn: String,
        deriv_urn: String,
        name: String,
    },
    // Webhooks tab (F6)
    WebhookList,
    WebhookDetail {
        system: String,
        event: String,
        hook_id: String,
    },
    // Reality Capture tab (F7)
    PhotosceneList,
    PhotosceneDetail {
        id: String,
    },
}

impl ViewKind {
    fn title(&self) -> String {
        match self {
            ViewKind::BucketList => "Buckets".into(),
            ViewKind::BucketDetail { bucket_key } => format!("Bucket: {bucket_key}"),
            ViewKind::ObjectList { bucket_key } => format!("Objects in {bucket_key}"),
            ViewKind::ObjectDetail { object_key, .. } => format!("Object: {object_key}"),
            ViewKind::HubList => "Hubs".into(),
            ViewKind::ProjectList { .. } => "Projects".into(),
            ViewKind::FolderList { .. } => "Folder Contents".into(),
            ViewKind::ItemDetail { .. } => "Item Detail".into(),
            ViewKind::IssueList { .. } => "Issues".into(),
            ViewKind::IssueDetail { .. } => "Issue Detail".into(),
            ViewKind::IssueCommentList { .. } => "Issue Comments".into(),
            ViewKind::IssueAttachmentList { .. } => "Issue Attachments".into(),
            ViewKind::IssueTypeList { .. } => "Issue Types".into(),
            ViewKind::RfiList { .. } => "RFIs".into(),
            ViewKind::RfiDetail { .. } => "RFI Detail".into(),
            ViewKind::AssetList { .. } => "Assets".into(),
            ViewKind::AssetDetail { .. } => "Asset Detail".into(),
            ViewKind::SubmittalList { .. } => "Submittals".into(),
            ViewKind::SubmittalDetail { .. } => "Submittal Detail".into(),
            ViewKind::ChecklistList { .. } => "Checklists".into(),
            ViewKind::ChecklistDetail { .. } => "Checklist Detail".into(),
            ViewKind::EngineList => "Engines".into(),
            ViewKind::ActivityList => "Activities".into(),
            ViewKind::WorkItemList => "Work Items".into(),
            ViewKind::WorkItemDetail { id } => format!("WorkItem: {id}"),
            ViewKind::AppBundleList => "AppBundles".into(),
            ViewKind::ManifestView { urn } => {
                let short = if urn.len() > 20 { &urn[..20] } else { urn };
                format!("Manifest: {short}")
            }
            ViewKind::DerivativeList { .. } => "Derivatives".into(),
            ViewKind::DerivativeDetail { name, .. } => format!("Derivative: {name}"),
            ViewKind::WebhookList => "Webhooks".into(),
            ViewKind::WebhookDetail { hook_id, .. } => format!("Webhook: {hook_id}"),
            ViewKind::PhotosceneList => "Photoscenes".into(),
            ViewKind::PhotosceneDetail { id } => format!("Photoscene: {id}"),
        }
    }
}

/// Holds table data for each view kind
#[derive(Debug, Clone)]
enum ResourceData {
    Buckets(Vec<BucketRow>),
    Objects(Vec<ObjectRow>),
    BucketDetail(Vec<DetailField>),
    ObjectDetail(Vec<DetailField>),
    Hubs(Vec<HubRow>),
    Projects(Vec<ProjectRow>),
    FolderContents(Vec<FolderContentRow>),
    ItemDetail(Vec<DetailField>),
    Issues(Vec<IssueRow>),
    IssueDetail(Vec<DetailField>),
    IssueComments(Vec<IssueCommentRow>),
    IssueAttachments(Vec<IssueAttachmentRow>),
    IssueTypes(Vec<IssueTypeRow>),
    Rfis(Vec<RfiRow>),
    RfiDetail(Vec<DetailField>),
    Assets(Vec<AssetRow>),
    AssetDetail(Vec<DetailField>),
    Submittals(Vec<SubmittalRow>),
    SubmittalDetail(Vec<DetailField>),
    Checklists(Vec<ChecklistRow>),
    ChecklistDetail(Vec<DetailField>),
    Engines(Vec<EngineRow>),
    Activities(Vec<ActivityRow>),
    WorkItems(Vec<WorkItemRow>),
    WorkItemDetail(Vec<DetailField>),
    AppBundles(Vec<AppBundleRow>),
    Manifest(Vec<DetailField>),
    Derivatives(Vec<DerivativeRow>),
    DerivativeDetail(Vec<DetailField>),
    Webhooks(Vec<WebhookRow>),
    WebhookDetail(Vec<DetailField>),
    Photoscenes(Vec<PhotosceneRow>),
    PhotosceneDetail(Vec<DetailField>),
}

// --- Row structs ---

#[derive(Debug, Clone)]
struct BucketRow {
    key: String,
    policy: String,
    created: String,
}

#[derive(Debug, Clone)]
struct ObjectRow {
    key: String,
    size: String,
    sha1: String,
}

#[derive(Debug, Clone)]
struct HubRow {
    name: String,
    id: String,
    region: String,
}

#[derive(Debug, Clone)]
struct ProjectRow {
    name: String,
    id: String,
}

#[derive(Debug, Clone)]
struct FolderContentRow {
    name: String,
    content_type: String,
    id: String,
    modified: String,
}

#[derive(Debug, Clone)]
struct IssueRow {
    title: String,
    status: String,
    assigned_to: String,
    created_at: String,
    id: String,
}

#[derive(Debug, Clone)]
struct RfiRow {
    title: String,
    status: String,
    priority: String,
    created_at: String,
    id: String,
}

#[derive(Debug, Clone)]
struct AssetRow {
    id: String,
    client_asset_id: String,
    description: String,
    status: String,
}

#[derive(Debug, Clone)]
struct SubmittalRow {
    id: String,
    title: String,
    number: String,
    status: String,
    due_date: String,
}

#[derive(Debug, Clone)]
struct ChecklistRow {
    id: String,
    title: String,
    status: String,
    location: String,
    due_date: String,
}

#[derive(Debug, Clone)]
struct IssueCommentRow {
    id: String,
    body: String,
    created_by: String,
    created_at: String,
}

#[derive(Debug, Clone)]
struct IssueAttachmentRow {
    id: String,
    name: String,
    urn: String,
}

#[derive(Debug, Clone)]
struct IssueTypeRow {
    id: String,
    title: String,
    is_active: String,
}

#[derive(Debug, Clone)]
struct EngineRow {
    id: String,
    description: String,
}

#[derive(Debug, Clone)]
struct ActivityRow {
    id: String,
}

#[derive(Debug, Clone)]
struct WorkItemRow {
    id: String,
    status: String,
    progress: String,
}

#[derive(Debug, Clone)]
struct AppBundleRow {
    id: String,
}

#[derive(Debug, Clone)]
struct DerivativeRow {
    name: String,
    output_type: String,
    role: String,
    mime: String,
    size: String,
    urn: String,
}

#[derive(Debug, Clone)]
struct WebhookRow {
    hook_id: String,
    event: String,
    callback_url: String,
    status: String,
    system: String,
    created: String,
}

#[derive(Debug, Clone)]
struct PhotosceneRow {
    id: String,
    name: String,
    scene_type: String,
    format: String,
    status: String,
}

#[derive(Debug, Clone)]
struct DetailField {
    label: String,
    value: String,
}

/// Messages from background fetch tasks
enum BackgroundMsg {
    DataReady(ViewKind, ResourceData),
    Error(String),
    Log(String),
}

/// Cache TTL — cached data older than this is considered stale and refetched.
const CACHE_TTL: Duration = Duration::from_secs(300); // 5 minutes

/// Minimum interval between API calls to avoid overload.
const API_THROTTLE: Duration = Duration::from_secs(2);

/// How long a status message stays visible before fading to shortcut hints.
const STATUS_MSG_TTL: Duration = Duration::from_secs(5);

/// A cached view: data + metadata for restoring state when navigating back.
#[derive(Clone)]
struct CacheEntry {
    data: ResourceData,
    fetched_at: Instant,
    /// Saved table selection so we restore cursor position on back-navigation.
    table_selection: Option<usize>,
}

impl CacheEntry {
    fn is_fresh(&self) -> bool {
        self.fetched_at.elapsed() < CACHE_TTL
    }
}

/// All API clients bundled
#[derive(Clone)]
struct Clients {
    auth: AuthClient,
    oss: OssClient,
    dm: DataManagementClient,
    issues: IssuesClient,
    rfi: RfiClient,
    da: DesignAutomationClient,
    acc: AccClient,
    derivative: DerivativeClient,
    webhooks: WebhooksClient,
    reality: RealityCaptureClient,
}

/// Application state
struct App {
    tab: ResourceTab,
    nav_stacks: [Vec<ViewKind>; 7],
    table_state: TableState,
    /// Currently displayed data for the active view (set from cache or fresh fetch).
    data: Option<ResourceData>,
    loading: bool,
    input_mode: InputMode,
    filter_text: String,
    error_msg: Option<String>,
    status_msg: String,
    /// When the status_msg was last set — shown for STATUS_MSG_TTL then fades to hints
    status_at: Option<Instant>,
    last_refresh: Option<Instant>,
    project_context: Option<(String, String)>,
    hub_context: Option<String>,
    quit: bool,
    /// Per-view data cache: avoids refetching on tab switch / back-navigation.
    cache: HashMap<ViewKind, CacheEntry>,
    /// API call counter for usage display
    api_calls: u32,
    /// Log messages ring buffer (newest last, max 50)
    logs: VecDeque<String>,
    /// Last time a fetch was dispatched (throttling)
    last_fetch: Option<Instant>,
    /// Whether 3-legged auth is active
    logged_in: bool,
    /// Action that needs event-loop-level handling (e.g. leaving TUI for login)
    pending_action: Option<PendingAction>,
    /// Frame counter for spinner animation
    tick: u64,
}

impl App {
    fn new() -> Self {
        Self {
            tab: ResourceTab::Buckets,
            nav_stacks: [
                vec![ViewKind::BucketList],     // Tab 0: Buckets
                vec![ViewKind::HubList],        // Tab 1: Data Mgmt
                vec![ViewKind::HubList],        // Tab 2: ACC (navigate Hub > Project > Issues)
                vec![ViewKind::EngineList],     // Tab 3: Design Automation
                vec![],                         // Tab 4: Model Derivative (empty until :urn)
                vec![ViewKind::WebhookList],    // Tab 5: Webhooks
                vec![ViewKind::PhotosceneList], // Tab 6: Reality Capture
            ],
            table_state: TableState::default(),
            data: None,
            loading: false,
            input_mode: InputMode::Normal,
            filter_text: String::new(),
            error_msg: None,
            status_msg: String::new(),
            status_at: None,
            last_refresh: None,
            project_context: None,
            hub_context: None,
            quit: false,
            cache: HashMap::new(),
            api_calls: 0,
            logs: VecDeque::new(),
            last_fetch: None,
            logged_in: false,
            pending_action: None,
            tick: 0,
        }
    }

    fn current_view(&self) -> &ViewKind {
        let stack = &self.nav_stacks[self.tab.index()];
        stack.last().expect("nav stack should never be empty")
    }

    /// Returns true if the current tab's nav stack is non-empty.
    fn has_current_view(&self) -> bool {
        !self.nav_stacks[self.tab.index()].is_empty()
    }

    /// Save current table selection into the cache entry for the current view.
    fn save_selection_to_cache(&mut self) {
        if !self.has_current_view() {
            return;
        }
        let view = self.current_view().clone();
        if let Some(entry) = self.cache.get_mut(&view) {
            entry.table_selection = self.table_state.selected();
        }
    }

    fn push_view(&mut self, view: ViewKind) {
        // Save cursor position for the view we're leaving
        self.save_selection_to_cache();
        self.nav_stacks[self.tab.index()].push(view);
        self.table_state.select(Some(0));
        self.data = None;
        self.error_msg = None;
    }

    fn pop_view(&mut self) -> bool {
        let stack = &mut self.nav_stacks[self.tab.index()];
        if stack.len() > 1 {
            stack.pop();
            self.error_msg = None;
            // Restore from cache if available
            let view = stack
                .last()
                .expect("navigation stack is never empty")
                .clone();
            if let Some(entry) = self.cache.get(&view) {
                self.data = Some(entry.data.clone());
                self.last_refresh = Some(entry.fetched_at);
                self.table_state.select(entry.table_selection.or(Some(0)));
                let count = self.row_count();
                self.status_msg = format!("{count} items (cached)");
            } else {
                self.data = None;
                self.table_state.select(Some(0));
            }
            true
        } else {
            false
        }
    }

    fn set_status(&mut self, msg: impl Into<String>) {
        self.status_msg = msg.into();
        self.status_at = Some(Instant::now());
    }

    /// Whether the status message is still fresh (within TTL).
    fn status_is_active(&self) -> bool {
        self.status_at.is_some_and(|t| t.elapsed() < STATUS_MSG_TTL)
    }

    fn push_log(&mut self, msg: String) {
        if self.logs.len() >= 50 {
            self.logs.pop_front();
        }
        self.logs.push_back(msg);
    }

    fn breadcrumb(&self) -> String {
        let stack = &self.nav_stacks[self.tab.index()];
        if stack.is_empty() {
            return "Use :urn <base64> to set context".into();
        }
        stack
            .iter()
            .map(|v| v.title())
            .collect::<Vec<_>>()
            .join(" > ")
    }

    fn row_count(&self) -> usize {
        let data = match &self.data {
            Some(d) => d,
            None => return 0,
        };
        let filter = self.filter_text.to_lowercase();
        match data {
            ResourceData::Buckets(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.key.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Objects(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.key.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Hubs(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.name.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Projects(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.name.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::FolderContents(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.name.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Issues(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.title.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Rfis(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.title.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Assets(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| {
                            r.id.to_lowercase().contains(&filter)
                                || r.description.to_lowercase().contains(&filter)
                        })
                        .count()
                }
            }
            ResourceData::Submittals(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.title.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Checklists(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.title.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::IssueComments(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.body.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Engines(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.id.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Activities(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.id.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::WorkItems(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.id.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::AppBundles(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.id.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Derivatives(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.name.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::Webhooks(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| {
                            r.event.to_lowercase().contains(&filter)
                                || r.callback_url.to_lowercase().contains(&filter)
                        })
                        .count()
                }
            }
            ResourceData::Photoscenes(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.name.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::IssueAttachments(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.name.to_lowercase().contains(&filter))
                        .count()
                }
            }
            ResourceData::IssueTypes(v) => {
                if filter.is_empty() {
                    v.len()
                } else {
                    v.iter()
                        .filter(|r| r.title.to_lowercase().contains(&filter))
                        .count()
                }
            }
            // Detail views
            ResourceData::BucketDetail(v)
            | ResourceData::ObjectDetail(v)
            | ResourceData::ItemDetail(v)
            | ResourceData::IssueDetail(v)
            | ResourceData::RfiDetail(v)
            | ResourceData::AssetDetail(v)
            | ResourceData::SubmittalDetail(v)
            | ResourceData::ChecklistDetail(v)
            | ResourceData::WorkItemDetail(v)
            | ResourceData::Manifest(v)
            | ResourceData::DerivativeDetail(v)
            | ResourceData::WebhookDetail(v)
            | ResourceData::PhotosceneDetail(v) => v.len(),
        }
    }
}

// ============================================================================
// Entry point
// ============================================================================

pub async fn run_dashboard(config: Config, http_config: HttpClientConfig) -> Result<()> {
    let auth = AuthClient::new_with_http_config(config.clone(), http_config.clone());
    let clients = Arc::new(Clients {
        auth: auth.clone(),
        oss: OssClient::new_with_http_config(config.clone(), auth.clone(), http_config.clone()),
        dm: DataManagementClient::new_with_http_config(
            config.clone(),
            auth.clone(),
            http_config.clone(),
        ),
        issues: IssuesClient::new_with_http_config(
            config.clone(),
            auth.clone(),
            http_config.clone(),
        ),
        rfi: RfiClient::new_with_http_config(config.clone(), auth.clone(), http_config.clone()),
        da: DesignAutomationClient::new_with_http_config(
            config.clone(),
            auth.clone(),
            http_config.clone(),
        ),
        acc: AccClient::new_with_http_config(config.clone(), auth.clone(), http_config.clone()),
        derivative: DerivativeClient::new_with_http_config(
            config.clone(),
            auth.clone(),
            http_config.clone(),
        ),
        webhooks: WebhooksClient::new_with_http_config(
            config.clone(),
            auth.clone(),
            http_config.clone(),
        ),
        reality: RealityCaptureClient::new_with_http_config(config, auth, http_config),
    });

    // Guard restores terminal on both normal exit and panic
    struct TerminalGuard {
        active: bool,
    }
    impl Drop for TerminalGuard {
        fn drop(&mut self) {
            if self.active {
                let _ = disable_raw_mode();
                let _ = execute!(io::stdout(), LeaveAlternateScreen);
            }
        }
    }

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let mut guard = TerminalGuard { active: true };
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let result = run_event_loop(&mut terminal, clients).await;

    // Normal cleanup — deactivate guard so it doesn't double-restore
    guard.active = false;
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    result
}

async fn run_event_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    clients: Arc<Clients>,
) -> Result<()> {
    let mut app = App::new();
    let (tx, mut rx) = mpsc::unbounded_channel::<BackgroundMsg>();

    // Check login state on startup
    app.logged_in = clients.auth.is_logged_in().await;
    if !app.logged_in {
        app.push_log("Not logged in. 2-legged auth (client credentials) will be used.".into());
        app.push_log("For 3-legged features, run: raps auth login".into());
    } else {
        app.push_log("Logged in (3-legged auth active)".into());
    }

    fetch::load_view(&mut app, &clients, &tx, false);

    loop {
        app.tick = app.tick.wrapping_add(1);
        terminal.draw(|f| render::ui(f, &mut app))?;

        if app.quit {
            break;
        }

        // Drain background messages first (non-blocking)
        while let Ok(msg) = rx.try_recv() {
            fetch::handle_bg_msg(&mut app, msg);
        }

        // Poll for key events with a short timeout
        if event::poll(Duration::from_millis(50))?
            && let Event::Key(key) = event::read()?
            && key.kind == event::KeyEventKind::Press
        {
            keys::handle_key(&mut app, key, &clients, &tx);
        }

        // Handle pending actions that require event-loop-level control
        if let Some(action) = app.pending_action.take() {
            match action {
                PendingAction::Login => {
                    // Leave TUI so the browser can open and user sees progress
                    disable_raw_mode()?;
                    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
                    terminal.show_cursor()?;

                    let scopes: &[&str] = &[
                        "data:read",
                        "data:write",
                        "data:create",
                        "data:search",
                        "bucket:create",
                        "bucket:read",
                        "account:read",
                        "user:read",
                        "viewables:read",
                    ];
                    match clients.auth.login(scopes).await {
                        Ok(_) => {
                            app.logged_in = true;
                            app.cache.clear();
                            app.push_log("Login successful (3-legged auth)".into());
                            app.set_status("Logged in — press r to refresh");
                        }
                        Err(e) => {
                            app.push_log(format!("Login failed: {e:#}"));
                            app.error_msg = Some(format!("Login failed: {e:#}"));
                        }
                    }

                    // Re-enter TUI
                    enable_raw_mode()?;
                    execute!(terminal.backend_mut(), EnterAlternateScreen)?;
                    terminal.hide_cursor()?;
                    terminal.clear()?;

                    // Reload current view with new auth
                    fetch::load_view(&mut app, &clients, &tx, true);
                }
                PendingAction::Logout => {
                    match clients.auth.logout().await {
                        Ok(()) => {
                            app.logged_in = false;
                            app.cache.clear();
                            app.push_log("Logged out".into());
                            app.set_status("Logged out (2-legged auth)");
                            // Reload current view with 2-leg auth
                            fetch::load_view(&mut app, &clients, &tx, true);
                        }
                        Err(e) => {
                            app.push_log(format!("Logout failed: {e:#}"));
                            app.error_msg = Some(format!("Logout failed: {e:#}"));
                        }
                    }
                }
            }
        }
    }

    Ok(())
}