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
use crate::crypto::{CryptoParameters, SecrecyMode, SecurityLevel};
use crate::prelude::HeaderObfuscatorSettings;
use crate::utils;
use packed_struct::derive::PrimitiveEnum_u8;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display, Formatter};
use std::path::PathBuf;
use strum::VariantNames;
#[cfg(feature = "typescript")]
use ts_rs::TS;
use uuid::Uuid;

#[derive(Copy, Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
/// If force_login is true, the protocol will disconnect any previously existent sessions in the session manager attributed to the account logging-in (so long as login succeeds)
/// The default is a Standard login that will with force_login set to false
pub enum ConnectMode {
    Standard { force_login: bool },
    Fetch { force_login: bool },
}

impl Default for ConnectMode {
    fn default() -> Self {
        Self::Standard { force_login: false }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct VirtualObjectMetadata {
    pub name: String,
    pub date_created: String,
    pub author: String,
    pub plaintext_length: usize,
    pub group_count: usize,
    pub object_id: ObjectId,
    pub cid: u64,
    pub transfer_type: TransferType,
}

#[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
#[repr(transparent)]
pub struct ObjectId(pub u128);

impl Debug for ObjectId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Display for ObjectId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(self, f)
    }
}

impl ObjectId {
    pub fn random() -> Self {
        Uuid::new_v4().as_u128().into()
    }

    pub const fn zero() -> Self {
        Self(0)
    }
}

impl From<u128> for ObjectId {
    fn from(value: u128) -> Self {
        Self(value)
    }
}

impl VirtualObjectMetadata {
    pub fn serialize(&self) -> Vec<u8> {
        bincode::serialize(self).unwrap()
    }

    pub fn deserialize_from<'a, T: AsRef<[u8]> + 'a>(input: T) -> Option<Self> {
        bincode::deserialize(input.as_ref()).ok()
    }

