sway-groups-core 0.1.0

Core library for sway-groups: DB entities, services, sway/waybar IPC.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
//! Workspace management service.

use crate::db::entities::{
    group, hidden_workspace, output, pending_workspace_event, setting, workspace, workspace_group,
};
use crate::db::entities::{
    FocusHistoryEntity, GroupEntity, GroupStateEntity, HiddenWorkspaceEntity, OutputEntity,
    PendingWorkspaceEventEntity, WorkspaceEntity, WorkspaceGroupEntity,
};
use crate::db::DatabaseManager;
use crate::error::{Error, Result};
use crate::sway::SwayIpcClient;
use sea_orm::{
    ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, ModelTrait, QueryFilter, Set,
};
use tracing::info;

/// Workspace information for display.
#[derive(Debug, Clone)]
pub struct WorkspaceInfo {
    pub id: i32,
    pub name: String,
    pub number: Option<i32>,
    pub output: Option<String>,
    pub is_global: bool,
    pub groups: Vec<String>,
}

/// Service for workspace operations.
pub struct WorkspaceService {
    db: DatabaseManager,
    ipc_client: SwayIpcClient,
    default_group: String,
    default_workspace: String,
}

impl WorkspaceService {
    /// Create a new workspace service.
    pub fn new(db: DatabaseManager, ipc_client: SwayIpcClient) -> Self {
        Self {
            db,
            ipc_client,
            default_group: "0".to_string(),
            default_workspace: "0".to_string(),
        }
    }

    pub fn with_config(db: DatabaseManager, ipc_client: SwayIpcClient, config: &sway_groups_config::SwaygConfig) -> Self {
        Self {
            db,
            ipc_client,
            default_group: config.defaults.default_group.clone(),
            default_workspace: config.defaults.default_workspace.clone(),
        }
    }

    pub fn default_group(&self) -> &str {
        &self.default_group
    }

    /// List workspace names visible in the active group on an output.
    pub async fn list_visible_workspaces(&self, output_name: &str) -> Result<Vec<String>> {
        let active_group = OutputEntity::find_by_name(output_name)
            .one(self.db.conn())
            .await?
            .map(|o| o.active_group)
            .unwrap_or(None);

        let sway_workspaces = self.ipc_client.get_workspaces()?;
        let sway_names: Vec<String> = sway_workspaces
            .iter()
            .filter(|w| w.output == output_name)
            .map(|w| w.name.clone())
            .collect();

        crate::db::queries::compute_visible_workspaces(
            self.db.conn(),
            &sway_names,
            active_group.as_deref(),
        )
        .await
    }

    /// List all workspaces with their group memberships. Uses 3 batch queries instead of N+1.
    pub async fn list_workspaces(
        &self,
        output_filter: Option<&str>,
        group_filter: Option<&str>,
    ) -> Result<Vec<WorkspaceInfo>> {
        let all_workspaces = WorkspaceEntity::find().all(self.db.conn()).await?;

        let workspaces: Vec<_> = all_workspaces
            .into_iter()
            .filter(|ws| {
                output_filter.is_none() || ws.output.as_deref() == output_filter
            })
            .collect();

        if workspaces.is_empty() {
            return Ok(Vec::new());
        }

        let ws_ids: Vec<i32> = workspaces.iter().map(|ws| ws.id).collect();
        let memberships_map =
            crate::db::queries::load_memberships_by_workspace_ids(self.db.conn(), &ws_ids).await?;

        let group_ids: Vec<i32> = memberships_map
            .values()
            .flat_map(|ms| ms.iter().map(|m| m.group_id))
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();
        let group_name_map =
            crate::db::queries::load_group_names_by_ids(self.db.conn(), &group_ids).await?;

        let mut result = Vec::new();

        for ws in workspaces {
            let memberships = memberships_map.get(&ws.id).map(|v| v.as_slice()).unwrap_or(&[]);
            let group_names: Vec<String> = memberships
                .iter()
                .filter_map(|m| group_name_map.get(&m.group_id).cloned())
                .collect();

            // Filter by group if specified
            if let Some(group_name) = group_filter
                && !group_names.iter().any(|g| g == group_name) {
                    continue;
                }

            result.push(WorkspaceInfo {
                id: ws.id,
                name: ws.name,
                number: ws.number,
                output: ws.output,
                is_global: ws.is_global,
                groups: group_names,
            });
        }

        Ok(result)
    }

    /// Get a workspace by name.
    pub async fn get_workspace(&self, name: &str) -> Result<Option<workspace::Model>> {
        Ok(WorkspaceEntity::find_by_name(name)
            .one(self.db.conn())
            .await?)
    }

