archivist-core 0.2.0

Platform-neutral core for the FicHub companion bot: FicHub REST API client, search/recommendation/download command logic, intent classification, pagination cache, and the PlatformMessage IR. Shared by every platform adapter (Discord, Telegram, Matrix, Slack, IRC, fediverse, CLI, web).
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
//! Typed response models matching the FicHub REST API.
//!
//! Shapes mirror `frontend/src/lib/api/types.ts` (the frontend is the
//! authoritative contract). Fields are `Option` where the API can omit them.

use serde::{Deserialize, Serialize};

/// A single export's download URLs.
/// Keys: epub, html, txt, md, mobi, pdf, azw3, docx, fb2, kepub.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ExportUrls {
    /// EPUB download URL, if the API produced one.
    #[serde(default)]
    pub epub: Option<String>,
    /// HTML download URL, if the API produced one.
    #[serde(default)]
    pub html: Option<String>,
    /// Plain-text download URL, if the API produced one.
    #[serde(default)]
    pub txt: Option<String>,
    /// Markdown download URL, if the API produced one.
    #[serde(default)]
    pub md: Option<String>,
    /// MOBI download URL, if the API produced one.
    #[serde(default)]
    pub mobi: Option<String>,
    /// PDF download URL, if the API produced one.
    #[serde(default)]
    pub pdf: Option<String>,
    /// AZW3 download URL, if the API produced one.
    #[serde(default)]
    pub azw3: Option<String>,
    /// DOCX download URL, if the API produced one.
    #[serde(default)]
    pub docx: Option<String>,
    /// FB2 download URL, if the API produced one.
    #[serde(default)]
    pub fb2: Option<String>,
    /// KEPUB download URL, if the API produced one.
    #[serde(default)]
    pub kepub: Option<String>,
}

impl ExportUrls {
    /// The preferred download URL for a human: EPUB, else first available.
    pub fn preferred(&self) -> Option<(String, String)> {
        if let Some(e) = &self.epub {
            return Some(("epub".to_string(), e.clone()));
        }
        self.first()
    }

    /// First available (format, url) pair.
    pub fn first(&self) -> Option<(String, String)> {
        macro_rules! try_fmt {
            ($name:literal, $field:ident) => {
                if let Some(u) = &self.$field {
                    return Some(($name.to_string(), u.clone()));
                }
            };
        }
        try_fmt!("html", html);
        try_fmt!("txt", txt);
        try_fmt!("md", md);
        try_fmt!("mobi", mobi);
        try_fmt!("pdf", pdf);
        try_fmt!("azw3", azw3);
        try_fmt!("docx", docx);
        try_fmt!("fb2", fb2);
        try_fmt!("kepub", kepub);
        None
    }

    /// List of (format, url) pairs currently available.
    pub fn available(&self) -> Vec<(String, String)> {
        let mut out = Vec::new();
        macro_rules! push {
            ($name:literal, $field:ident) => {
                if let Some(u) = &self.$field {
                    out.push(($name.to_string(), u.clone()));
                }
            };
        }
        push!("epub", epub);
        push!("html", html);
        push!("txt", txt);
        push!("md", md);
        push!("mobi", mobi);
        push!("pdf", pdf);
        push!("azw3", azw3);
        push!("docx", docx);
        push!("fb2", fb2);
        push!("kepub", kepub);
        out
    }
}

