brahe 1.4.0

Brahe is a modern satellite dynamics library for research and engineering applications designed to be easy-to-learn, high-performance, and quick-to-deploy. The north-star of the development is enabling users to solve meaningful problems and answer questions quickly, easily, and correctly.
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
/*!
 * Query builder for the CelestrakClient API.
 *
 * Provides a fluent builder pattern for constructing CelestrakClient queries
 * with both server-side parameters (sent to CelestrakClient) and client-side
 * post-processing options (filtering, ordering, limiting applied after download).
 *
 * CelestrakClient uses standard HTTP query parameters rather than path-based queries:
 * `?GROUP=stations&FORMAT=JSON`
 */

use crate::celestrak::types::{CelestrakOutputFormat, CelestrakQueryType, SupGPSource};

/// A client-side filter predicate for post-download filtering.
///
/// Uses the same operator string format as SpaceTrack operators
/// (e.g., `>50`, `<0.01`, `<>DEBRIS`, `25544--25600`, `~~STARLINK`, `^NOAA`).
#[derive(Debug, Clone)]
pub(crate) struct Filter {
    pub(crate) field: String,
    pub(crate) value: String,
}

/// An ordering clause for client-side sorting of results.
#[derive(Debug, Clone)]
pub(crate) struct OrderBy {
    pub(crate) field: String,
    pub(crate) ascending: bool,
}

/// Builder for constructing CelestrakClient API queries.
///
/// Uses a fluent API where each method returns `Self` to allow method chaining.
/// Parameters are divided into:
///
/// - **Server-side**: Sent as URL query parameters to CelestrakClient (group, catnr, etc.)
/// - **Client-side**: Applied by Brahe after downloading the data (filter, order_by, limit)
///
/// # Examples
///
/// ```
/// use brahe::celestrak::{CelestrakQuery, CelestrakOutputFormat};
///
/// // GP query by satellite group
/// let query = CelestrakQuery::gp()
///     .group("stations")
///     .format(CelestrakOutputFormat::Json);
///
/// let url = query.build_url();
/// assert!(url.contains("GROUP=stations"));
/// assert!(url.contains("FORMAT=JSON"));
///
/// // SATCAT query for active payloads
/// let query = CelestrakQuery::satcat()
///     .active(true)
///     .payloads(true);
///
/// let url = query.build_url();
/// assert!(url.contains("ACTIVE=Y"));
/// assert!(url.contains("PAYLOADS=Y"));
/// ```
#[derive(Debug, Clone)]
pub struct CelestrakQuery {
    query_type: CelestrakQueryType,
    // Server-side parameters (sent to CelestrakClient API)
    group: Option<String>,
    catnr: Option<u32>,
    intdes: Option<String>,
    name: Option<String>,
    special: Option<String>,
    source: Option<SupGPSource>,
    file: Option<String>,
    payloads: Option<bool>,
    on_orbit: Option<bool>,
    active: Option<bool>,
    max_results: Option<u32>,
    output_format: Option<CelestrakOutputFormat>,
    // Client-side post-processing (applied by Brahe after download)
    filters: Vec<Filter>,
    order_by_clauses: Vec<OrderBy>,
    limit_count: Option<u32>,
}

impl CelestrakQuery {
    /// Create a new query builder for the specified query type.
    ///
    /// # Arguments
    ///
    /// * `query_type` - The CelestrakClient API endpoint to query
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::celestrak::{CelestrakQuery, CelestrakQueryType};
    ///
    /// let query = CelestrakQuery::new(CelestrakQueryType::GP);
    /// assert_eq!(query.query_type(), CelestrakQueryType::GP);
    /// ```
    pub fn new(query_type: CelestrakQueryType) -> Self {
        CelestrakQuery {
            query_type,
            group: None,
            catnr: None,
            intdes: None,
            name: None,
            special: None,
            source: None,
            file: None,
            payloads: None,
            on_orbit: None,
            active: None,
            max_results: None,
            output_format: None,
            filters: Vec::new(),
            order_by_clauses: Vec::new(),
            limit_count: None,
        }
    }