    /// Ensure a workspace exists in DB, creating it in sway if necessary.
    async fn ensure_workspace(&self, workspace_name: &str) -> Result<workspace::Model> {
        if let Some(ws) = WorkspaceEntity::find_by_name(workspace_name)
            .one(self.db.conn())
            .await?
        {
            return Ok(ws);
        }

        // Not in DB — check sway
        let sway_workspaces = self.ipc_client.get_workspaces()?;
        let sway_ws = sway_workspaces
            .iter()
            .find(|w| w.name == workspace_name || w.num.map(|n| n.to_string()) == Some(workspace_name.to_string()));

        match sway_ws {
            Some(ws) => {
                let number = ws.num.map(|n| n as i32);
                let now = chrono::Utc::now().naive_utc();

                let active = workspace::ActiveModel {
                    name: Set(ws.name.clone()),
                    number: Set(number),
                    output: Set(Some(ws.output.clone())),
                    is_global: Set(false),
                    created_at: Set(Some(now)),
                    updated_at: Set(Some(now)),
                    ..Default::default()
                };
                Ok(active.insert(self.db.conn()).await?)
            }
            None => {
                // Not in sway either — create it via swaymsg
                info!("Workspace '{}' not found in sway, creating it", workspace_name);
                self.ipc_client.run_command(&format!("workspace {}", workspace_name))?;

                let sway_workspaces = self.ipc_client.get_workspaces()?;
                let sway_ws = sway_workspaces
                    .iter()
                    .find(|w| w.name == workspace_name);

                match sway_ws {
                    Some(ws) => {
                        let number = ws.num.map(|n| n as i32);
                        let now = chrono::Utc::now().naive_utc();

                        let active = workspace::ActiveModel {
                            name: Set(ws.name.clone()),
                            number: Set(number),
                            output: Set(Some(ws.output.clone())),
                            is_global: Set(false),
                            created_at: Set(Some(now)),
                            updated_at: Set(Some(now)),
                            ..Default::default()
                        };
                        Ok(active.insert(self.db.conn()).await?)
                    }
                    None => {
                        Err(Error::WorkspaceNotFound(workspace_name.to_string()))
                    }
                }
            }
        }
    }

    /// Add a workspace to a group.
    pub async fn add_to_group(&self, workspace_name: &str, group_name: &str) -> Result<()> {
        let workspace = self.ensure_workspace(workspace_name).await?;

        // Get group
        let group = GroupEntity::find_by_name(group_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::GroupNotFound(group_name.to_string()))?;

        // Check if membership already exists
        let existing = WorkspaceGroupEntity::find_membership(workspace.id, group.id)
            .one(self.db.conn())
            .await?;

        if existing.is_some() {
            return Err(Error::InvalidArgs(format!(
                "Workspace '{}' is already in group '{}'",
                workspace_name, group_name
            )));
        }

        // Create membership
        let now = chrono::Utc::now().naive_utc();
        let membership = workspace_group::ActiveModel {
            workspace_id: Set(workspace.id),
            group_id: Set(group.id),
            created_at: Set(Some(now)),
            ..Default::default()
        };
        membership.insert(self.db.conn()).await?;

        info!(
            "Added workspace '{}' to group '{}'",
            workspace_name, group_name
        );
        Ok(())
    }

    /// Remove a workspace from a group.
    pub async fn remove_from_group(
        &self,
        workspace_name: &str,
        group_name: &str,
    ) -> Result<()> {
        let workspace = WorkspaceEntity::find_by_name(workspace_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::WorkspaceNotFound(workspace_name.to_string()))?;

        let group = GroupEntity::find_by_name(group_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::GroupNotFound(group_name.to_string()))?;

        // Find and delete membership
        let membership = WorkspaceGroupEntity::find_membership(workspace.id, group.id)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| {
                Error::InvalidArgs(format!(
                    "Workspace '{}' is not in group '{}'",
                    workspace_name, group_name
                ))
            })?;

        membership.delete(self.db.conn()).await?;

        // Also clear any hidden flag for this (ws, group) pair — when the ws is
        // re-added later it should default to visible.
        if let Some(row) = HiddenWorkspaceEntity::find_entry(workspace.id, group.id)
            .one(self.db.conn())
            .await?
        {
            row.delete(self.db.conn()).await?;
        }