/// Fic metadata object returned by `/api/epub` and `/api/meta`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FicMeta {
    /// FicHub url id (string form).
    pub id: String,
    /// Numeric work id, when known.
    #[serde(default)]
    pub work_id: Option<i64>,
    /// Work title.
    pub title: String,
    /// Author display name.
    pub author: String,
    /// Number of chapters.
    pub chapters: i64,
    /// Word count.
    pub words: i64,
    /// Work description/summary.
    pub description: String,
    /// Status string (e.g. `complete`, `in-progress`).
    pub status: String,
    /// Source site domain.
    pub source: String,
    /// ISO timestamp of original publication.
    pub created: String,
    /// ISO timestamp of last update.
    pub updated: String,
    /// Site-specific extra metadata, when the API provides it.
    #[serde(default)]
    pub extra_meta: Option<serde_json::Value>,
    /// Raw extended metadata object, when the API provides it.
    #[serde(default)]
    pub raw_extended_meta: Option<serde_json::Value>,
    /// Author profile URL on the source site.
    pub author_url: String,
    /// Author id within the source site.
    pub author_local_id: String,
    /// FicHub source id.
    pub source_id: i64,
    /// FicHub author id.
    pub author_id: i64,
}

/// Response from `GET /api/epub?q=` and `GET /api/meta?q=`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ExportResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Echoed query, when present.
    #[serde(default)]
    pub q: Option<String>,
    /// Error/notice message, when present.
    #[serde(default)]
    pub msg: Option<String>,
    /// FicHub url id of the work.
    #[serde(default)]
    pub url_id: Option<String>,
    /// URL slug, when present.
    #[serde(default)]
    pub slug: Option<String>,
    /// Fic metadata, when the API returned it.
    #[serde(default)]
    pub meta: Option<FicMeta>,
    /// Per-format content hashes, when present.
    #[serde(default)]
    pub hashes: Option<serde_json::Map<String, serde_json::Value>>,
    /// Structured download URLs (newer API shape).
    #[serde(default)]
    pub urls: Option<ExportUrls>,
    /// Legacy flat EPUB URL (older API shape).
    #[serde(default)]
    pub epub_url: Option<String>,
    /// Legacy flat HTML URL (older API shape).
    #[serde(default)]
    pub html_url: Option<String>,
    /// Legacy flat TXT URL (older API shape).
    #[serde(default)]
    pub txt_url: Option<String>,
    /// Legacy flat MD URL (older API shape).
    #[serde(default)]
    pub md_url: Option<String>,
    /// Legacy flat MOBI URL (older API shape).
    #[serde(default)]
    pub mobi_url: Option<String>,
    /// Legacy flat PDF URL (older API shape).
    #[serde(default)]
    pub pdf_url: Option<String>,
    /// Legacy flat AZW3 URL (older API shape).
    #[serde(default)]
    pub azw3_url: Option<String>,
    /// Legacy flat DOCX URL (older API shape).
    #[serde(default)]
    pub docx_url: Option<String>,
    /// Legacy flat FB2 URL (older API shape).
    #[serde(default)]
    pub fb2_url: Option<String>,
    /// Legacy flat KEPUB URL (older API shape).
    #[serde(default)]
    pub kepub_url: Option<String>,
    /// Download notes, when present.
    #[serde(default)]
    pub notes: Option<Vec<String>>,
}

impl ExportResponse {
    /// Build a flat ExportUrls from the `*_url` fields (older API shape).
    pub fn flat_urls(&self) -> ExportUrls {
        ExportUrls {
            epub: self.epub_url.clone(),
            html: self.html_url.clone(),
            txt: self.txt_url.clone(),
            md: self.md_url.clone(),
            mobi: self.mobi_url.clone(),
            pdf: self.pdf_url.clone(),
            azw3: self.azw3_url.clone(),
            docx: self.docx_url.clone(),
            fb2: self.fb2_url.clone(),
            kepub: self.kepub_url.clone(),
        }
    }
}

/// Response from `GET /api/epub/convert?format=mobi|pdf|azw3`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ConvertResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Echoed query, when present.
    #[serde(default)]
    pub q: Option<String>,
    /// Error/notice message, when present.
    #[serde(default)]
    pub msg: Option<String>,
    /// FicHub url id of the work.
    #[serde(default)]
    pub url_id: Option<String>,
    /// Requested output format.
    #[serde(default)]
    pub format: Option<String>,
    /// Hash of the produced file, when present.
    #[serde(default)]
    pub hash: Option<String>,
    /// Download URL for the converted file.
    #[serde(default)]
    pub url: Option<String>,
    /// Whether the conversion was served from cache.
    #[serde(default)]
    pub cached: Option<bool>,
    /// Conversion duration in milliseconds.
    #[serde(default)]
    pub elapsed_ms: Option<i64>,
}

