librus-rs 2.0.1

Rust client for Librus Synergia - the Polish school diary system
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
1156
1157
//! # librus-rs
//!
//! Rust client for [Librus Synergia](https://synergia.librus.pl/) - the Polish school diary system.
//!
//! This crate provides an async API client for accessing student grades, attendance,
//! messages, and other data from Librus Synergia.
//!
//! # Quick Start
//!
//! ```rust,no_run
//! use librus_rs::Client;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), librus_rs::Error> {
//!     // Create client from environment variables
//!     let mut client = Client::from_env().await?;
//!
//!     // Fetch grades
//!     let grades = client.grades().await?;
//!     for grade in grades.grades {
//!         println!("{}: {}", grade.date, grade.grade);
//!     }
//!
//!     // Fetch unread message count
//!     let unread = client.unread_counts().await?;
//!     println!("Unread messages: {}", unread.inbox);
//!
//!     Ok(())
//! }
//! ```
//!
//! # Client Construction
//!
//! There are three ways to create a [`Client`]:
//!
//! ## From Environment Variables
//!
//! Reads `LIBRUS_USERNAME` and `LIBRUS_PASSWORD` from the environment:
//!
//! ```rust,no_run
//! use librus_rs::Client;
//!
//! # async fn example() -> Result<(), librus_rs::Error> {
//! let client = Client::from_env().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## With Explicit Credentials
//!
//! ```rust,no_run
//! use librus_rs::Client;
//!
//! # async fn example() -> Result<(), librus_rs::Error> {
//! let client = Client::new("username", "password").await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Using the Builder Pattern
//!
//! ```rust,no_run
//! use librus_rs::Client;
//!
//! # async fn example() -> Result<(), librus_rs::Error> {
//! let client = Client::builder()
//!     .username("username")
//!     .password("password")
//!     .build()
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! # API Overview
//!
//! The client provides access to two APIs:
//!
//! ## Synergia API
//!
//! Academic data including grades, attendance, lessons, and users.
//!
//! | Method | Description |
//! |--------|-------------|
//! | [`Client::me()`] | Current user info |
//! | [`Client::grades()`] | All grades |
//! | [`Client::grade_category()`] | Grade category by ID |
//! | [`Client::grade_comment()`] | Grade comment by ID |
//! | [`Client::lesson()`] | Lesson info by ID |
//! | [`Client::subject()`] | Subject info by ID |
//! | [`Client::attendances()`] | All attendances |
//! | [`Client::attendance_types()`] | Attendance types |
//! | [`Client::homeworks()`] | All homeworks |
//! | [`Client::school_notices()`] | School notices (announcements) |
//! | [`Client::user()`] | User by ID |
//! | [`Client::current_user()`] | Current user details |
//!
//! ## Messages API
//!
//! Internal messaging system.
//!
//! | Method | Description |
//! |--------|-------------|
//! | [`Client::unread_counts()`] | Unread message counts |
//! | [`Client::inbox_messages()`] | Received messages |
//! | [`Client::outbox_messages()`] | Sent messages |
//! | [`Client::message()`] | Full message details |
//! | [`Client::attachment()`] | Download attachment |
//!
//! # Error Handling
//!
//! All API methods return `Result<T, Error>`. See [`Error`] for possible error variants.
//!
//! ```rust,no_run
//! use librus_rs::{Client, Error};
//!
//! # async fn example() {
//! let result = Client::from_env().await;
//! match result {
//!     Ok(client) => println!("Authenticated successfully"),
//!     Err(Error::MissingEnvVar(var)) => eprintln!("Missing: {}", var),
//!     Err(Error::Authentication) => eprintln!("Invalid credentials"),
//!     Err(e) => eprintln!("Error: {}", e),
//! }
//! # }
//! ```

mod error;
mod structs;

use reqwest::Client as HttpClient;