    pub fn get_security_level(&self) -> Option<SecurityLevel> {
        match &self.transfer_type {
            TransferType::FileTransfer => None,
            TransferType::RemoteEncryptedVirtualFilesystem { security_level, .. } => {
                Some(*security_level)
            }
        }
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum ObjectTransferOrientation {
    Receiver { is_revfs_pull: bool },
    Sender,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
#[allow(variant_size_differences)]
pub enum ObjectTransferStatus {
    TransferBeginning,
    ReceptionBeginning(PathBuf, VirtualObjectMetadata),
    // relative group_id, total groups, Mb/s
    TransferTick(usize, usize, f32),
    ReceptionTick(usize, usize, f32),
    TransferComplete,
    ReceptionComplete,
    Fail(String),
}

impl ObjectTransferStatus {
    pub fn is_tick_type(&self) -> bool {
        matches!(
            self,
            ObjectTransferStatus::TransferTick(_, _, _)
                | ObjectTransferStatus::ReceptionTick(_, _, _)
        )
    }

    /// Even if an error, returns true if the file transfer is done
    pub fn is_finished_type(&self) -> bool {
        matches!(
            self,
            ObjectTransferStatus::TransferComplete
                | ObjectTransferStatus::ReceptionComplete
                | ObjectTransferStatus::Fail(_)
        )
    }
}

impl std::fmt::Display for ObjectTransferStatus {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ObjectTransferStatus::TransferBeginning => {
                write!(f, "Transfer beginning")
            }

            ObjectTransferStatus::ReceptionBeginning(_, vfm) => {
                write!(f, "Download for object {vfm:?} beginning")
            }

            ObjectTransferStatus::TransferTick(relative_group_id, total_groups, transfer_rate) => {
                utils::print_tick(f, *relative_group_id, *total_groups, *transfer_rate)
            }

            ObjectTransferStatus::ReceptionTick(relative_group_id, total_groups, transfer_rate) => {
                utils::print_tick(f, *relative_group_id, *total_groups, *transfer_rate)
            }

            ObjectTransferStatus::TransferComplete => {
                write!(f, "Transfer complete")
            }

            ObjectTransferStatus::ReceptionComplete => {
                write!(f, "Download complete")
            }

            ObjectTransferStatus::Fail(reason) => {
                write!(f, "Failure. Reason: {reason}")
            }
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct SessionSecuritySettings {
    pub security_level: SecurityLevel,
    pub secrecy_mode: SecrecyMode,
    pub crypto_params: CryptoParameters,
    pub header_obfuscator_settings: HeaderObfuscatorSettings,
}

#[derive(
    Debug,
    Serialize,
    Deserialize,
    Copy,
    Clone,
    Eq,
    PartialEq,
    Default,
    PrimitiveEnum_u8,
    strum::EnumString,
    strum::EnumIter,
    strum::EnumCount,
    strum_macros::VariantNames,
)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum UdpMode {
    #[default]
    Disabled,
    Enabled,
}

impl UdpMode {
    pub fn variants() -> Vec<String> {
        Self::VARIANTS.iter().map(|s| s.to_string()).collect()
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum MemberState {
    EnteredGroup { cids: Vec<u64> },
    LeftGroup { cids: Vec<u64> },
}

#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum GroupMemberAlterMode {
    Leave,
    Kick,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
/// Options for creating message groups
pub struct MessageGroupOptions {
    pub group_type: GroupType,
    pub id: u128,
    /// Whether the group uses the flat zero-trust CGKA or the Decentralized Hierarchy Encryption overlay.
    #[cfg_attr(feature = "typescript", ts(skip))]
    #[serde(default)]
    pub hierarchy: GroupHierarchyMode,
}

impl Default for MessageGroupOptions {
    fn default() -> Self {
        Self {
            group_type: GroupType::Private,
            id: Uuid::new_v4().as_u128(),
            hierarchy: GroupHierarchyMode::default(),
        }
    }
}

/// How a group's encryption is structured. `Flat` is the ordinary zero-trust CGKA where every member
/// shares one epoch key; `CommandHierarchy` adds the Decentralized Hierarchy Encryption overlay where a
/// superior can read its subordinates' messages (see [`ReadPolicy`]).
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
pub enum GroupHierarchyMode {
    /// Flat zero-trust group: one shared epoch key, no command hierarchy.
    #[default]
    Flat,
    /// Command-hierarchy overlay: members occupy a [`CommandPath`]; superiors read their subtree.
    CommandHierarchy {
        /// Who can read each message.
        read_policy: ReadPolicy,
        /// Initial rank assignment (member cid → command path), set by the owner at group creation.
        /// Consumed **owner-locally** to seed the hierarchy and never forwarded to the relay (the owner
        /// neutralizes this before the `Create` leaves the node), so command-structure labels stay off
        /// the wire; only the owner and the assigned members (via E2E-sealed node secrets) learn them.
        #[serde(default)]
        ranks: std::collections::HashMap<u64, CommandPath>,
    },
}

/// Who can read a hierarchy-group message.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadPolicy {
    /// Only the sender's command path + its ancestors (superiors).
    SuperiorOnly,
    /// Everyone in the flat group reads normally; superiors additionally retain a subtree audit capability.
    BroadcastAudit,
}

/// A position in a command hierarchy: ordered segments from the root (e.g. `/HQ/Bn1/Co-A/Plt-2`). An
/// empty path is the root authority. `is_ancestor_of` is the "superior reads subordinate" predicate.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct CommandPath(pub Vec<String>);

impl CommandPath {
    /// The root authority path (empty).
    pub fn root() -> Self {
        CommandPath(Vec::new())
    }

    /// Parse `/HQ/Bn1/Co-A` into segments (slashes split; empty segments ignored).
    pub fn parse(path: &str) -> Self {
        CommandPath(
            path.split('/')
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect(),
        )
    }

    /// A child path with one more segment.
    pub fn child(&self, segment: &str) -> Self {
        let mut segs = self.0.clone();
        segs.push(segment.to_string());
        CommandPath(segs)
    }

    /// Depth (number of segments).
    pub fn depth(&self) -> usize {
        self.0.len()
    }

    /// Whether `self` is an ancestor of (or equal to) `other` — i.e. `self` is a prefix of `other`.
    pub fn is_ancestor_of(&self, other: &CommandPath) -> bool {
        other.0.len() >= self.0.len() && other.0[..self.0.len()] == self.0[..]
    }
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Copy, Clone)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum GroupType {
    /// A public group is a group where any user registered to the owner can join
    Public,
    /// A private group is a group where the group can only be joined when the owner
    /// sends out Invitation requests to mutually-registered peers
    Private,
}

#[derive(Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub struct MessageGroupKey {
    pub cid: u64,
    pub mgid: u128,
}

impl MessageGroupKey {
    pub fn new(cid: u64, mgid: u128) -> Self {
        Self { cid, mgid }
    }
}

impl std::fmt::Debug for MessageGroupKey {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self}")
    }
}

impl std::fmt::Display for MessageGroupKey {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}:{}]", self.cid, self.mgid)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum TransferType {
    FileTransfer,
    RemoteEncryptedVirtualFilesystem {
        virtual_path: PathBuf,
        security_level: SecurityLevel,
    },
}