/// A single recommendation result.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct RecResult {
    /// FicHub url id.
    pub url_id: String,
    /// Work title.
    pub title: String,
    /// Author display name.
    pub author: String,
    /// Word count.
    #[serde(default)]
    pub words: i64,
    /// Chapter count.
    #[serde(default)]
    pub chapters: i64,
    /// Status string (e.g. `complete`).
    #[serde(default)]
    pub status: String,
    /// Source site domain.
    #[serde(default)]
    pub site_domain: String,
    /// Short summary/description.
    #[serde(default)]
    pub summary: String,
    /// Recommendation score (0..1).
    #[serde(default)]
    pub score: f64,
    /// Community-driven score.
    #[serde(default)]
    pub community_score: f64,
    /// Per-format download URLs, when present.
    #[serde(default)]
    pub download_urls: serde_json::Map<String, serde_json::Value>,
}

/// Response from `GET /api/recommendations?q=&n=`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RecommendationsResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Source fic url id the recs were computed for.
    #[serde(default)]
    pub url_id: String,
    /// Source site domain, when present.
    #[serde(default)]
    pub site_domain: Option<String>,
    /// Recommended works.
    #[serde(default)]
    pub recommendations: Vec<RecResult>,
    /// ISO timestamp when the recs were generated.
    #[serde(default)]
    pub generated_at: String,
}

/// Personal recommendations response (`GET /api/recommendations/personal`).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PersonalRecommendationsResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Whether the user's history was enough to compute recs.
    #[serde(default)]
    pub enough_data: bool,
    /// Recommended works.
    #[serde(default)]
    pub recs: Vec<RecResult>,
    /// `[{ "title": ..., "url_id": ... }, ...]` — what the recs were based on.
    #[serde(default)]
    pub based_on: Vec<serde_json::Value>,
    /// Pluggable-mode diagnostics (`strategies`, `curator_alpha`, ...).
    #[serde(default)]
    pub strategies: Vec<serde_json::Value>,
}

/// A community suggestion for a fic (`GET /api/recommendations/votes`).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Suggestion {
    /// Suggestion id.
    pub id: i64,
    /// Suggested work's url id.
    pub suggested_url_id: String,
    /// Optional comment explaining the suggestion.
    #[serde(default)]
    pub comment: Option<String>,
    /// Net vote count.
    pub net_votes: i64,
    /// ISO timestamp, when present.
    #[serde(default)]
    pub created: Option<String>,
}

/// Response from `GET /api/recommendations/votes?url_id=`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct VotesResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Source fic url id.
    pub url_id: String,
    /// Community suggestions.
    #[serde(default)]
    pub suggestions: Vec<Suggestion>,
}

/// A search result row (`GET /api/search`, `POST /api/search/ask`).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SearchResult {
    /// FicHub url id.
    pub url_id: String,
    /// Work title.
    pub title: String,
    /// Author display name.
    pub author: String,
    /// Source site domain.
    pub source: String,
    /// Word count.
    pub words: i64,
    /// Chapter count.
    pub chapters: i64,
    /// Status string (e.g. `complete`).
    pub status: String,
    /// Work description.
    pub description: String,
    /// ISO timestamp of last update, when present.
    #[serde(default)]
    pub updated: Option<String>,
    /// Relevance rank, when present.
    #[serde(default)]
    pub rank: Option<f64>,
    /// Highlighted snippet, when present.
    #[serde(default)]
    pub snippet: Option<String>,
    /// Tags attached to the work.
    #[serde(default)]
    pub tags: Vec<serde_json::Value>,
    /// Freeform tag count on the work.
    #[serde(default)]
    pub total_freeform: usize,
    /// Comment count.
    #[serde(default)]
    pub comment_count: i64,
    /// Kudos count.
    #[serde(default)]
    pub kudos_count: i64,
}