pub use crate::error::Error;
pub use crate::structs::announcements::{ResponseSchoolNotices, SchoolNotice};
pub use crate::structs::events::{Homework, ResponseHomeworks};
pub use crate::structs::grades::{
    Grade, GradeCategory, GradeComment, ResponseGrades, ResponseGradesCategories,
    ResponseGradesComments,
};
pub use crate::structs::lessons::{
    Attendance, AttendanceType, Lesson, LessonSubject, ResponseAttendances,
    ResponseAttendancesType, ResponseLesson, ResponseLessonSubject,
};
pub use crate::structs::me::{Me, ResponseMe};
pub use crate::structs::messages::{
    Attachment, InboxMessage, MessageDetail, OutboxMessage, UnreadCounts,
};
pub use crate::structs::users::{ResponseUser, User};

use crate::structs::messages::{
    ResponseInboxMessages, ResponseMessageDetail, ResponseOutboxMessages, ResponseUnreadCounts,
};

/// A specialized `Result` type for librus-rs operations.
pub type Result<T> = std::result::Result<T, Error>;

const SYNERGIA_API_BASE: &str = "https://synergia.librus.pl/gateway/api/2.0/";
const MESSAGES_API_BASE: &str = "https://wiadomosci.librus.pl/api/";
const AUTH_URL: &str = "https://api.librus.pl/OAuth/Authorization?client_id=46";
const AUTH_TEST_URL: &str =
    "https://api.librus.pl/OAuth/Authorization?client_id=46&response_type=code&scope=mydata";
const AUTH_GRANT_URL: &str = "https://api.librus.pl/OAuth/Authorization/Grant?client_id=46";
const TOKEN_INFO_URL: &str = "https://synergia.librus.pl/gateway/api/2.0/Auth/TokenInfo/";
const MESSAGES_INIT_URL: &str = "https://synergia.librus.pl/wiadomosci3";

/// Builder for creating a [`Client`] instance with custom configuration.
///
/// # Example
///
/// ```rust,no_run
/// use librus_rs::ClientBuilder;
///
/// # async fn example() -> Result<(), librus_rs::Error> {
/// let client = ClientBuilder::new()
///     .username("my_username")
///     .password("my_password")
///     .build()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Default)]
pub struct ClientBuilder {
    username: Option<String>,
    password: Option<String>,
}

impl ClientBuilder {
    /// Creates a new builder instance with no credentials set.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the Librus username.
    ///
    /// # Example
    ///
    /// ```rust
    /// use librus_rs::ClientBuilder;
    ///
    /// let builder = ClientBuilder::new().username("my_username");
    /// ```
    pub fn username(mut self, username: impl Into<String>) -> Self {
        self.username = Some(username.into());
        self
    }

    /// Sets the Librus password.
    ///
    /// # Example
    ///
    /// ```rust
    /// use librus_rs::ClientBuilder;
    ///
    /// let builder = ClientBuilder::new()
    ///     .username("my_username")
    ///     .password("my_password");
    /// ```
    pub fn password(mut self, password: impl Into<String>) -> Self {
        self.password = Some(password.into());
        self
    }

    /// Builds and authenticates the client.
    ///
    /// This method consumes the builder and attempts to authenticate with Librus.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Username is missing ([`Error::MissingCredentials`])
    /// - Password is missing ([`Error::MissingCredentials`])
    /// - Authentication fails ([`Error::Authentication`])
    /// - Network error occurs ([`Error::Request`])
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::ClientBuilder;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = ClientBuilder::new()
    ///     .username("my_username")
    ///     .password("my_password")
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn build(self) -> Result<Client> {
        let username = self.username.ok_or(Error::MissingCredentials("username"))?;
        let password = self.password.ok_or(Error::MissingCredentials("password"))?;
        Client::authenticate(&username, &password).await
    }
}

/// An authenticated Librus API client.
///
/// This is the main entry point for interacting with Librus Synergia.
/// Create a client using one of the constructor methods, then call API methods
/// to fetch data.
///
/// # Example
///
/// ```rust,no_run
/// use librus_rs::Client;
///
/// #[tokio::main]
/// async fn main() -> Result<(), librus_rs::Error> {
///     let mut client = Client::from_env().await?;
///
///     // Fetch user info
///     let me = client.me().await?;
///     println!("Logged in as: {} {}", me.me.user.first_name, me.me.user.last_name);
///
///     // Fetch grades
///     let grades = client.grades().await?;
///     println!("Total grades: {}", grades.grades.len());
///
///     Ok(())
/// }
/// ```
pub struct Client {
    http: HttpClient,
    messages_initialized: bool,
}