// =============================================================================
// Connection Types
// =============================================================================

/// Type of client-to-server connection.
///
/// Used for C2S disconnect events and peer discovery requests.
/// For P2P connections, use [`PeerConnectionType`] instead.
///
/// # Variants
///
/// - `Server`: Standard client-to-server connection (most common)
/// - `Extended`: Connection through federated server network (future feature)
///
/// # Network Topology
///
/// ```text
/// Standard Mode:          Extended Mode:
/// ┌────────┐              ┌────────┐      icid        ┌────────┐
/// │ Client │◄─────────────│ Server │◄────────────────►│ Server │
/// └────────┘  session_cid └────────┘                  └────────┘
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum ClientConnectionType {
    /// Standard client-to-server connection.
    Server {
        /// The session CID for this connection
        session_cid: u64,
    },
    /// Extended mode: client connected through federated server network.
    ///
    /// In Extended mode, multiple central servers are interconnected.
    /// **NOTE**: Not yet implemented - reserved for future use.
    Extended {
        /// The session CID for the client's connection to their home server
        session_cid: u64,
        /// The interserver connection identifier (icid) for server-to-server link
        interserver_cid: u64,
    },
}

impl ClientConnectionType {
    /// Returns the session CID for this connection.
    #[inline]
    pub fn session_cid(&self) -> u64 {
        match self {
            ClientConnectionType::Server { session_cid } => *session_cid,
            ClientConnectionType::Extended { session_cid, .. } => *session_cid,
        }
    }

    /// Returns the interserver CID if this is an Extended connection.
    #[inline]
    pub fn interserver_cid(&self) -> Option<u64> {
        match self {
            ClientConnectionType::Server { .. } => None,
            ClientConnectionType::Extended {
                interserver_cid, ..
            } => Some(*interserver_cid),
        }
    }
}

impl Display for ClientConnectionType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ClientConnectionType::Server { session_cid } => {
                write!(f, "C2S Server (cid={session_cid})")
            }
            ClientConnectionType::Extended {
                session_cid,
                interserver_cid,
            } => {
                write!(
                    f,
                    "C2S Extended (cid={session_cid}, icid={interserver_cid})"
                )
            }
        }
    }
}