    /// Create a new GP query builder.
    ///
    /// Shorthand for `CelestrakQuery::new(CelestrakQueryType::GP)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::celestrak::{CelestrakQuery, CelestrakQueryType};
    ///
    /// let query = CelestrakQuery::gp();
    /// assert_eq!(query.query_type(), CelestrakQueryType::GP);
    /// ```
    pub fn gp() -> Self {
        Self::new(CelestrakQueryType::GP)
    }

    /// Create a new supplemental GP query builder.
    ///
    /// Shorthand for `CelestrakQuery::new(CelestrakQueryType::SupGP)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::celestrak::{CelestrakQuery, CelestrakQueryType};
    ///
    /// let query = CelestrakQuery::sup_gp();
    /// assert_eq!(query.query_type(), CelestrakQueryType::SupGP);
    /// ```
    pub fn sup_gp() -> Self {
        Self::new(CelestrakQueryType::SupGP)
    }

    /// Create a new SATCAT query builder.
    ///
    /// Shorthand for `CelestrakQuery::new(CelestrakQueryType::SATCAT)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::celestrak::{CelestrakQuery, CelestrakQueryType};
    ///
    /// let query = CelestrakQuery::satcat();
    /// assert_eq!(query.query_type(), CelestrakQueryType::SATCAT);
    /// ```
    pub fn satcat() -> Self {
        Self::new(CelestrakQueryType::SATCAT)
    }

    // -- Server-side parameters --

    /// Set the satellite group for the query.
    ///
    /// Available for GP and SATCAT queries. Groups include "stations", "active",
    /// "gnss", "last-30-days", etc.
    ///
    /// # Arguments
    ///
    /// * `group` - The satellite group name
    pub fn group(mut self, group: &str) -> Self {
        self.group = Some(group.to_string());
        self
    }

    /// Set the NORAD catalog number filter.
    ///
    /// Available for GP, SupGP, and SATCAT queries.
    ///
    /// # Arguments
    ///
    /// * `norad_id` - The NORAD catalog number
    pub fn catnr(mut self, norad_id: u32) -> Self {
        self.catnr = Some(norad_id);
        self
    }

    /// Set the international designator filter.
    ///
    /// Available for GP, SupGP, and SATCAT queries.
    ///
    /// # Arguments
    ///
    /// * `intdes` - The international designator (e.g., "1998-067A")
    pub fn intdes(mut self, intdes: &str) -> Self {
        self.intdes = Some(intdes.to_string());
        self
    }

    /// Set the satellite name search filter.
    ///
    /// Available for GP, SupGP, and SATCAT queries.
    ///
    /// # Arguments
    ///
    /// * `name` - The satellite name (partial match supported)
    pub fn name_search(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }

    /// Set the special query parameter.
    ///
    /// Available for all query types. Typically used for special collections
    /// or custom queries.
    ///
    /// # Arguments
    ///
    /// * `special` - The special query value
    pub fn special(mut self, special: &str) -> Self {
        self.special = Some(special.to_string());
        self
    }

    /// Set the supplemental GP data source.
    ///
    /// Only available for SupGP queries.
    ///
    /// # Arguments
    ///
    /// * `source` - The supplemental data source
    pub fn source(mut self, source: SupGPSource) -> Self {
        self.source = Some(source);
        self
    }

    /// Set the file parameter for supplemental GP queries.
    ///
    /// Only available for SupGP queries.
    ///
    /// # Arguments
    ///
    /// * `file` - The file identifier
    pub fn file(mut self, file: &str) -> Self {
        self.file = Some(file.to_string());
        self
    }

    /// Filter to payloads only.
    ///
    /// Only available for SATCAT queries.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to filter to payloads only
    pub fn payloads(mut self, enabled: bool) -> Self {
        self.payloads = Some(enabled);
        self
    }

    /// Filter to on-orbit objects only.
    ///
    /// Only available for SATCAT queries.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to filter to on-orbit objects only
    pub fn on_orbit(mut self, enabled: bool) -> Self {
        self.on_orbit = Some(enabled);
        self
    }

    /// Filter to active objects only.
    ///
    /// Only available for SATCAT queries.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to filter to active objects only
    pub fn active(mut self, enabled: bool) -> Self {
        self.active = Some(enabled);
        self
    }