/// Search facets (`GET /api/search`).
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct SearchFacets {
    /// Available fandom facets.
    #[serde(default)]
    pub fandoms: Vec<serde_json::Value>,
    /// Available tag facets.
    #[serde(default)]
    pub tags: Vec<serde_json::Value>,
}

/// Response envelope from `GET /api/search`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SearchResponse {
    /// Total matching works.
    pub total: i64,
    /// Current page (1-based).
    pub page: usize,
    /// Results per page.
    pub per_page: usize,
    /// Matching works.
    pub results: Vec<SearchResult>,
    /// Facet counts, when present.
    #[serde(default)]
    pub facets: SearchFacets,
}

/// Response from `POST /api/search/ask` — search envelope plus ask metadata.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AskResponse {
    /// The underlying search envelope.
    #[serde(flatten)]
    pub search: SearchResponse,
    /// Whether the natural-language ask path was used.
    #[serde(default)]
    pub used_ask: bool,
    /// The original natural-language query, when ask was used.
    #[serde(default)]
    pub ask_query: Option<String>,
    /// Free-text translation of the parsed filters, when present.
    #[serde(default)]
    pub translation: Option<serde_json::Value>,
}

/// Response from `GET /api/search/body?q=`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BodySearchResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Total matching works.
    #[serde(default)]
    pub total: i64,
    /// Current page (1-based).
    #[serde(default)]
    pub page: usize,
    /// Results per page.
    #[serde(default)]
    pub per_page: usize,
    /// Matching works.
    #[serde(default)]
    pub results: Vec<BodySearchHit>,
}

/// A body-search hit with `<mark>`-highlighted snippet.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BodySearchHit {
    /// FicHub url id.
    pub url_id: String,
    /// Numeric work id, when known.
    #[serde(default)]
    pub work_id: Option<i64>,
    /// Work title.
    pub title: String,
    /// Author display name.
    pub author: String,
    /// Source site domain.
    #[serde(default)]
    pub source: String,
    /// Word count.
    #[serde(default)]
    pub words: i64,
    /// Chapter count.
    #[serde(default)]
    pub chapters: i64,
    /// Status string.
    #[serde(default)]
    pub status: String,
    /// Work description.
    #[serde(default)]
    pub description: String,
    /// `<mark>`-highlighted matching passage.
    #[serde(default)]
    pub body_snippet: Option<String>,
}

/// A feed item (`GET /api/v1/feed`).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FeedItem {
    /// Numeric work id.
    #[serde(default)]
    pub work_id: i64,
    /// FicHub url id.
    #[serde(default)]
    pub url_id: String,
    /// Work title.
    #[serde(default)]
    pub title: String,
    /// Author display name.
    #[serde(default)]
    pub author: String,
    /// ISO timestamp of last update.
    #[serde(default)]
    pub updated: String,
    /// Feed entry format (e.g. `epub`).
    #[serde(default)]
    pub format: String,
    /// Optional feed note.
    #[serde(default)]
    pub note: Option<String>,
}

/// Response from `GET /api/v1/feed`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FeedResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Feed items.
    #[serde(default)]
    pub items: Vec<FeedItem>,
    /// Current page.
    #[serde(default)]
    pub page: i64,
    /// Results per page.
    #[serde(default)]
    pub per_page: i64,
    /// Total items.
    #[serde(default)]
    pub total: i64,
}