/// Type of peer-to-peer connection.
///
/// Used in peer signaling to identify P2P connections between clients.
///
/// # Variants
///
/// - `LocalGroupPeer`: Both peers connected to the same server
/// - `ExternalGroupPeer`: Peers connected to different servers (federated)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum PeerConnectionType {
    /// P2P connection where both peers are on the same server.
    LocalGroupPeer {
        /// This client's session CID
        session_cid: u64,
        /// The peer's CID
        peer_cid: u64,
    },
    /// P2P connection where peers are on different servers (federated).
    ExternalGroupPeer {
        /// This client's session CID
        session_cid: u64,
        /// The interserver connection identifier
        interserver_cid: u64,
        /// The peer's CID on their home server
        peer_cid: u64,
    },
}

impl PeerConnectionType {
    /// Returns the originating session CID.
    #[inline]
    pub fn get_original_session_cid(&self) -> u64 {
        match self {
            PeerConnectionType::LocalGroupPeer { session_cid, .. } => *session_cid,
            PeerConnectionType::ExternalGroupPeer { session_cid, .. } => *session_cid,
        }
    }

    /// Returns the target peer CID.
    #[inline]
    pub fn get_original_target_cid(&self) -> u64 {
        match self {
            PeerConnectionType::LocalGroupPeer { peer_cid, .. } => *peer_cid,
            PeerConnectionType::ExternalGroupPeer { peer_cid, .. } => *peer_cid,
        }
    }

    /// Returns a reversed connection (swapping session_cid and peer_cid).
    pub fn reverse(&self) -> PeerConnectionType {
        match self {
            PeerConnectionType::LocalGroupPeer {
                session_cid,
                peer_cid,
            } => PeerConnectionType::LocalGroupPeer {
                session_cid: *peer_cid,
                peer_cid: *session_cid,
            },
            PeerConnectionType::ExternalGroupPeer {
                session_cid,
                interserver_cid,
                peer_cid,
            } => PeerConnectionType::ExternalGroupPeer {
                session_cid: *peer_cid,
                interserver_cid: *interserver_cid,
                peer_cid: *session_cid,
            },
        }
    }

    /// Converts to a VirtualConnectionType.
    pub fn as_virtual_connection(self) -> VirtualConnectionType {
        match self {
            PeerConnectionType::LocalGroupPeer {
                session_cid,
                peer_cid,
            } => VirtualConnectionType::LocalGroupPeer {
                session_cid,
                peer_cid,
            },
            PeerConnectionType::ExternalGroupPeer {
                session_cid,
                interserver_cid,
                peer_cid,
            } => VirtualConnectionType::ExternalGroupPeer {
                session_cid,
                interserver_cid,
                peer_cid,
            },
        }
    }
}

impl Display for PeerConnectionType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            PeerConnectionType::LocalGroupPeer {
                session_cid,
                peer_cid,
            } => {
                write!(f, "hLAN {session_cid} <-> {peer_cid}")
            }
            PeerConnectionType::ExternalGroupPeer {
                session_cid,
                interserver_cid,
                peer_cid,
            } => {
                write!(f, "hWAN {session_cid} <-> {interserver_cid} <-> {peer_cid}")
            }
        }
    }
}

/// Unified type representing all possible virtual connections.
///
/// This type is used throughout the protocol for packet routing and connection
/// management. It covers both C2S and P2P connection scenarios.
///
/// # Variants
///
/// ## C2S Connections
/// - `LocalGroupServer`: Client connected to their home server
/// - `ExternalGroupServer`: Client connected through federated network (future)
///
/// ## P2P Connections
/// - `LocalGroupPeer`: P2P where both peers share the same server
/// - `ExternalGroupPeer`: P2P across federated servers (future)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export))]
pub enum VirtualConnectionType {
    /// P2P connection on the same server.
    LocalGroupPeer {
        /// This client's session CID
        session_cid: u64,
        /// The peer's CID
        peer_cid: u64,
    },
    /// P2P connection across federated servers.
    ExternalGroupPeer {
        /// This client's session CID
        session_cid: u64,
        /// The interserver connection identifier
        interserver_cid: u64,
        /// The peer's CID on their home server
        peer_cid: u64,
    },
    /// Standard client-to-server connection.
    LocalGroupServer {
        /// The session CID
        session_cid: u64,
    },
    /// Client-to-server through federated network.
    ExternalGroupServer {
        /// This client's session CID
        session_cid: u64,
        /// The interserver connection identifier
        interserver_cid: u64,
    },
}