    /// Set the maximum number of results returned by the server.
    ///
    /// Only available for SATCAT queries. This is a server-side limit.
    /// For client-side limiting (applied after download), use `limit()`.
    ///
    /// # Arguments
    ///
    /// * `max` - Maximum number of results
    pub fn max(mut self, max: u32) -> Self {
        self.max_results = Some(max);
        self
    }

    /// Set the output format for query results.
    ///
    /// If not specified, typed query methods (`query_gp`, `query_satcat`)
    /// will automatically use JSON.
    ///
    /// # Arguments
    ///
    /// * `format` - The desired output format
    pub fn format(mut self, format: CelestrakOutputFormat) -> Self {
        self.output_format = Some(format);
        self
    }

    // -- Client-side post-processing --

    /// Add a client-side filter predicate.
    ///
    /// Filters are applied by Brahe after downloading the data. Use SpaceTrack
    /// operator functions to construct comparison values.
    ///
    /// # Arguments
    ///
    /// * `field` - The record field name (e.g., "INCLINATION", "ECCENTRICITY")
    /// * `value` - The filter value with optional operator prefix (e.g., ">50", "<0.01")
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::celestrak::CelestrakQuery;
    /// use brahe::spacetrack::operators;
    ///
    /// let query = CelestrakQuery::gp()
    ///     .group("stations")
    ///     .filter("INCLINATION", &operators::greater_than("50"))
    ///     .filter("ECCENTRICITY", &operators::less_than("0.01"));
    /// ```
    pub fn filter(mut self, field: &str, value: &str) -> Self {
        self.filters.push(Filter {
            field: field.to_string(),
            value: value.to_string(),
        });
        self
    }

    /// Add a client-side ordering clause.
    ///
    /// Ordering is applied by Brahe after downloading the data.
    /// Multiple calls are cumulative.
    ///
    /// # Arguments
    ///
    /// * `field` - The field to sort by
    /// * `ascending` - Whether to sort ascending (true) or descending (false)
    pub fn order_by(mut self, field: &str, ascending: bool) -> Self {
        self.order_by_clauses.push(OrderBy {
            field: field.to_string(),
            ascending,
        });
        self
    }

    /// Set a client-side limit on the number of results.
    ///
    /// This limit is applied after downloading and filtering. For server-side
    /// limiting on SATCAT queries, use `max()`.
    ///
    /// # Arguments
    ///
    /// * `count` - Maximum number of records to return after filtering
    pub fn limit(mut self, count: u32) -> Self {
        self.limit_count = Some(count);
        self
    }

    // -- Accessors --

    /// Returns the query type for this query.
    pub fn query_type(&self) -> CelestrakQueryType {
        self.query_type
    }

    /// Returns the output format for this query.
    ///
    /// Returns `None` if no format has been explicitly set.
    pub fn output_format(&self) -> Option<CelestrakOutputFormat> {
        self.output_format
    }

    /// Returns true if this query has any client-side filters.
    pub fn has_client_side_processing(&self) -> bool {
        !self.filters.is_empty() || !self.order_by_clauses.is_empty() || self.limit_count.is_some()
    }

    /// Returns a reference to the client-side filters.
    pub(crate) fn client_side_filters(&self) -> &[Filter] {
        &self.filters
    }

    /// Returns a reference to the client-side ordering clauses.
    pub(crate) fn client_side_order_by(&self) -> &[OrderBy] {
        &self.order_by_clauses
    }

    /// Returns the client-side limit, if set.
    pub(crate) fn client_side_limit(&self) -> Option<u32> {
        self.limit_count
    }

    // -- URL building --