/// A Fic Request board item (`GET /api/requests`).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RequestItem {
    /// Request id.
    pub id: i64,
    /// Request title.
    pub title: String,
    /// Request body text.
    pub body: String,
    /// Seed work (fic the request is about), when known.
    #[serde(default)]
    pub seed_work_id: Option<i64>,
    /// Request status.
    pub status: String,
    /// ISO timestamp of creation.
    #[serde(default)]
    pub created_at: String,
    /// Number of answers.
    #[serde(default)]
    pub answer_count: i64,
    /// Upvote count.
    #[serde(default)]
    pub upvotes: i64,
}

/// Response from `GET /api/requests?status=`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RequestsResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Request items.
    #[serde(default)]
    pub items: Vec<RequestItem>,
    /// Current page.
    #[serde(default)]
    pub page: i64,
    /// Request status filter echoed back.
    #[serde(default)]
    pub status: String,
}

/// A roadmap consensus cluster row.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClusterRow {
    /// Cluster id.
    pub id: i64,
    /// Cluster text (the roadmap item).
    pub text: String,
    /// Elo rating in the consensus tournament.
    #[serde(default)]
    pub elo_rating: f64,
    /// Matches played.
    #[serde(default)]
    pub matches_played: i64,
    /// Times picked as best.
    #[serde(default)]
    pub times_picked_best: i64,
    /// Times picked as worst.
    #[serde(default)]
    pub times_picked_worst: i64,
    /// Number of suggestions.
    #[serde(default)]
    pub suggestions: i64,
    /// Cluster status.
    #[serde(default)]
    pub status: String,
    /// Controversy score.
    #[serde(default)]
    pub controversy: i64,
}

/// Response from `GET /api/roadmap/consensus`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ConsensusResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Leaderboard rows.
    #[serde(default)]
    pub leaderboard: Vec<ClusterRow>,
    /// Most controversial rows.
    #[serde(default)]
    pub controversy: Vec<ClusterRow>,
}

/// Auth response from `POST /api/auth/login`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthResponse {
    /// JWT to use for authenticated endpoints.
    pub token: String,
    /// The authenticated user.
    pub user: AuthUserModel,
}

/// The authenticated user model.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthUserModel {
    /// FicHub user id.
    pub id: i64,
    /// Username.
    pub username: String,
    /// Role code.
    pub role: i16,
    /// Reputation score.
    pub reputation: i64,
    /// Email address, when present.
    #[serde(default)]
    pub email: Option<String>,
    /// Level.
    #[serde(default)]
    pub level: i16,
    /// Experience points.
    #[serde(default)]
    pub exp: i64,
}

/// Me response from `GET /api/auth/me`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MeResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// The authenticated user, when the token was valid.
    #[serde(default)]
    pub user: Option<AuthUserModel>,
}

// ── Forum (F2–F6: categories/topics/posts/follow/read/search/moderation) ──
//
// Shapes mirror `src/routes/forum.rs` in the FicHub web repo (the
// authoritative server implementation of FORUM-API-CONTRACT.md). All forum
// endpoints are auth-gated; the bot always sends the bearer token.

/// A forum category (`GET /api/forum/categories` item).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumCategory {
    /// Category id.
    pub id: i64,
    /// URL slug (used as `category=` in topic lists).
    pub slug: String,
    /// Display title.
    pub title: String,
    /// Category description.
    #[serde(default)]
    pub description: String,
    /// Sort position (ascending).
    #[serde(default)]
    pub position: i32,
    /// Mod-only board (hidden from anonymous readers).
    #[serde(default)]
    pub is_mod_only: bool,
    /// ISO timestamp of creation.
    #[serde(default)]
    pub created_at: String,
    /// Live topic count (excludes deleted/hidden).
    #[serde(default)]
    pub topic_count: i64,
    /// ISO timestamp of the most recent topic activity, when present.
    #[serde(default)]
    pub last_activity_at: Option<String>,
}

/// Response envelope from `GET /api/forum/categories`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumCategoriesResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Visible categories.
    #[serde(default)]
    pub items: Vec<ForumCategory>,
}