/// Alias for VirtualConnectionType (for readability in target contexts).
pub type VirtualTargetType = VirtualConnectionType;

/// Constant for C2S identity (target_cid = 0 means server).
pub const C2S_IDENTITY_CID: u64 = 0;

impl VirtualConnectionType {
    /// Serializes to bytes.
    pub fn serialize(&self) -> Vec<u8> {
        bincode::serialize(self).unwrap()
    }

    /// Deserializes from bytes.
    pub fn deserialize_from<'a, T: AsRef<[u8]> + 'a>(this: T) -> Option<Self> {
        bincode::deserialize(this.as_ref()).ok()
    }

    /// Gets the target CID, agnostic to connection type.
    pub fn get_target_cid(&self) -> u64 {
        match self {
            VirtualConnectionType::LocalGroupServer { .. } => C2S_IDENTITY_CID,
            VirtualConnectionType::LocalGroupPeer { peer_cid, .. } => *peer_cid,
            VirtualConnectionType::ExternalGroupPeer { peer_cid, .. } => *peer_cid,
            VirtualConnectionType::ExternalGroupServer {
                interserver_cid, ..
            } => *interserver_cid,
        }
    }

    /// Gets the session CID.
    pub fn get_session_cid(&self) -> u64 {
        match self {
            VirtualConnectionType::LocalGroupServer { session_cid } => *session_cid,
            VirtualConnectionType::LocalGroupPeer { session_cid, .. } => *session_cid,
            VirtualConnectionType::ExternalGroupPeer { session_cid, .. } => *session_cid,
            VirtualConnectionType::ExternalGroupServer { session_cid, .. } => *session_cid,
        }
    }

    /// Returns true if this is a C2S connection.
    pub fn is_server_connection(&self) -> bool {
        matches!(
            self,
            VirtualConnectionType::LocalGroupServer { .. }
                | VirtualConnectionType::ExternalGroupServer { .. }
        )
    }

    /// Returns true if this is a P2P connection.
    pub fn is_peer_connection(&self) -> bool {
        matches!(
            self,
            VirtualConnectionType::LocalGroupPeer { .. }
                | VirtualConnectionType::ExternalGroupPeer { .. }
        )
    }

    /// Attempts to convert to a PeerConnectionType.
    pub fn try_as_peer_connection(&self) -> Option<PeerConnectionType> {
        match self {
            VirtualConnectionType::LocalGroupPeer {
                session_cid,
                peer_cid,
            } => Some(PeerConnectionType::LocalGroupPeer {
                session_cid: *session_cid,
                peer_cid: *peer_cid,
            }),
            VirtualConnectionType::ExternalGroupPeer {
                session_cid,
                interserver_cid,
                peer_cid,
            } => Some(PeerConnectionType::ExternalGroupPeer {
                session_cid: *session_cid,
                interserver_cid: *interserver_cid,
                peer_cid: *peer_cid,
            }),
            _ => None,
        }
    }

    /// Attempts to convert to a ClientConnectionType.
    pub fn try_as_client_connection(&self) -> Option<ClientConnectionType> {
        match self {
            VirtualConnectionType::LocalGroupServer { session_cid } => {
                Some(ClientConnectionType::Server {
                    session_cid: *session_cid,
                })
            }
            VirtualConnectionType::ExternalGroupServer {
                session_cid,
                interserver_cid,
            } => Some(ClientConnectionType::Extended {
                session_cid: *session_cid,
                interserver_cid: *interserver_cid,
            }),
            _ => None,
        }
    }