    /// Build the URL query string for this query.
    ///
    /// Produces the query string portion (after `?`) to be appended to the
    /// base URL and endpoint path. Only includes server-side parameters;
    /// client-side filters are not included in the URL.
    ///
    /// # Returns
    ///
    /// * `String` - The URL query string (e.g., "GROUP=stations&FORMAT=JSON")
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::celestrak::{CelestrakQuery, CelestrakOutputFormat};
    ///
    /// let query = CelestrakQuery::gp()
    ///     .group("stations")
    ///     .format(CelestrakOutputFormat::Json);
    ///
    /// let url = query.build_url();
    /// assert_eq!(url, "GROUP=stations&FORMAT=JSON");
    /// ```
    pub fn build_url(&self) -> String {
        let mut params = Vec::new();

        // GP and SATCAT: GROUP
        if let Some(ref group) = self.group {
            params.push(format!("GROUP={}", group));
        }

        // GP, SupGP, SATCAT: CATNR
        if let Some(catnr) = self.catnr {
            params.push(format!("CATNR={}", catnr));
        }

        // GP, SupGP, SATCAT: INTDES
        if let Some(ref intdes) = self.intdes {
            params.push(format!("INTDES={}", intdes));
        }

        // GP, SupGP, SATCAT: NAME
        if let Some(ref name) = self.name {
            params.push(format!("NAME={}", name));
        }

        // All: SPECIAL
        if let Some(ref special) = self.special {
            params.push(format!("SPECIAL={}", special));
        }

        // SupGP: SOURCE
        if let Some(ref source) = self.source {
            params.push(format!("SOURCE={}", source.as_str()));
        }

        // SupGP: FILE
        if let Some(ref file) = self.file {
            params.push(format!("FILE={}", file));
        }

        // SATCAT: PAYLOADS
        if let Some(enabled) = self.payloads
            && enabled
        {
            params.push("PAYLOADS=Y".to_string());
        }

        // SATCAT: ONORBIT
        if let Some(enabled) = self.on_orbit
            && enabled
        {
            params.push("ONORBIT=Y".to_string());
        }

        // SATCAT: ACTIVE
        if let Some(enabled) = self.active
            && enabled
        {
            params.push("ACTIVE=Y".to_string());
        }

        // SATCAT: MAX
        if let Some(max) = self.max_results {
            params.push(format!("MAX={}", max));
        }

        // All: FORMAT
        if let Some(ref format) = self.output_format {
            params.push(format!("FORMAT={}", format.as_str()));
        }

        params.join("&")
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    // -- Constructor tests --

    #[test]
    fn test_gp_constructor() {
        let query = CelestrakQuery::gp();
        assert_eq!(query.query_type(), CelestrakQueryType::GP);
    }

    #[test]
    fn test_sup_gp_constructor() {
        let query = CelestrakQuery::sup_gp();
        assert_eq!(query.query_type(), CelestrakQueryType::SupGP);
    }

    #[test]
    fn test_satcat_constructor() {
        let query = CelestrakQuery::satcat();
        assert_eq!(query.query_type(), CelestrakQueryType::SATCAT);
    }

    #[test]
    fn test_new_constructor() {
        let query = CelestrakQuery::new(CelestrakQueryType::GP);
        assert_eq!(query.query_type(), CelestrakQueryType::GP);
    }

    // -- GP URL building tests --

    #[test]
    fn test_gp_by_group() {
        let query = CelestrakQuery::gp().group("stations");
        assert_eq!(query.build_url(), "GROUP=stations");
    }

    #[test]
    fn test_gp_by_catnr() {
        let query = CelestrakQuery::gp().catnr(25544);
        assert_eq!(query.build_url(), "CATNR=25544");
    }

    #[test]
    fn test_gp_by_intdes() {
        let query = CelestrakQuery::gp().intdes("1998-067A");
        assert_eq!(query.build_url(), "INTDES=1998-067A");
    }

    #[test]
    fn test_gp_by_name() {
        let query = CelestrakQuery::gp().name_search("ISS");
        assert_eq!(query.build_url(), "NAME=ISS");
    }

    #[test]
    fn test_gp_with_format() {
        let query = CelestrakQuery::gp()
            .group("stations")
            .format(CelestrakOutputFormat::Json);
        assert_eq!(query.build_url(), "GROUP=stations&FORMAT=JSON");
    }

    #[test]
    fn test_gp_with_tle_format() {
        let query = CelestrakQuery::gp()
            .group("stations")
            .format(CelestrakOutputFormat::ThreeLe);
        assert_eq!(query.build_url(), "GROUP=stations&FORMAT=3LE");
    }

    #[test]
    fn test_gp_with_special() {
        let query = CelestrakQuery::gp().special("all");
        assert_eq!(query.build_url(), "SPECIAL=all");
    }

    #[test]
    fn test_gp_multiple_params() {
        let query = CelestrakQuery::gp()
            .group("stations")
            .catnr(25544)
            .format(CelestrakOutputFormat::Json);
        assert_eq!(query.build_url(), "GROUP=stations&CATNR=25544&FORMAT=JSON");
    }

    // -- SupGP URL building tests --

    #[test]
    fn test_sup_gp_by_source() {
        let query = CelestrakQuery::sup_gp().source(SupGPSource::SpaceX);
        assert_eq!(query.build_url(), "SOURCE=spacex");
    }

    #[test]
    fn test_sup_gp_by_file() {
        let query = CelestrakQuery::sup_gp().file("starlink");
        assert_eq!(query.build_url(), "FILE=starlink");
    }

    #[test]
    fn test_sup_gp_by_catnr() {
        let query = CelestrakQuery::sup_gp().catnr(25544);
        assert_eq!(query.build_url(), "CATNR=25544");
    }

    #[test]
    fn test_sup_gp_with_source_and_format() {
        let query = CelestrakQuery::sup_gp()
            .source(SupGPSource::Starlink)
            .format(CelestrakOutputFormat::Json);
        assert_eq!(query.build_url(), "SOURCE=starlink&FORMAT=JSON");
    }

    #[test]
    fn test_sup_gp_with_name() {
        let query = CelestrakQuery::sup_gp().name_search("STARLINK-1234");
        assert_eq!(query.build_url(), "NAME=STARLINK-1234");
    }

    // -- SATCAT URL building tests --

    #[test]
    fn test_satcat_by_group() {
        let query = CelestrakQuery::satcat().group("stations");
        assert_eq!(query.build_url(), "GROUP=stations");
    }

    #[test]
    fn test_satcat_active() {
        let query = CelestrakQuery::satcat().active(true);
        assert_eq!(query.build_url(), "ACTIVE=Y");
    }

    #[test]
    fn test_satcat_payloads() {
        let query = CelestrakQuery::satcat().payloads(true);
        assert_eq!(query.build_url(), "PAYLOADS=Y");
    }

    #[test]
    fn test_satcat_on_orbit() {
        let query = CelestrakQuery::satcat().on_orbit(true);
        assert_eq!(query.build_url(), "ONORBIT=Y");
    }

    #[test]
    fn test_satcat_with_max() {
        let query = CelestrakQuery::satcat().active(true).max(100);
        assert_eq!(query.build_url(), "ACTIVE=Y&MAX=100");
    }

    #[test]
    fn test_satcat_multiple_flags() {
        let query = CelestrakQuery::satcat()
            .active(true)
            .payloads(true)
            .on_orbit(true)
            .format(CelestrakOutputFormat::Json);
        assert_eq!(
            query.build_url(),
            "PAYLOADS=Y&ONORBIT=Y&ACTIVE=Y&FORMAT=JSON"
        );
    }

    #[test]
    fn test_satcat_false_flags_not_in_url() {
        let query = CelestrakQuery::satcat()
            .active(false)
            .payloads(false)
            .on_orbit(false);
        assert_eq!(query.build_url(), "");
    }

    #[test]
    fn test_satcat_by_name() {
        let query = CelestrakQuery::satcat()
            .name_search("ISS")
            .format(CelestrakOutputFormat::Json);
        assert_eq!(query.build_url(), "NAME=ISS&FORMAT=JSON");
    }

    // -- Client-side parameter tests --

    #[test]
    fn test_client_side_filter() {
        let query = CelestrakQuery::gp()
            .group("stations")
            .filter("INCLINATION", ">50");
        assert!(query.has_client_side_processing());
        assert_eq!(query.client_side_filters().len(), 1);
        assert_eq!(query.client_side_filters()[0].field, "INCLINATION");
        assert_eq!(query.client_side_filters()[0].value, ">50");
        // Client-side filters not in URL
        assert_eq!(query.build_url(), "GROUP=stations");
    }

    #[test]
    fn test_client_side_order_by() {
        let query = CelestrakQuery::gp()
            .group("stations")
            .order_by("EPOCH", false);
        assert!(query.has_client_side_processing());
        assert_eq!(query.client_side_order_by().len(), 1);
        assert_eq!(query.client_side_order_by()[0].field, "EPOCH");
        assert!(!query.client_side_order_by()[0].ascending);
    }

    #[test]
    fn test_client_side_limit() {
        let query = CelestrakQuery::gp().group("stations").limit(10);
        assert!(query.has_client_side_processing());
        assert_eq!(query.client_side_limit(), Some(10));
    }

    #[test]
    fn test_no_client_side_processing() {
        let query = CelestrakQuery::gp().group("stations");
        assert!(!query.has_client_side_processing());
    }

    #[test]
    fn test_multiple_client_side_filters() {
        let query = CelestrakQuery::gp()
            .group("active")
            .filter("INCLINATION", ">50")
            .filter("ECCENTRICITY", "<0.01")
            .filter("OBJECT_TYPE", "<>DEBRIS");
        assert_eq!(query.client_side_filters().len(), 3);
    }

    // -- Accessor tests --

    #[test]
    fn test_output_format_accessor_none() {
        let query = CelestrakQuery::gp();
        assert_eq!(query.output_format(), None);
    }

    #[test]
    fn test_output_format_accessor_set() {
        let query = CelestrakQuery::gp().format(CelestrakOutputFormat::Json);
        assert_eq!(query.output_format(), Some(CelestrakOutputFormat::Json));
    }

    // -- Builder immutability tests --

    #[test]
    fn test_builder_immutability() {
        let base = CelestrakQuery::gp().group("stations");
        let extended = base.clone().filter("INCLINATION", ">50");

        // Base query should not be affected by extending
        assert!(!base.has_client_side_processing());
        assert!(extended.has_client_side_processing());
        assert_eq!(base.build_url(), "GROUP=stations");
        assert_eq!(extended.build_url(), "GROUP=stations");
    }

    // -- Clone tests --

    #[test]
    fn test_query_clone() {
        let query = CelestrakQuery::gp()
            .group("stations")
            .filter("INCLINATION", ">50")
            .order_by("EPOCH", false)
            .limit(10);

        let cloned = query.clone();
        assert_eq!(query.build_url(), cloned.build_url());
        assert_eq!(query.query_type(), cloned.query_type());
        assert_eq!(
            query.client_side_filters().len(),
            cloned.client_side_filters().len()
        );
        assert_eq!(
            query.client_side_order_by().len(),
            cloned.client_side_order_by().len()
        );
        assert_eq!(query.client_side_limit(), cloned.client_side_limit());
    }

    // -- All format tests --

    #[test]
    fn test_all_output_formats() {
        let formats = vec![
            (CelestrakOutputFormat::Tle, "FORMAT=TLE"),
            (CelestrakOutputFormat::TwoLe, "FORMAT=2LE"),
            (CelestrakOutputFormat::ThreeLe, "FORMAT=3LE"),
            (CelestrakOutputFormat::Xml, "FORMAT=XML"),
            (CelestrakOutputFormat::Kvn, "FORMAT=KVN"),
            (CelestrakOutputFormat::Json, "FORMAT=JSON"),
            (CelestrakOutputFormat::JsonPretty, "FORMAT=JSON-PRETTY"),
            (CelestrakOutputFormat::Csv, "FORMAT=CSV"),
        ];

        for (format, expected) in formats {
            let query = CelestrakQuery::gp().format(format);
            assert_eq!(query.build_url(), expected);
        }
    }

    // -- Empty query test --

    #[test]
    fn test_empty_query() {
        let query = CelestrakQuery::gp();
        assert_eq!(query.build_url(), "");
    }

    // -- Debug test --

    #[test]
    fn test_query_debug() {
        let query = CelestrakQuery::gp().group("stations");
        let debug = format!("{:?}", query);
        assert!(debug.contains("stations"));
        assert!(debug.contains("GP"));
    }
}