/// A topic row in the category listing (`GET /api/forum/topics` item).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumTopic {
    /// Topic id.
    pub id: i64,
    /// Topic title.
    pub title: String,
    /// Canonical slug `{slugified-title}-{id}`, when assigned.
    #[serde(default)]
    pub topic_slug: Option<String>,
    /// Author user id.
    pub author_id: i64,
    /// Author display name.
    #[serde(default)]
    pub author_username: String,
    /// Number of replies (visible posts − OP).
    #[serde(default)]
    pub reply_count: i64,
    /// Legacy vote score (v2 keeps this at 0; mod points are the score system).
    #[serde(default)]
    pub vote_score: i64,
    /// View count.
    #[serde(default)]
    pub view_count: i64,
    /// Id of the newest post, when present.
    #[serde(default)]
    pub last_post_id: Option<i64>,
    /// Topic status: `open` | `locked` | `pinned` | `removed`.
    #[serde(default)]
    pub status: String,
    /// ISO timestamp of last activity.
    #[serde(default)]
    pub last_activity_at: String,
    /// ISO timestamp of creation.
    #[serde(default)]
    pub created_at: String,
    /// Whether the current user has unread posts in this topic.
    #[serde(default)]
    pub unread: bool,
}

/// Response envelope from `GET /api/forum/topics`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumTopicList {
    /// Error code (0 = success).
    pub err: i32,
    /// Topic rows (pinned first, then last activity desc).
    #[serde(default)]
    pub items: Vec<ForumTopic>,
    /// Cursor for the next page (last topic id), when more pages exist.
    #[serde(default)]
    pub next_cursor: Option<i64>,
    /// Category slug echoed back.
    #[serde(default)]
    pub category: String,
    /// Page size actually applied.
    #[serde(default)]
    pub limit: i64,
}

/// A quoted-post preview attached to a forum post (best-effort server-side).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumQuote {
    /// Author of the quoted post.
    #[serde(default)]
    pub author_username: String,
    /// First ~200 chars of the quoted post.
    #[serde(default)]
    pub preview: String,
}

/// A single post in a topic detail (`GET /api/forum/topics/{id}` item).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumPost {
    /// Post id.
    pub id: i64,
    /// Author user id.
    pub author_id: i64,
    /// Author display name.
    #[serde(default)]
    pub author_username: String,
    /// Post body (markdown).
    #[serde(default)]
    pub body: String,
    /// Id of the quoted post, when this post quotes one.
    #[serde(default)]
    pub quote_of: Option<i64>,
    /// Resolved quote preview, when available.
    #[serde(default)]
    pub quote: Option<ForumQuote>,
    /// ISO timestamp of last edit, when edited.
    #[serde(default)]
    pub edited_at: Option<String>,
    /// ISO timestamp of deletion, when soft-deleted.
    #[serde(default)]
    pub deleted_at: Option<String>,
    /// ISO timestamp of creation.
    #[serde(default)]
    pub created_at: String,
    /// Moderation score (0 baseline; adjusted by mod actions).
    #[serde(default)]
    pub score: i32,
    /// Whether this post is the topic OP (lowest-id post).
    #[serde(default)]
    pub is_op: bool,
}