    /// Returns true if this is a local group connection (same server).
    pub fn is_local_group(&self) -> bool {
        matches!(
            self,
            VirtualConnectionType::LocalGroupPeer { .. }
                | VirtualConnectionType::LocalGroupServer { .. }
        )
    }

    /// Returns true if this is an external group connection (federated).
    pub fn is_external_group(&self) -> bool {
        !self.is_local_group()
    }

    /// Sets the target CID (for P2P connections only).
    pub fn set_target_cid(&mut self, target_cid: u64) {
        match self {
            VirtualConnectionType::LocalGroupPeer { peer_cid, .. }
            | VirtualConnectionType::ExternalGroupPeer { peer_cid, .. } => *peer_cid = target_cid,
            _ => {}
        }
    }

    /// Sets the session CID.
    pub fn set_session_cid(&mut self, cid: u64) {
        match self {
            VirtualConnectionType::LocalGroupPeer { session_cid, .. }
            | VirtualConnectionType::ExternalGroupPeer { session_cid, .. }
            | VirtualConnectionType::LocalGroupServer { session_cid }
            | VirtualConnectionType::ExternalGroupServer { session_cid, .. } => *session_cid = cid,
        }
    }
}

impl Display for VirtualConnectionType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            VirtualConnectionType::LocalGroupServer { session_cid } => {
                write!(f, "C2S Local (cid={session_cid})")
            }
            VirtualConnectionType::LocalGroupPeer {
                session_cid,
                peer_cid,
            } => {
                write!(f, "P2P Local ({session_cid} -> {peer_cid})")
            }
            VirtualConnectionType::ExternalGroupPeer {
                session_cid,
                interserver_cid,
                peer_cid,
            } => {
                write!(
                    f,
                    "P2P External ({session_cid} -> {interserver_cid} -> {peer_cid})"
                )
            }
            VirtualConnectionType::ExternalGroupServer {
                session_cid,
                interserver_cid,
            } => {
                write!(f, "C2S External ({session_cid} -> {interserver_cid})")
            }
        }
    }
}

impl From<PeerConnectionType> for VirtualConnectionType {
    fn from(peer: PeerConnectionType) -> Self {
        peer.as_virtual_connection()
    }
}