        info!(
            "Removed workspace '{}' from group '{}'",
            workspace_name, group_name
        );
        Ok(())
    }

    /// Move a workspace to specific groups, removing it from all others.
    pub async fn move_to_groups(
        &self,
        workspace_name: &str,
        group_names: &[&str],
    ) -> Result<()> {
        let workspace = match WorkspaceEntity::find_by_name(workspace_name)
            .one(self.db.conn())
            .await?
        {
            Some(ws) => ws,
            None => {
                let sway_workspaces = self.ipc_client.get_workspaces()?;
                let sway_ws = sway_workspaces
                    .iter()
                    .find(|w| w.name == workspace_name || w.num.map(|n| n.to_string()) == Some(workspace_name.to_string()));

                match sway_ws {
                    Some(ws) => {
                        let number = ws.num.map(|n| n as i32);
                        let now = chrono::Utc::now().naive_utc();

                        let active = workspace::ActiveModel {
                            name: Set(ws.name.clone()),
                            number: Set(number),
                            output: Set(Some(ws.output.clone())),
                            is_global: Set(false),
                            created_at: Set(Some(now)),
                            updated_at: Set(Some(now)),
                            ..Default::default()
                        };
                        active.insert(self.db.conn()).await?
                    }
                    None => {
                        return Err(Error::WorkspaceNotFound(workspace_name.to_string()));
                    }
                }
            }
        };

        let memberships = WorkspaceGroupEntity::find_by_workspace(workspace.id)
            .all(self.db.conn())
            .await?;

        for m in memberships {
            m.delete(self.db.conn()).await?;
        }

        let mut new_group_ids: Vec<i32> = Vec::new();
        for group_name in group_names {
            let group = match GroupEntity::find_by_name(*group_name)
                .one(self.db.conn())
                .await?
            {
                Some(g) => g,
                None => {
                    let now = chrono::Utc::now().naive_utc();
                    let active = group::ActiveModel {
                        name: Set(group_name.to_string()),
                        created_at: Set(Some(now)),
                        updated_at: Set(Some(now)),
                        ..Default::default()
                    };
                    let model = active.insert(self.db.conn()).await?;
                    info!("Auto-created group: {}", group_name);
                    model
                }
            };

            let now = chrono::Utc::now().naive_utc();
            let membership = workspace_group::ActiveModel {
                workspace_id: Set(workspace.id),
                group_id: Set(group.id),
                created_at: Set(Some(now)),
                ..Default::default()
            };
            membership.insert(self.db.conn()).await?;
            new_group_ids.push(group.id);
        }

        // Drop hidden entries for groups the workspace is no longer in.
        // (Global workspaces keep their hidden entries for non-member groups.)
        if !workspace.is_global {
            HiddenWorkspaceEntity::delete_many()
                .filter(hidden_workspace::Column::WorkspaceId.eq(workspace.id))
                .filter(hidden_workspace::Column::GroupId.is_not_in(new_group_ids))
                .exec(self.db.conn())
                .await?;
        }

        info!(
            "Moved workspace '{}' to groups: {}",
            workspace_name,
            group_names.join(", ")
        );
        Ok(())
    }

    /// Get groups for a workspace.
    pub async fn get_groups_for_workspace(&self, workspace_name: &str) -> Result<Vec<String>> {
        let workspace = WorkspaceEntity::find_by_name(workspace_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::WorkspaceNotFound(workspace_name.to_string()))?;

        let memberships = WorkspaceGroupEntity::find_by_workspace(workspace.id)
            .all(self.db.conn())
            .await?;

        let group_ids: Vec<i32> = memberships.iter().map(|m| m.group_id).collect();
        let group_name_map =
            crate::db::queries::load_group_names_by_ids(self.db.conn(), &group_ids).await?;

        Ok(group_name_map.into_values().collect())
    }

    pub async fn is_global(&self, workspace_name: &str) -> Result<bool> {
        Ok(WorkspaceEntity::find_by_name(workspace_name)
            .one(self.db.conn())
            .await?
            .map(|e| e.is_global)
            .unwrap_or(false))
    }

    // -----------------------------------------------------------------------
    // Hidden workspaces (per-group) and show_hidden_workspaces setting
    // -----------------------------------------------------------------------

    /// Whether a workspace is marked as hidden in the given group.
    pub async fn is_hidden(&self, workspace_name: &str, group_name: &str) -> Result<bool> {
        let workspace = WorkspaceEntity::find_by_name(workspace_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::WorkspaceNotFound(workspace_name.to_string()))?;
        let group = GroupEntity::find_by_name(group_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::GroupNotFound(group_name.to_string()))?;
        let row = HiddenWorkspaceEntity::find_entry(workspace.id, group.id)
            .one(self.db.conn())
            .await?;
        Ok(row.is_some())
    }

    /// Mark/unmark a workspace as hidden in a specific group.
    ///
    /// Validation: a non-global workspace must be a member of the group; if
    /// not, returns `InvalidArgs` and logs the rejection. Global workspaces
    /// can be hidden in any group (they are implicitly in all groups).
    pub async fn set_hidden(
        &self,
        workspace_name: &str,
        group_name: &str,
        hidden: bool,
    ) -> Result<()> {
        let workspace = WorkspaceEntity::find_by_name(workspace_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::WorkspaceNotFound(workspace_name.to_string()))?;
        let group = GroupEntity::find_by_name(group_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::GroupNotFound(group_name.to_string()))?;

        if !workspace.is_global {
            let membership =
                WorkspaceGroupEntity::find_membership(workspace.id, group.id)
                    .one(self.db.conn())
                    .await?;
            if membership.is_none() {
                let msg = format!(
                    "Cannot hide: workspace '{}' is not a member of group '{}'",
                    workspace_name, group_name
                );
                tracing::warn!("{}", msg);
                return Err(Error::InvalidArgs(msg));
            }
        }

        if hidden {
            let existing = HiddenWorkspaceEntity::find_entry(workspace.id, group.id)
                .one(self.db.conn())
                .await?;
            if existing.is_none() {
                let row = hidden_workspace::ActiveModel {
                    workspace_id: Set(workspace.id),
                    group_id: Set(group.id),
                };
                row.insert(self.db.conn()).await?;
                info!(
                    "Marked workspace '{}' as hidden in group '{}'",
                    workspace_name, group_name
                );
            }
        } else if let Some(row) = HiddenWorkspaceEntity::find_entry(workspace.id, group.id)
            .one(self.db.conn())
            .await?
        {
            row.delete(self.db.conn()).await?;
            info!(
                "Unmarked workspace '{}' as hidden in group '{}'",
                workspace_name, group_name
            );
        }

        Ok(())
    }

    /// Remove all hidden entries for the given group.
    /// Returns the number of rows removed.
    pub async fn unhide_all_in_group(&self, group_name: &str) -> Result<u64> {
        let group = GroupEntity::find_by_name(group_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::GroupNotFound(group_name.to_string()))?;

        let res = HiddenWorkspaceEntity::delete_many()
            .filter(hidden_workspace::Column::GroupId.eq(group.id))
            .exec(self.db.conn())
            .await?;
        info!(
            "Unhid {} workspace(s) in group '{}'",
            res.rows_affected, group_name
        );
        Ok(res.rows_affected)
    }

    /// Read the global `show_hidden_workspaces` DB flag (default false).
    pub async fn get_show_hidden(&self) -> Result<bool> {
        crate::db::queries::get_bool_setting(
            self.db.conn(),
            setting::SHOW_HIDDEN_WORKSPACES,
            false,
        )
        .await
    }

    /// Set the global `show_hidden_workspaces` DB flag.
    pub async fn set_show_hidden(&self, value: bool) -> Result<()> {
        crate::db::queries::set_setting(
            self.db.conn(),
            setting::SHOW_HIDDEN_WORKSPACES,
            if value { "true" } else { "false" },
        )
        .await?;
        info!("Set {} = {}", setting::SHOW_HIDDEN_WORKSPACES, value);
        Ok(())
    }

    /// Set workspace global status.
    pub async fn set_global(&self, workspace_name: &str, global: bool) -> Result<()> {
        let workspace = WorkspaceEntity::find_by_name(workspace_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::WorkspaceNotFound(workspace_name.to_string()))?;

        let ws_id = workspace.id;
        let mut active = workspace.into_active_model();
        active.is_global = Set(global);
        active.updated_at = Set(Some(chrono::Utc::now().naive_utc()));
        active.update(self.db.conn()).await?;

        if global {
            let memberships = WorkspaceGroupEntity::find_by_workspace(ws_id)
                .all(self.db.conn())
                .await?;
            let count = memberships.len();

            let affected_group_ids: Vec<i32> = memberships.iter().map(|m| m.group_id).collect();

            for m in memberships {
                m.delete(self.db.conn()).await?;
            }
            if count > 0 {
                info!(
                    "Removed workspace '{}' from {} group(s) (now global)",
                    workspace_name,
                    count
                );
            }

            let sway_workspaces = self.ipc_client.get_workspaces()?;
            let sway_names: std::collections::HashSet<String> = sway_workspaces
                .iter()
                .map(|w| w.name.clone())
                .collect();

            let outputs = self.ipc_client.get_outputs()?;
            let active_group_ids: std::collections::HashSet<i32> = {
                let mut ids = std::collections::HashSet::new();
                for o in &outputs {
                    if let Some(out) = OutputEntity::find_by_name(&o.name)
                        .one(self.db.conn())
                        .await?
                        && let Some(ref ag) = out.active_group
                            && let Some(g) = GroupEntity::find_by_name(ag)
                                .one(self.db.conn())
                                .await?
                            {
                                ids.insert(g.id);
                            }
                }
                ids
            };

            for gid in &affected_group_ids {
                if active_group_ids.contains(gid) {
                    continue;
                }

                let group = match GroupEntity::find_by_id(*gid)
                    .one(self.db.conn())
                    .await?
                {
                    Some(g) => g,
                    None => continue,
                };

                let remaining_memberships = WorkspaceGroupEntity::find_by_group(group.id)
                    .all(self.db.conn())
                    .await?;

                let mut has_non_global_in_sway = false;
                for rm in &remaining_memberships {
                    if let Some(ws) = WorkspaceEntity::find_by_id(rm.workspace_id)
                        .one(self.db.conn())
                        .await?
                    {
                        if ws.name == self.default_workspace {
                            continue;
                        }
                        if !ws.is_global && sway_names.contains(&ws.name) {
                            has_non_global_in_sway = true;
                            break;
                        }
                    }
                }

                if !has_non_global_in_sway {
                    info!("Auto-removed empty group '{}' (workspace '{}' went global)", group.name, workspace_name);
                    let group_name = group.name.clone();
                    match group.delete(self.db.conn()).await {
                        Ok(_) => {},
                        Err(e) => info!("Failed to delete group '{}': {:?}", group_name, e),
                    }
                }
            }
        } else {
            let sway_workspaces = self.ipc_client.get_workspaces()?;
            let ws_output = sway_workspaces
                .iter()
                .find(|ws| ws.name == workspace_name)
                .map(|ws| ws.output.clone());

            if let Some(output_name) = ws_output {
                let active_group = OutputEntity::find_by_name(&output_name)
                    .one(self.db.conn())
                    .await?
                    .map(|o| o.active_group)
                    .unwrap_or(None);

                if let Some(ref ag) = active_group {
                    let group = GroupEntity::find_by_name(ag)
                        .one(self.db.conn())
                        .await?;

                    if let Some(group) = group {
                        let existing = WorkspaceGroupEntity::find_membership(ws_id, group.id)
                            .one(self.db.conn())
                            .await?;
                        if existing.is_none() {
                            let now = chrono::Utc::now().naive_utc();
                            let membership = workspace_group::ActiveModel {
                                workspace_id: Set(ws_id),
                            group_id: Set(group.id),
                            created_at: Set(Some(now)),
                            ..Default::default()
                        };
                        membership.insert(self.db.conn()).await?;
                        info!(
                            "Added global workspace '{}' back to group '{}'",
                            workspace_name, ag
                        );
                    }
                }
                }
            } else {
                info!(
                    "Workspace '{}' not found in sway, cannot reassign to group",
                    workspace_name
                );
            }
        }

        info!(
            "Set workspace '{}' global = {}",
            workspace_name, global
        );
        Ok(())
    }

    /// Rename a workspace. Returns whether it was a simple rename or a merge.
    pub async fn rename_workspace(&self, old_name: &str, new_name: &str) -> Result<bool> {
        let target_exists = WorkspaceEntity::find_by_name(new_name)
            .one(self.db.conn())
            .await?
            .is_some();

        if target_exists {
            self.merge_workspace(old_name, new_name).await?;
            let focus_cmd = format!("workspace \"{}\"", new_name);
            self.ipc_client.run_command(&focus_cmd)?;
            Ok(true)
        } else {
            self.simple_rename_workspace(old_name, new_name).await?;
            Ok(false)
        }
    }

    async fn simple_rename_workspace(&self, old_name: &str, new_name: &str) -> Result<()> {
        self.ipc_client.rename_workspace(old_name, new_name)?;

        let workspace = WorkspaceEntity::find_by_name(old_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::WorkspaceNotFound(old_name.to_string()))?;

        let mut active = workspace.into_active_model();
        active.name = Set(new_name.to_string());
        active.updated_at = Set(Some(chrono::Utc::now().naive_utc()));
        active.update(self.db.conn()).await?;

        info!("Renamed workspace '{}' to '{}'", old_name, new_name);
        Ok(())
    }

    async fn merge_workspace(&self, old_name: &str, new_name: &str) -> Result<()> {
        let old_ws = WorkspaceEntity::find_by_name(old_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::WorkspaceNotFound(old_name.to_string()))?;

        let new_ws = WorkspaceEntity::find_by_name(new_name)
            .one(self.db.conn())
            .await?
            .ok_or_else(|| Error::WorkspaceNotFound(new_name.to_string()))?;

        let old_memberships = WorkspaceGroupEntity::find_by_workspace(old_ws.id)
            .all(self.db.conn())
            .await?;

        let new_memberships = WorkspaceGroupEntity::find_by_workspace(new_ws.id)
            .all(self.db.conn())
            .await?;

        let now = chrono::Utc::now().naive_utc();

        for old_m in &old_memberships {
            let already = new_memberships.iter().any(|nm| nm.group_id == old_m.group_id);
            if !already {
                let membership = workspace_group::ActiveModel {
                    workspace_id: Set(new_ws.id),
                    group_id: Set(old_m.group_id),
                    created_at: Set(Some(now)),
                    ..Default::default()
                };
                membership.insert(self.db.conn()).await?;
            }
        }

        let tree_payload = self.ipc_client.get_tree()?;
        let tree: serde_json::Value = serde_json::from_slice(&tree_payload)?;

        fn collect_containers(node: &serde_json::Value, target_ws: &str, ids: &mut Vec<i64>) {
            let node_type = node.get("type").and_then(|t| t.as_str());
            let node_name = node.get("name").and_then(|n| n.as_str());

            if node_type == Some("workspace") && node_name == Some(target_ws) {
                if let Some(nodes) = node.get("nodes").and_then(|n| n.as_array()) {
                    for child in nodes {
                        if child.get("type").and_then(|t| t.as_str()) == Some("con")
                            && let Some(id) = child.get("id").and_then(|i| i.as_i64()) {
                                ids.push(id);
                            }
                    }
                }
                if let Some(nodes) = node.get("floating_nodes").and_then(|n| n.as_array()) {
                    for child in nodes {
                        if child.get("type").and_then(|t| t.as_str()) == Some("floating_con")
                            && let Some(id) = child.get("id").and_then(|i| i.as_i64()) {
                                ids.push(id);
                            }
                    }
                }
                return;
            }

            if let Some(nodes) = node.get("nodes").and_then(|n| n.as_array()) {
                for child in nodes {
                    collect_containers(child, target_ws, ids);
                }
            }
            if let Some(nodes) = node.get("floating_nodes").and_then(|n| n.as_array()) {
                for child in nodes {
                    collect_containers(child, target_ws, ids);
                }
            }
        }

        let mut container_ids = Vec::new();
        collect_containers(&tree, old_name, &mut container_ids);

        for id in &container_ids {
            let command = format!("[con_id={}] move to workspace \"{}\"", id, new_name);
            info!("merge: moving con_id={} to workspace '{}'", id, new_name);
            self.ipc_client.run_command(&command)?;
        }

        for m in old_memberships {
            m.delete(self.db.conn()).await?;
        }

        if let Ok(histories) = FocusHistoryEntity::find_by_workspace_name(old_name)
            .all(self.db.conn())
            .await
        {
            for h in histories {
                h.delete(self.db.conn()).await.ok();
            }
        }

        if let Ok(states) = GroupStateEntity::find_by_last_focused_workspace(old_name)
            .all(self.db.conn())
            .await
        {
            for s in states {
                s.delete(self.db.conn()).await.ok();
            }
        }

        // Clear hidden entries for the old workspace (row going away).
        HiddenWorkspaceEntity::delete_many()
            .filter(hidden_workspace::Column::WorkspaceId.eq(old_ws.id))
            .exec(self.db.conn())
            .await?;

        old_ws.delete(self.db.conn()).await?;

        info!("Merged workspace '{}' into '{}'", old_name, new_name);
        Ok(())
    }

    /// Sync workspaces from sway.
    pub async fn sync_from_sway(&self) -> Result<()> {
        let sway_workspaces = self.ipc_client.get_workspaces()?;
        let sway_outputs = self.ipc_client.get_outputs()?;
        let now = chrono::Utc::now().naive_utc();

        // Sync outputs
        for sway_out in &sway_outputs {
            let existing = OutputEntity::find_by_name(&sway_out.name)
                .one(self.db.conn())
                .await?;

            if let Some(out) = existing {
                let mut active = out.into_active_model();
                active.updated_at = Set(Some(now));
                active.update(self.db.conn()).await?;
            } else {
                let active = output::ActiveModel {
                    name: Set(sway_out.name.clone()),
                    active_group: Set(None),
                    created_at: Set(Some(now)),
                    updated_at: Set(Some(now)),
                    ..Default::default()
                };
                active.insert(self.db.conn()).await?;
                info!("Created output '{}'", sway_out.name);
            }
        }

        let sway_names: std::collections::HashSet<String> = sway_workspaces
            .iter()
            .map(|w| w.name.clone())
            .collect();

        for sway_ws in sway_workspaces {
            let base_name = sway_ws.name.clone();
            let existing = WorkspaceEntity::find_by_name(&base_name)
                .one(self.db.conn())
                .await?;

            if let Some(ws) = existing {
                let mut active = ws.into_active_model();
                active.number = Set(sway_ws.num.map(|n| n as i32));
                active.output = Set(Some(sway_ws.output));
                active.updated_at = Set(Some(now));
                active.update(self.db.conn()).await?;
            } else {
                let ws_output = sway_ws.output.clone();

                // Determine group: prefer output's active_group from DB
                let active_group = {
                    let mut group_name: Option<String> = None;
                    if let Some(output) = OutputEntity::find_by_name(&ws_output)
                        .one(self.db.conn())
                        .await
                        .ok()
                        .flatten()
                    {
                        group_name = output.active_group;
                    }

                    group_name
                };

                let number = sway_ws.num.map(|n| n as i32);
                let active = workspace::ActiveModel {
                    name: Set(base_name.clone()),
                    number: Set(number),
                    output: Set(Some(ws_output)),
                    is_global: Set(false),
                    created_at: Set(Some(now)),
                    updated_at: Set(Some(now)),
                    ..Default::default()
                };
                let ws = active.insert(self.db.conn()).await?;

                if let Some(ref ag) = active_group
                    && let Some(group) = GroupEntity::find_by_name(ag)
                        .one(self.db.conn())
                        .await?
                    {
                        let membership = workspace_group::ActiveModel {
                            workspace_id: Set(ws.id),
                            group_id: Set(group.id),
                            created_at: Set(Some(now)),
                            ..Default::default()
                        };
                        membership.insert(self.db.conn()).await?;
                    }
            }
        }

        // Remove workspaces that no longer exist in sway
        let db_workspaces = WorkspaceEntity::find()
            .all(self.db.conn())
            .await?;

        for ws in &db_workspaces {
            if !sway_names.contains(&ws.name) {
                // Remove group memberships
                let memberships = WorkspaceGroupEntity::find_by_workspace(ws.id)
                    .all(self.db.conn())
                    .await?;
                for m in memberships {
                    m.delete(self.db.conn()).await?;
                }
                // Remove focus history entries
                if let Ok(histories) = FocusHistoryEntity::find_by_workspace_name(&ws.name)
                    .all(self.db.conn())
                    .await
                {
                    for h in histories {
                        h.delete(self.db.conn()).await.ok();
                    }
                }
                // Remove group_state entries referencing this workspace
                if let Ok(states) = GroupStateEntity::find_by_last_focused_workspace(&ws.name)
                    .all(self.db.conn())
                    .await
                {
                    for s in states {
                        s.delete(self.db.conn()).await.ok();
                    }
                }
                // Remove hidden entries for this workspace
                HiddenWorkspaceEntity::delete_many()
                    .filter(hidden_workspace::Column::WorkspaceId.eq(ws.id))
                    .exec(self.db.conn())
                    .await
                    .ok();
                // Remove the workspace itself
                ws.clone().delete(self.db.conn()).await?;
                info!("Removed workspace '{}' (no longer in sway)", ws.name);
            }
        }

        info!("Synced workspaces from sway");
        Ok(())
    }

    /// Repair the database by reconciling with sway's actual state.
    /// Returns (removed_workspaces, added_workspaces, removed_groups).
    pub async fn repair(
        &self,
        group_service: &crate::services::GroupService,
    ) -> Result<(usize, usize, usize)> {
        let sway_workspaces = self.ipc_client.get_workspaces()?;
        let sway_outputs = self.ipc_client.get_outputs()?;
        let now = chrono::Utc::now().naive_utc();

        let sway_names: std::collections::HashSet<String> = sway_workspaces
            .iter()
            .map(|w| w.name.clone())
            .collect();

        let sway_output_names: std::collections::HashSet<String> = sway_outputs
            .iter()
            .map(|o| o.name.clone())
            .collect();

        let mut removed_ws = 0usize;
        let mut added_ws = 0usize;

        // --- Sync outputs ---
        let db_outputs = OutputEntity::find()
            .all(self.db.conn())
            .await?;

        for db_out in &db_outputs {
            if !sway_output_names.contains(&db_out.name) {
                db_out.clone().delete(self.db.conn()).await.ok();
                info!("repair: removed output '{}' from DB", db_out.name);
            }
        }

        for sway_out in &sway_outputs {
            let existing = OutputEntity::find_by_name(&sway_out.name)
                .one(self.db.conn())
                .await?;

            if let Some(out) = existing {
                let mut active = out.into_active_model();
                active.updated_at = Set(Some(now));
                active.update(self.db.conn()).await?;
            } else {
                let active = output::ActiveModel {
                    name: Set(sway_out.name.clone()),
                    active_group: Set(None),
                    created_at: Set(Some(now)),
                    updated_at: Set(Some(now)),
                    ..Default::default()
                };
                active.insert(self.db.conn()).await?;
                info!("repair: created output '{}'", sway_out.name);
            }
        }

        // --- Remove workspaces from DB that are not in sway ---
        let db_workspaces = WorkspaceEntity::find()
            .all(self.db.conn())
            .await?;

        for ws in &db_workspaces {
            if !sway_names.contains(&ws.name) {
                let memberships = WorkspaceGroupEntity::find_by_workspace(ws.id)
                    .all(self.db.conn())
                    .await?;
                for m in memberships {
                    m.delete(self.db.conn()).await.ok();
                }

                if let Ok(histories) = FocusHistoryEntity::find_by_workspace_name(&ws.name)
                    .all(self.db.conn())
                    .await
                {
                    for h in histories {
                        h.delete(self.db.conn()).await.ok();
                    }
                }

                HiddenWorkspaceEntity::delete_many()
                    .filter(hidden_workspace::Column::WorkspaceId.eq(ws.id))
                    .exec(self.db.conn())
                    .await
                    .ok();

                ws.clone().delete(self.db.conn()).await?;
                info!("repair: removed workspace '{}' from DB (not in sway)", ws.name);
                removed_ws += 1;
            }
        }

        // --- Add sway workspaces to DB that are not yet tracked ---
        for sway_ws in &sway_workspaces {
            let existing = WorkspaceEntity::find_by_name(&sway_ws.name)
                .one(self.db.conn())
                .await?;

            if existing.is_none() {
                let active = workspace::ActiveModel {
                    name: Set(sway_ws.name.clone()),
                    number: Set(sway_ws.num.map(|n| n as i32)),
                    output: Set(Some(sway_ws.output.clone())),
                    is_global: Set(false),
                    created_at: Set(Some(now)),
                    updated_at: Set(Some(now)),
                    ..Default::default()
                };
                let ws = active.insert(self.db.conn()).await?;

                if let Some(group) = GroupEntity::find_by_name(&self.default_group)
                    .one(self.db.conn())
                    .await?
                {
                    let membership = workspace_group::ActiveModel {
                        workspace_id: Set(ws.id),
                        group_id: Set(group.id),
                        created_at: Set(Some(now)),
                        ..Default::default()
                    };
                    membership.insert(self.db.conn()).await?;
                }

                info!("repair: added workspace '{}' to group '{}'", sway_ws.name, self.default_group);
                added_ws += 1;
            }
        }

        // --- Prune empty groups ---
        let removed_groups = group_service.prune_groups(&[]).await.unwrap_or_else(|e| { tracing::warn!("prune_groups failed: {}", e); 0 });

        info!("repair: removed {} stale workspaces, added {} new workspaces, pruned {} empty groups",
              removed_ws, added_ws, removed_groups);

        Ok((removed_ws, added_ws, removed_groups))
    }

    /// Register a pending workspace event to prevent the daemon from picking it up.
    /// Call before executing a sway command that creates or renames a workspace.
    /// Returns the id of the inserted pending event (for later removal).
    pub async fn register_pending_event(&self, workspace_name: &str, event_type: &str) -> Result<i32> {
        let now = chrono::Utc::now().naive_utc();
        let active = pending_workspace_event::ActiveModel {
            workspace_name: Set(workspace_name.to_string()),
            event_type: Set(event_type.to_string()),
            created_at: Set(now),
            ..Default::default()
        };
        let model = active.insert(self.db.conn()).await?;
        Ok(model.id)
    }

    /// Remove a pending workspace event after the sway command has completed.
    pub async fn remove_pending_event(&self, id: i32) -> Result<()> {
        if let Some(model) = PendingWorkspaceEventEntity::find_by_id(id)
            .one(self.db.conn())
            .await?
        {
            model.delete(self.db.conn()).await?;
        }
        Ok(())
    }

}