/// Topic detail + posts (`GET /api/forum/topics/{id}` and `/by-slug/{slug}`).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumTopicDetail {
    /// Error code (0 = success).
    pub err: i32,
    /// Topic id.
    pub id: i64,
    /// Topic title.
    pub title: String,
    /// Canonical slug, when assigned.
    #[serde(default)]
    pub topic_slug: Option<String>,
    /// Author user id.
    pub author_id: i64,
    /// Author display name.
    #[serde(default)]
    pub author_username: String,
    /// Category slug.
    #[serde(default)]
    pub category_slug: String,
    /// Category display title.
    #[serde(default)]
    pub category_title: String,
    /// Topic status.
    #[serde(default)]
    pub status: String,
    /// OP body (markdown).
    #[serde(default)]
    pub body: String,
    /// Free-form payload JSONB, when set.
    #[serde(default)]
    pub payload: serde_json::Value,
    /// View count AFTER this fetch incremented it.
    #[serde(default)]
    pub view_count: i64,
    /// ISO timestamp of creation.
    #[serde(default)]
    pub created_at: String,
    /// ISO timestamp of last update, when present.
    #[serde(default)]
    pub updated_at: Option<String>,
    /// Posts (OP first, then replies ascending; `after=` cursor skips earlier).
    #[serde(default)]
    pub items: Vec<ForumPost>,
    /// Cursor for the next page of posts, when more exist.
    #[serde(default)]
    pub next_cursor: Option<i64>,
    /// Page size actually applied.
    #[serde(default)]
    pub limit: i64,
    /// View count before this fetch incremented it.
    #[serde(default)]
    pub view_count_before: i64,
}

/// A forum search hit (`GET /api/forum/search` result).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumSearchHit {
    /// `topic` (OP match) or `post` (reply match).
    #[serde(default)]
    pub r#type: String,
    /// Topic id the hit belongs to.
    pub topic_id: i64,
    /// Topic slug, when assigned.
    #[serde(default)]
    pub topic_slug: Option<String>,
    /// Post id, when the hit is a reply.
    #[serde(default)]
    pub post_id: Option<i64>,
    /// Author user id.
    pub author_id: i64,
    /// Author display name.
    #[serde(default)]
    pub author_username: String,
    /// Topic title.
    #[serde(default)]
    pub title: String,
    /// Matched body text.
    #[serde(default)]
    pub body: String,
    /// `<mark>`-highlighted snippet, when present.
    #[serde(default)]
    pub snippet: Option<String>,
    /// Category slug.
    #[serde(default)]
    pub category_slug: String,
    /// Category display title.
    #[serde(default)]
    pub category_title: String,
    /// ISO timestamp of the matching post/topic.
    #[serde(default)]
    pub created_at: String,
}

/// Response envelope from `GET /api/forum/search`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumSearchResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Query echoed back.
    #[serde(default)]
    pub q: String,
    /// Matches (ranked).
    #[serde(default)]
    pub results: Vec<ForumSearchHit>,
    /// Always null (search is limit/offset, not cursor-paginated).
    #[serde(default)]
    pub next_cursor: Option<i64>,
    /// Page size actually applied.
    #[serde(default)]
    pub limit: i64,
    /// Number of merged matches (pre-truncation).
    #[serde(default)]
    pub total: i64,
}

/// Response from `POST /api/forum/topics` (create topic).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumCreateTopicResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// New topic id.
    #[serde(default)]
    pub id: i64,
    /// New OP post id.
    #[serde(default)]
    pub post_id: i64,
    /// Generated canonical slug `{slugified-title}-{id}`.
    #[serde(default)]
    pub topic_slug: Option<String>,
    /// Human message.
    #[serde(default)]
    pub msg: String,
}

/// Response from `POST /api/forum/topics/{id}/posts` (reply).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumPostCreated {
    /// Error code (0 = success).
    pub err: i32,
    /// New post id.
    #[serde(default)]
    pub id: i64,
    /// Human message.
    #[serde(default)]
    pub msg: String,
}

/// Follow state (`POST` toggle and `GET` read on `/api/forum/topics/{id}/follow`).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumFollowState {
    /// Error code (0 = success).
    pub err: i32,
    /// Whether the current user is following the topic (post-toggle value).
    #[serde(default)]
    pub following: bool,
    /// Total follower count.
    #[serde(default)]
    pub follower_count: i64,
}