impl From<ClientConnectionType> for VirtualConnectionType {
    fn from(client: ClientConnectionType) -> Self {
        match client {
            ClientConnectionType::Server { session_cid } => {
                VirtualConnectionType::LocalGroupServer { session_cid }
            }
            ClientConnectionType::Extended {
                session_cid,
                interserver_cid,
            } => VirtualConnectionType::ExternalGroupServer {
                session_cid,
                interserver_cid,
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn command_path_parse_root_child_depth() {
        assert_eq!(CommandPath::root().depth(), 0);
        let p = CommandPath::parse("/HQ/Bn1/Co-A");
        assert_eq!(p.0, vec!["HQ", "Bn1", "Co-A"]);
        assert_eq!(p.depth(), 3);
        // leading/trailing/double slashes and empties are ignored
        assert_eq!(CommandPath::parse("///HQ//Bn1/").0, vec!["HQ", "Bn1"]);
        assert_eq!(CommandPath::parse("").depth(), 0);
        let c = CommandPath::parse("/HQ").child("Bn1");
        assert_eq!(c.0, vec!["HQ", "Bn1"]);
    }

    #[test]
    fn command_path_is_ancestor_of() {
        let root = CommandPath::root();
        let hq = CommandPath::parse("/HQ");
        let bn1 = CommandPath::parse("/HQ/Bn1");
        let coa = CommandPath::parse("/HQ/Bn1/Co-A");
        let cob = CommandPath::parse("/HQ/Bn1/Co-B");
        // reflexive + prefix chain
        assert!(hq.is_ancestor_of(&hq));
        assert!(root.is_ancestor_of(&coa));
        assert!(hq.is_ancestor_of(&bn1));
        assert!(bn1.is_ancestor_of(&coa));
        // not upward, not across
        assert!(!coa.is_ancestor_of(&bn1));
        assert!(!coa.is_ancestor_of(&cob));
        assert!(!cob.is_ancestor_of(&coa));
    }

    #[test]
    fn virtual_connection_type_accessors_and_predicates() {
        let server = VirtualConnectionType::LocalGroupServer { session_cid: 7 };
        let peer = VirtualConnectionType::LocalGroupPeer {
            session_cid: 7,
            peer_cid: 9,
        };
        let ext_peer = VirtualConnectionType::ExternalGroupPeer {
            session_cid: 1,
            interserver_cid: 2,
            peer_cid: 3,
        };
        let ext_server = VirtualConnectionType::ExternalGroupServer {
            session_cid: 4,
            interserver_cid: 5,
        };

        assert_eq!(server.get_target_cid(), C2S_IDENTITY_CID);
        assert_eq!(server.get_session_cid(), 7);
        assert_eq!(peer.get_target_cid(), 9);
        assert_eq!(ext_peer.get_target_cid(), 3);
        assert_eq!(ext_server.get_target_cid(), 5);
        assert_eq!(ext_peer.get_session_cid(), 1);

        assert!(server.is_server_connection() && !server.is_peer_connection());
        assert!(peer.is_peer_connection() && !peer.is_server_connection());
        assert!(server.is_local_group() && !server.is_external_group());
        assert!(ext_peer.is_external_group() && !ext_peer.is_local_group());

        assert!(peer.try_as_peer_connection().is_some());
        assert!(server.try_as_peer_connection().is_none());
        assert!(server.try_as_client_connection().is_some());
        assert!(peer.try_as_client_connection().is_none());
    }

    #[test]
    fn virtual_connection_type_mutators_and_roundtrip() {
        let mut peer = VirtualConnectionType::LocalGroupPeer {
            session_cid: 7,
            peer_cid: 9,
        };
        peer.set_target_cid(42);
        peer.set_session_cid(11);
        assert_eq!(peer.get_target_cid(), 42);
        assert_eq!(peer.get_session_cid(), 11);

        // set_target_cid is a no-op on server connections
        let mut server = VirtualConnectionType::LocalGroupServer { session_cid: 1 };
        server.set_target_cid(99);
        assert_eq!(server.get_target_cid(), C2S_IDENTITY_CID);
        server.set_session_cid(2);
        assert_eq!(server.get_session_cid(), 2);

        let bytes = peer.serialize();
        assert_eq!(VirtualConnectionType::deserialize_from(&bytes), Some(peer));
        assert!(VirtualConnectionType::deserialize_from([0xFFu8; 1]).is_none());
        // Display does not panic for any variant
        let _ = format!("{server}{peer}");
    }

    #[test]
    fn peer_connection_type_reverse_and_convert() {
        let local = PeerConnectionType::LocalGroupPeer {
            session_cid: 1,
            peer_cid: 2,
        };
        assert_eq!(local.get_original_session_cid(), 1);
        assert_eq!(local.get_original_target_cid(), 2);
        let rev = local.reverse();
        assert_eq!(rev.get_original_session_cid(), 2);
        assert_eq!(rev.get_original_target_cid(), 1);

        let ext = PeerConnectionType::ExternalGroupPeer {
            session_cid: 1,
            interserver_cid: 5,
            peer_cid: 2,
        };
        assert_eq!(ext.reverse().get_original_session_cid(), 2);

        // round-trip through VirtualConnectionType conversions
        let v: VirtualConnectionType = local.into();
        assert_eq!(v.try_as_peer_connection(), Some(local));
        assert_eq!(VirtualConnectionType::from(ext).get_target_cid(), 2);
        let _ = format!("{local}{ext}");
    }

    #[test]
    fn client_connection_type_accessors() {
        let server = ClientConnectionType::Server { session_cid: 8 };
        let ext = ClientConnectionType::Extended {
            session_cid: 8,
            interserver_cid: 3,
        };
        assert_eq!(server.session_cid(), 8);
        assert_eq!(server.interserver_cid(), None);
        assert_eq!(ext.interserver_cid(), Some(3));
        // From<ClientConnectionType> mapping
        assert_eq!(
            VirtualConnectionType::from(server),
            VirtualConnectionType::LocalGroupServer { session_cid: 8 }
        );
        assert!(matches!(
            VirtualConnectionType::from(ext),
            VirtualConnectionType::ExternalGroupServer { .. }
        ));
        let _ = format!("{server}{ext}");
    }

    #[test]
    fn object_transfer_status_predicates_and_display() {
        assert!(ObjectTransferStatus::TransferTick(1, 2, 3.0).is_tick_type());
        assert!(ObjectTransferStatus::ReceptionTick(1, 2, 3.0).is_tick_type());
        assert!(!ObjectTransferStatus::TransferBeginning.is_tick_type());
        assert!(ObjectTransferStatus::TransferComplete.is_finished_type());
        assert!(ObjectTransferStatus::ReceptionComplete.is_finished_type());
        assert!(ObjectTransferStatus::Fail("x".into()).is_finished_type());
        assert!(!ObjectTransferStatus::TransferBeginning.is_finished_type());
        for s in [
            ObjectTransferStatus::TransferBeginning,
            ObjectTransferStatus::TransferTick(1, 4, 2.5),
            ObjectTransferStatus::ReceptionTick(2, 4, 1.0),
            ObjectTransferStatus::TransferComplete,
            ObjectTransferStatus::ReceptionComplete,
            ObjectTransferStatus::Fail("boom".into()),
        ] {
            assert!(!format!("{s}").is_empty());
        }
    }

    #[test]
    fn virtual_object_metadata_roundtrip_and_security_level() {
        let file = VirtualObjectMetadata {
            name: "f".into(),
            date_created: "now".into(),
            author: "a".into(),
            plaintext_length: 10,
            group_count: 1,
            object_id: ObjectId::zero(),
            cid: 5,
            transfer_type: TransferType::FileTransfer,
        };
        let bytes = file.serialize();
        let back = VirtualObjectMetadata::deserialize_from(&bytes).unwrap();
        assert_eq!(back.cid, 5);
        assert!(file.get_security_level().is_none());

        let revfs = VirtualObjectMetadata {
            transfer_type: TransferType::RemoteEncryptedVirtualFilesystem {
                virtual_path: PathBuf::from("/v"),
                security_level: SecurityLevel::High,
            },
            ..file
        };
        assert!(matches!(
            revfs.get_security_level(),
            Some(SecurityLevel::High)
        ));
        assert!(VirtualObjectMetadata::deserialize_from([0u8; 1]).is_none());
    }

    #[test]
    fn object_id_and_message_group_key_helpers() {
        assert_eq!(ObjectId::zero().0, 0);
        assert_eq!(ObjectId::from(42u128).0, 42);
        assert_ne!(ObjectId::random(), ObjectId::random());
        assert_eq!(format!("{}", ObjectId::from(7u128)), "7");

        let key = MessageGroupKey::new(3, 99);
        assert_eq!(key.cid, 3);
        assert_eq!(key.mgid, 99);
        assert!(!format!("{key}").is_empty());
        assert!(!format!("{key:?}").is_empty());
    }

    #[test]
    fn udp_mode_and_defaults() {
        assert_eq!(UdpMode::default(), UdpMode::Disabled);
        assert!(!UdpMode::variants().is_empty());
        assert_eq!(GroupHierarchyMode::default(), GroupHierarchyMode::Flat);
        assert_eq!(
            MessageGroupOptions::default().group_type,
            GroupType::Private
        );
    }
}