impl Client {
    /// Creates a new client from environment variables.
    ///
    /// Reads `LIBRUS_USERNAME` and `LIBRUS_PASSWORD` from the environment
    /// and authenticates with Librus.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `LIBRUS_USERNAME` is not set ([`Error::MissingEnvVar`])
    /// - `LIBRUS_PASSWORD` is not set ([`Error::MissingEnvVar`])
    /// - Authentication fails ([`Error::Authentication`])
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// // Ensure LIBRUS_USERNAME and LIBRUS_PASSWORD are set
    /// let client = Client::from_env().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn from_env() -> Result<Self> {
        let username = std::env::var("LIBRUS_USERNAME")
            .map_err(|_| Error::MissingEnvVar("LIBRUS_USERNAME"))?;
        let password = std::env::var("LIBRUS_PASSWORD")
            .map_err(|_| Error::MissingEnvVar("LIBRUS_PASSWORD"))?;
        Self::authenticate(&username, &password).await
    }

    /// Creates a new client with explicit credentials.
    ///
    /// # Errors
    ///
    /// Returns an error if authentication fails ([`Error::Authentication`])
    /// or a network error occurs ([`Error::Request`]).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::new("username", "password").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new(username: &str, password: &str) -> Result<Self> {
        Self::authenticate(username, password).await
    }

    /// Creates a builder for configuring the client.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::builder()
    ///     .username("username")
    ///     .password("password")
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    async fn authenticate(username: &str, password: &str) -> Result<Self> {
        let http = HttpClient::builder()
            .cookie_store(true)
            .build()
            .map_err(Error::HttpClient)?;

        let form_params = [("action", "login"), ("login", username), ("pass", password)];

        http.get(AUTH_TEST_URL)
            .send()
            .await
            .map_err(Error::Request)?;

        http.post(AUTH_URL)
            .form(&form_params)
            .send()
            .await
            .map_err(Error::Request)?;

        http.get(AUTH_GRANT_URL)
            .send()
            .await
            .map_err(Error::Request)?;

        let token_response = http
            .get(TOKEN_INFO_URL)
            .send()
            .await
            .map_err(Error::Request)?;

        if token_response.status() != 200 {
            return Err(Error::Authentication);
        }

        Ok(Self {
            http,
            messages_initialized: false,
        })
    }

    async fn get_api(&self, endpoint: &str) -> Result<String> {
        let url = format!("{}{}", SYNERGIA_API_BASE, endpoint);
        let response = self
            .http
            .get(&url)
            .header("Content-Type", "application/json")
            .send()
            .await
            .map_err(Error::Request)?;

        let status = response.status();
        let text = response.text().await.map_err(Error::Request)?;

        if !status.is_success() {
            return Err(Error::ApiError {
                status: status.as_u16(),
                body: text,
            });
        }

        Ok(text)
    }

    async fn get_messages_api(&self, endpoint: &str) -> Result<String> {
        let url = format!("{}{}", MESSAGES_API_BASE, endpoint);
        let response = self.http.get(&url).send().await.map_err(Error::Request)?;

        let status = response.status();
        let text = response.text().await.map_err(Error::Request)?;

        if !status.is_success() {
            return Err(Error::ApiError {
                status: status.as_u16(),
                body: text,
            });
        }

        Ok(text)
    }

    async fn ensure_messages_initialized(&mut self) -> Result<()> {
        if self.messages_initialized {
            return Ok(());
        }
        self.http
            .get(MESSAGES_INIT_URL)
            .send()
            .await
            .map_err(Error::Request)?;
        self.messages_initialized = true;
        Ok(())
    }

    /// Gets current user information.
    ///
    /// Returns account details, user profile, and class information.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let me = client.me().await?;
    /// println!("User: {} {}", me.me.user.first_name, me.me.user.last_name);
    /// println!("Email: {}", me.me.account.email);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn me(&self) -> Result<ResponseMe> {
        let json = self.get_api("Me").await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets all grades for the student.
    ///
    /// Returns a list of all grades across all subjects.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let grades = client.grades().await?;
    /// for grade in grades.grades {
    ///     println!("{}: {} ({})", grade.date, grade.grade, grade.semester);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn grades(&self) -> Result<ResponseGrades> {
        let json = self.get_api("Grades").await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets a grade category by ID.
    ///
    /// Categories describe the type of grade (e.g., test, homework, quiz).
    ///
    /// # Arguments
    ///
    /// * `id` - The category ID from a [`Grade`]'s `category` field
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the category is not found.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let category = client.grade_category(123).await?;
    /// println!("Category: {}", category.category.name);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn grade_category(&self, id: i32) -> Result<ResponseGradesCategories> {
        let json = self.get_api(&format!("Grades/Categories/{}", id)).await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets a grade comment by ID.
    ///
    /// Comments provide additional context for a grade.
    ///
    /// # Arguments
    ///
    /// * `id` - The comment ID from a [`Grade`]'s `comments` field
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the comment is not found.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let comment = client.grade_comment(456).await?;
    /// if let Some(c) = comment.comment {
    ///     println!("Comment: {}", c.text);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn grade_comment(&self, id: i32) -> Result<ResponseGradesComments> {
        let json = self.get_api(&format!("Grades/Comments/{}", id)).await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets a lesson by ID.
    ///
    /// Lessons contain information about which teacher teaches which subject to which class.
    ///
    /// # Arguments
    ///
    /// * `id` - The lesson ID
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the lesson is not found.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let lesson = client.lesson(789).await?;
    /// println!("Lesson ID: {}", lesson.lesson.id);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn lesson(&self, id: i32) -> Result<ResponseLesson> {
        let json = self.get_api(&format!("Lessons/{}", id)).await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets a subject by ID.
    ///
    /// Subjects contain the name and short code for academic subjects.
    ///
    /// # Arguments
    ///
    /// * `id` - The subject ID
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the subject is not found.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let subject = client.subject(101).await?;
    /// if let Some(s) = subject.subject {
    ///     println!("Subject: {} ({})", s.name, s.short);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn subject(&self, id: i32) -> Result<ResponseLessonSubject> {
        let json = self.get_api(&format!("Subjects/{}", id)).await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets all attendances for the student.
    ///
    /// Returns attendance records for all lessons.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let attendances = client.attendances().await?;
    /// println!("Total records: {}", attendances.attendances.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn attendances(&self) -> Result<ResponseAttendances> {
        let json = self.get_api("Attendances/").await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets all attendance types.
    ///
    /// Types describe the kind of attendance (present, absent, late, etc.).
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let types = client.attendance_types().await?;
    /// for t in types.types {
    ///     println!("{}: {} ({})", t.id, t.name, t.short);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn attendance_types(&self) -> Result<ResponseAttendancesType> {
        let json = self.get_api("Attendances/Types/").await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets all homeworks.
    ///
    /// Returns a list of all homework assignments.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let homeworks = client.homeworks().await?;
    /// for hw in homeworks.homeworks {
    ///     println!("{}: {}", hw.date, hw.content);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn homeworks(&self) -> Result<ResponseHomeworks> {
        let json = self.get_api("HomeWorks/").await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets school notices (announcements).
    ///
    /// Returns a list of school notices.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let notices = client.school_notices().await?;
    /// for notice in notices.school_notices {
    ///     println!("{}: {}", notice.creation_date, notice.subject);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn school_notices(&self) -> Result<ResponseSchoolNotices> {
        let json = self.get_api("SchoolNotices").await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets school notices (announcements) with pagination.
    ///
    /// # Arguments
    ///
    /// * `page` - Page number (1-indexed)
    /// * `limit` - Number of notices per page
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    pub async fn school_notices_page(
        &self,
        page: u32,
        limit: u32,
    ) -> Result<ResponseSchoolNotices> {
        let endpoint = format!("SchoolNotices?page={}&limit={}", page, limit);
        let json = self.get_api(&endpoint).await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets the latest school notices (announcements).
    ///
    /// This paginates through all notices, sorts them by `creation_date` (descending),
    /// and returns the newest `limit` items.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    pub async fn school_notices_latest(&self, limit: usize) -> Result<Vec<SchoolNotice>> {
        if limit == 0 {
            return Ok(Vec::new());
        }

        let page_size: u32 = 50;
        let mut page = 1;
        let mut all = Vec::new();

        loop {
            let resp = self.school_notices_page(page, page_size).await?;
            if resp.school_notices.is_empty() {
                break;
            }

            let count = resp.school_notices.len();
            all.extend(resp.school_notices);

            if count < page_size as usize {
                break;
            }

            page += 1;
        }

        all.sort_by(|a, b| b.creation_date.cmp(&a.creation_date));
        all.truncate(limit);
        Ok(all)
    }

    /// Gets a user by ID.
    ///
    /// Users include teachers, students, and parents.
    ///
    /// # Arguments
    ///
    /// * `id` - The user ID
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the user is not found.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let client = Client::from_env().await?;
    /// let user = client.user(12345).await?;
    /// if let Some(u) = user.user {
    ///     println!("{} {}", u.first_name, u.last_name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn user(&self, id: i32) -> Result<ResponseUser> {
        let json = self.get_api(&format!("Users/{}", id)).await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets current user details.
    ///
    /// Returns detailed information about the authenticated user.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    pub async fn current_user(&self) -> Result<ResponseUser> {
        let json = self.get_api("Users").await?;
        serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })
    }

    /// Gets unread message counts for all folders.
    ///
    /// Returns counts for inbox, notes, alerts, and other message categories.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let mut client = Client::from_env().await?;
    /// let counts = client.unread_counts().await?;
    /// println!("Unread inbox: {}", counts.inbox);
    /// println!("Unread alerts: {}", counts.alerts);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn unread_counts(&mut self) -> Result<UnreadCounts> {
        self.ensure_messages_initialized().await?;
        let json = self.get_messages_api("inbox/unreadMessagesCount").await?;
        let resp: ResponseUnreadCounts = serde_json::from_str(&json).map_err(|e| Error::Parse {
            source: e,
            body: json,
        })?;
        Ok(resp.data)
    }

    /// Gets inbox messages (received).
    ///
    /// # Arguments
    ///
    /// * `page` - Page number (1-indexed)
    /// * `limit` - Number of messages per page
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let mut client = Client::from_env().await?;
    /// let messages = client.inbox_messages(1, 10).await?;
    /// for msg in messages {
    ///     println!("{}: {}", msg.sender_name, msg.topic);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn inbox_messages(&mut self, page: u32, limit: u32) -> Result<Vec<InboxMessage>> {
        self.ensure_messages_initialized().await?;
        let endpoint = format!("inbox/messages?page={}&limit={}", page, limit);
        let json = self.get_messages_api(&endpoint).await?;
        let resp: ResponseInboxMessages =
            serde_json::from_str(&json).map_err(|e| Error::Parse {
                source: e,
                body: json,
            })?;
        Ok(resp.data)
    }

    /// Gets outbox messages (sent).
    ///
    /// # Arguments
    ///
    /// * `page` - Page number (1-indexed)
    /// * `limit` - Number of messages per page
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response parsing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let mut client = Client::from_env().await?;
    /// let messages = client.outbox_messages(1, 10).await?;
    /// for msg in messages {
    ///     println!("To {}: {}", msg.receiver_name, msg.topic);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn outbox_messages(&mut self, page: u32, limit: u32) -> Result<Vec<OutboxMessage>> {
        self.ensure_messages_initialized().await?;
        let endpoint = format!("outbox/messages?page={}&limit={}", page, limit);
        let json = self.get_messages_api(&endpoint).await?;
        let resp: ResponseOutboxMessages =
            serde_json::from_str(&json).map_err(|e| Error::Parse {
                source: e,
                body: json,
            })?;
        Ok(resp.data)
    }

    /// Gets full message details by ID.
    ///
    /// Returns the complete message including body content and attachments.
    ///
    /// # Arguments
    ///
    /// * `message_id` - The message ID from an [`InboxMessage`] or [`OutboxMessage`]
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the message is not found.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let mut client = Client::from_env().await?;
    /// let detail = client.message("12345").await?;
    /// if let Some(content) = Client::decode_message_content(&detail.message) {
    ///     println!("Content: {}", content);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn message(&mut self, message_id: &str) -> Result<MessageDetail> {
        self.ensure_messages_initialized().await?;
        let endpoint = format!("inbox/messages/{}", message_id);
        let json = self.get_messages_api(&endpoint).await?;
        let resp: ResponseMessageDetail =
            serde_json::from_str(&json).map_err(|e| Error::Parse {
                source: e,
                body: json,
            })?;
        Ok(resp.data)
    }

    /// Downloads attachment bytes.
    ///
    /// # Arguments
    ///
    /// * `attachment_id` - The attachment ID from a [`MessageDetail`]'s attachments
    /// * `message_id` - The message ID containing the attachment
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the attachment is not found.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use librus_rs::Client;
    /// use std::fs;
    ///
    /// # async fn example() -> Result<(), librus_rs::Error> {
    /// let mut client = Client::from_env().await?;
    /// let detail = client.message("12345").await?;
    /// for attachment in &detail.attachments {
    ///     let bytes = client.attachment(&attachment.id, &detail.message_id).await?;
    ///     fs::write(&attachment.name, &bytes).expect("Failed to save file");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn attachment(&mut self, attachment_id: &str, message_id: &str) -> Result<Vec<u8>> {
        self.ensure_messages_initialized().await?;
        let url = format!(
            "https://wiadomosci.librus.pl/api/attachments/{}/messages/{}",
            attachment_id, message_id
        );
        let response = self.http.get(&url).send().await.map_err(Error::Request)?;

        let status = response.status();
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(Error::ApiError {
                status: status.as_u16(),
                body,
            });
        }

        let bytes = response.bytes().await.map_err(Error::Request)?;
        Ok(bytes.to_vec())
    }

    /// Decodes base64-encoded message content to a string.
    ///
    /// Message bodies in Librus are base64-encoded. Use this helper to decode them.
    ///
    /// # Arguments
    ///
    /// * `content` - The base64-encoded content string
    ///
    /// # Returns
    ///
    /// `Some(String)` if decoding succeeds, `None` if the content is invalid.
    ///
    /// # Example
    ///
    /// ```rust
    /// use librus_rs::Client;
    ///
    /// let encoded = "SGVsbG8sIFdvcmxkIQ==";
    /// let decoded = Client::decode_message_content(encoded);
    /// assert_eq!(decoded, Some("Hello, World!".to_string()));
    /// ```
    pub fn decode_message_content(content: &str) -> Option<String> {
        use base64::{engine::general_purpose::STANDARD, Engine};
        STANDARD
            .decode(content)
            .ok()
            .and_then(|bytes| String::from_utf8(bytes).ok())
    }

    /// Formats API-provided HTML content into readable text.
    ///
    /// School notices (announcements) are often HTML-formatted. This helper removes tags
    /// and performs a minimal entity decode to make the content readable.
    ///
    /// # Example
    ///
    /// ```rust
    /// use librus_rs::Client;
    ///
    /// let html = "<p>Hello&nbsp;<b>World</b> &amp; friends</p>";
    /// let text = Client::notice_content_to_text(html);
    /// assert_eq!(text, "Hello World & friends");
    /// ```
    pub fn notice_content_to_text(content: &str) -> String {
        let mut out = String::with_capacity(content.len());
        let mut in_tag = false;

        for ch in content.chars() {
            match ch {
                '<' => in_tag = true,
                '>' => in_tag = false,
                _ if !in_tag => out.push(ch),
                _ => {}
            }
        }

        // Minimal entity decoding for common cases.
        let out = out
            .replace("&nbsp;", " ")
            .replace("&amp;", "&")
            .replace("&lt;", "<")
            .replace("&gt;", ">")
            .replace("&quot;", "\"")
            .replace("&#39;", "'");

        out.trim().to_string()
    }
}

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

    #[test]
    fn test_decode_message_content() {
        let encoded = base64::engine::general_purpose::STANDARD.encode("Hello, World!");
        let decoded = Client::decode_message_content(&encoded);
        assert_eq!(decoded, Some("Hello, World!".to_string()));
    }

    #[test]
    fn test_decode_invalid_content() {
        let decoded = Client::decode_message_content("not valid base64!!!");
        assert!(decoded.is_none());
    }

    #[test]
    fn test_notice_content_to_text() {
        let html = "<p>Hello&nbsp;<b>World</b> &amp; friends</p>";
        let text = Client::notice_content_to_text(html);
        assert_eq!(text, "Hello World & friends");
    }
}