/// Response from `POST /api/forum/topics/{id}/read` (mark read).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumMarkRead {
    /// Error code (0 = success).
    pub err: i32,
    /// The read marker actually stored (monotonic).
    #[serde(default)]
    pub last_read_post_id: i64,
    /// ISO timestamp of the upsert.
    #[serde(default)]
    pub updated_at: String,
}

/// Response from `GET /api/forum/moderation/status` (F5).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumModerationStatus {
    /// Error code (0 = success).
    pub err: i32,
    /// Points left in the current grant window.
    #[serde(default)]
    pub points_left: i16,
    /// ISO timestamp of grant expiry, when eligible.
    #[serde(default)]
    pub expires_at: Option<String>,
    /// Whether the user may moderate.
    #[serde(default)]
    pub eligible: bool,
    /// Why the user is ineligible, when present.
    #[serde(default)]
    pub reason: Option<String>,
}

/// A moderation-queue row (`GET /api/forum/moderation/queue` item, F5).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumModQueueItem {
    /// Post id.
    pub post_id: i64,
    /// Topic id the post belongs to.
    pub topic_id: i64,
    /// Author display name.
    #[serde(default)]
    pub author_username: String,
    /// Post excerpt (first ~300 chars).
    #[serde(default)]
    pub body: String,
    /// Current moderation score.
    #[serde(default)]
    pub score: i32,
    /// Times already moderated.
    #[serde(default)]
    pub mod_count: i32,
    /// Always null in v2 (reason is chosen at moderate time).
    #[serde(default)]
    pub reason: Option<String>,
    /// ISO timestamp of creation.
    #[serde(default)]
    pub created_at: String,
}

/// Response envelope from `GET /api/forum/moderation/queue` (F5).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumModerationQueue {
    /// Error code (0 = success).
    pub err: i32,
    /// Posts needing moderation (lowest score first).
    #[serde(default)]
    pub items: Vec<ForumModQueueItem>,
    /// Item count.
    #[serde(default)]
    pub count: i64,
    /// Cold-start gate: eligible-moderator pool below minimum.
    #[serde(default)]
    pub pool_too_small: bool,
}

/// Response from `POST /api/forum/posts/{id}/moderate` (F5).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumModerateResponse {
    /// Error code (0 = success).
    pub err: i32,
    /// Score delta applied for the reason.
    #[serde(default)]
    pub delta: i16,
    /// Post score after the action.
    #[serde(default)]
    pub score_after: i32,
    /// Always null in v2 (auto-collapse is client-side).
    #[serde(default)]
    pub hidden_until: Option<String>,
}

/// A metamoderation-queue row (`GET /api/forum/metamod/queue` item, F6).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumMetamodItem {
    /// Moderation action id (used for the vote).
    pub action_id: i64,
    /// Post id the action targeted.
    pub post_id: i64,
    /// Topic id the post belongs to.
    pub topic_id: i64,
    /// Post excerpt (first ~200 chars).
    #[serde(default)]
    pub excerpt: String,
    /// Reason the moderator used.
    #[serde(default)]
    pub reason: String,
    /// Score delta the moderator applied.
    #[serde(default)]
    pub delta: i16,
    /// Post score after the action.
    #[serde(default)]
    pub score_after: i32,
    /// ISO timestamp of the action.
    #[serde(default)]
    pub created_at: String,
}

/// Response envelope from `GET /api/forum/metamod/queue` (F6).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumMetamodQueue {
    /// Error code (0 = success).
    pub err: i32,
    /// Anonymized moderation actions to rate.
    #[serde(default)]
    pub items: Vec<ForumMetamodItem>,
    /// Item count.
    #[serde(default)]
    pub count: i64,
    /// Cold-start gate: eligible-metamod pool below minimum.
    #[serde(default)]
    pub pool_too_small: bool,
}

/// Response from `POST /api/forum/metamod/{actionId}/vote` (F6).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForumMetamodVoteResponse {
    /// Error code (0 = success).
    pub err: i32,
}