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
//! Typed HTTP client for the FicHub REST API.
//!
//! Wraps `reqwest` and every endpoint the bot uses. Never touches the FicHub
//! database directly — this is the shared contract between the bot and the
//! archive (mirrors what the frontend's `api/client.ts` does).
//!
//! Auth: endpoints that need a logged-in user (`/api/recommendations/personal`,
//! `/api/v1/feed`, `/api/bookmarks`, `/api/ratings`, `/api/kudos`, `/api/blocks`,
//! `/api/requests` voting, `/api/roadmap` voting) take an `auth_token` and send
//! it as `Authorization: Bearer <token>`.

use std::sync::Arc;

use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
use serde::de::DeserializeOwned;

use crate::config::BotConfig;
use crate::error::{BotError, Result};
use crate::model::*;

/// A client for the FicHub REST API.
#[derive(Debug, Clone)]
pub struct FichubClient {
    /// Shared reqwest client (cookies + rustls).
    http: reqwest::Client,
    /// Bot config (base URL).
    config: Arc<BotConfig>,
}

impl FichubClient {
    /// Build a new client from a config.
    pub fn new(config: Arc<BotConfig>) -> Result<Self> {
        let http = reqwest::Client::builder()
            .user_agent("fanfic-archivist/0.1 (FicHub Discord bot)")
            .build()
            .map_err(BotError::Http)?;
        Ok(Self { http, config })
    }

    /// Build a client with a custom `reqwest::Client` (used in tests with a mock).
    pub fn with_client(config: Arc<BotConfig>, http: reqwest::Client) -> Self {
        Self { http, config }
    }

    /// Access the underlying `reqwest::Client` (shared with intent/LLM callers).
    pub fn http(&self) -> &reqwest::Client {
        &self.http
    }

    /// Low-level GET returning deserialized JSON.
    async fn get<T: DeserializeOwned>(
        &self,
        path: &str,
        auth_token: Option<&str>,
    ) -> Result<T> {
        let url = self.config.url(path);
        let mut req = self.http.get(&url);
        if let Some(tok) = auth_token {
            req = req.header(AUTHORIZATION, format!("Bearer {tok}"));
        }
        let resp = req.send().await?;
        Self::parse_response(resp).await
    }

    /// Low-level POST with a JSON body returning deserialized JSON.
    async fn post<T: DeserializeOwned, B: serde::Serialize + ?Sized>(
        &self,
        path: &str,
        body: &B,
        auth_token: Option<&str>,
    ) -> Result<T> {
        let url = self.config.url(path);
        let mut req = self.http.post(&url).header(CONTENT_TYPE, "application/json");
        if let Some(tok) = auth_token {
            req = req.header(AUTHORIZATION, format!("Bearer {tok}"));
        }
        let resp = req.json(body).send().await?;
        Self::parse_response(resp).await
    }

    /// Low-level DELETE returning unit (used for blocklist removal).
    async fn delete(
        &self,
        path: &str,
        auth_token: Option<&str>,
    ) -> Result<serde_json::Value> {
        let url = self.config.url(path);
        let mut req = self.http.delete(&url);
        if let Some(tok) = auth_token {
            req = req.header(AUTHORIZATION, format!("Bearer {tok}"));
        }
        let resp = req.send().await?;
        Self::parse_response(resp).await
    }

    /// Parse a response into the typed shape, checking status + `err` field.
    async fn parse_response<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T> {
        let status = resp.status().as_u16();
        let body = resp.text().await.unwrap_or_default();
        if status < 200 || status >= 300 {
            return Err(BotError::Status { status, body });
        }
        // Most FicHub endpoints embed `err` (0 = ok). Deserialize first, then
        // check err field if present.
        let value: serde_json::Value = serde_json::from_str(&body)
            .map_err(|e| BotError::Json(e))?;
        if let Some(err) = value.get("err").and_then(|e| e.as_i64()) {
            if err != 0 {
                let msg = value
                    .get("msg")
                    .and_then(|m| m.as_str())
                    .unwrap_or("unknown error")
                    .to_string();
                return Err(BotError::Api {
                    err: err as i32,
                    msg,
                });
            }
        }
        serde_json::from_value(value).map_err(BotError::Json)
    }

    // ── Export / metadata ──────────────────────────────────────────────

    /// `GET /api/epub?q=<url>` — export metadata + download URLs.
    pub async fn fetch_export(&self, url: &str) -> Result<ExportResponse> {
        let q = urlencoding::encode(url);
        self.get(&format!("/api/epub?q={q}"), None).await
    }

    /// `GET /api/epub/convert?q=<url>&format=mobi|pdf|azw3` — lazy conversion.
    pub async fn lazy_convert(&self, url: &str, format: &str) -> Result<ConvertResponse> {
        let q = urlencoding::encode(url);
        self.get(&format!("/api/epub/convert?q={q}&format={format}"), None)
            .await
    }

    /// `GET /api/meta?q=<url>` — metadata only (no download URLs).
    pub async fn fetch_meta(&self, url: &str) -> Result<ExportResponse> {
        let q = urlencoding::encode(url);
        self.get(&format!("/api/meta?q={q}"), None).await
    }

    // ── Recommendations ────────────────────────────────────────────────

    /// `GET /api/recommendations?q=&n=` — similar works to a seed URL.
    pub async fn recommendations(&self, url: &str, n: i32) -> Result<RecommendationsResponse> {
        let q = urlencoding::encode(url);
        self.get(&format!("/api/recommendations?q={q}&n={n}"), None)
            .await
    }

    /// `GET /api/recommendations/personal` — personalized recs (auth).
    pub async fn personal_recommendations(
        &self,
        token: &str,
    ) -> Result<PersonalRecommendationsResponse> {
        self.get("/api/recommendations/personal", Some(token)).await
    }

    /// `GET /api/recommendations/strategies` — list available strategies.
    pub async fn strategies(&self) -> Result<serde_json::Value> {
        self.get("/api/recommendations/strategies", None).await
    }

    // ── Search ─────────────────────────────────────────────────────────

    /// `GET /api/search?q=&page=&per_page=` — advanced search.
    pub async fn search(
        &self,
        params: &SearchParams,
    ) -> Result<SearchResponse> {
        self.get(&format!("/api/search?{}", params.to_query()), None)
            .await
    }

    /// `POST /api/search/ask` — LLM-assisted natural-language search.
    pub async fn ask(&self, q: &str) -> Result<AskResponse> {
        self.post("/api/search/ask", &serde_json::json!({ "q": q }), None)
            .await
    }

    /// `GET /api/search/body?q=&page=&per_page=` — full-text body search.
    pub async fn body_search(
        &self,
        q: &str,
        page: usize,
        per_page: usize,
    ) -> Result<BodySearchResponse> {
        self.get(&format!("/api/search/body?q={q}&page={page}&per_page={per_page}"), None)
            .await
    }

    // ── Social / library (auth) ────────────────────────────────────────

    /// `GET /api/v1/feed?page=` — new chapters from followed works (auth).
    pub async fn feed(&self, token: &str, page: i64) -> Result<FeedResponse> {
        self.get(&format!("/api/v1/feed?page={page}"), Some(token)).await
    }

    /// `POST /api/bookmarks` — bookmark a fic (auth).
    pub async fn add_bookmark(&self, token: &str, url_id: &str) -> Result<serde_json::Value> {
        self.post(
            "/api/bookmarks",
            &serde_json::json!({ "url_id": url_id }),
            Some(token),
        )
        .await
    }

    /// `DELETE /api/bookmarks/{work_id}` — remove a bookmark (auth).
    pub async fn remove_bookmark(
        &self,
        token: &str,
        work_id: i64,
    ) -> Result<serde_json::Value> {
        self.delete(&format!("/api/bookmarks/{work_id}"), Some(token)).await
    }

    /// `POST /api/ratings` — rate a fic (auth).
    pub async fn rate(&self, token: &str, url_id: &str, stars: i32) -> Result<serde_json::Value> {
        self.post(
            "/api/ratings",
            &serde_json::json!({ "url_id": url_id, "stars": stars }),
            Some(token),
        )
        .await
    }

    /// `POST /api/blocks` — block/hide a fic from recommendations (auth).
    pub async fn add_block(&self, token: &str, url_id: &str) -> Result<serde_json::Value> {
        self.post(
            "/api/blocks",
            &serde_json::json!({ "url_id": url_id }),
            Some(token),
        )
        .await
    }

    /// `DELETE /api/blocks/{url_id}` — unblock a fic (auth).
    pub async fn remove_block(&self, token: &str, url_id: &str) -> Result<serde_json::Value> {
        self.delete(&format!("/api/blocks/{url_id}"), Some(token)).await
    }

    /// `GET /api/kudos/{work_id}` — kudos counts for a work.
    pub async fn kudos(&self, work_id: i64) -> Result<serde_json::Value> {
        self.get(&format!("/api/kudos/{work_id}"), None).await
    }

    // ── Community: Fic Requests ────────────────────────────────────────

    /// `GET /api/requests?status=&page=` — list requests.
    pub async fn list_requests(&self, status: &str, page: i64) -> Result<RequestsResponse> {
        self.get(&format!("/api/requests?status={status}&page={page}"), None)
            .await
    }

    /// `POST /api/requests` — create a request (auth).
    pub async fn create_request(
        &self,
        token: &str,
        title: &str,
        body: &str,
    ) -> Result<serde_json::Value> {
        self.post(
            "/api/requests",
            &serde_json::json!({ "title": title, "body": body }),
            Some(token),
        )
        .await
    }

    // ── Community: Roadmap consensus ───────────────────────────────────

    /// `GET /api/roadmap/consensus` — public leaderboard + controversy.
    pub async fn consensus(&self) -> Result<ConsensusResponse> {
        self.get("/api/roadmap/consensus", None).await
    }

    // ── Auth ───────────────────────────────────────────────────────────

    /// `POST /api/auth/login` — exchange username/password for a JWT.
    pub async fn login(&self, username: &str, password: &str) -> Result<AuthResponse> {
        self.post(
            "/api/auth/login",
            &serde_json::json!({ "username": username, "password": password }),
            None,
        )
        .await
    }

    /// `GET /api/auth/me` — verify a token, get the current user.
    pub async fn me(&self, token: &str) -> Result<MeResponse> {
        self.get("/api/auth/me", Some(token)).await
    }

    /// `GET /api/docs/ask?q=...&n=...` — Ask-the-Docs RAG (grounded help).
    /// Returns the top matching doc sections (with anchors) as JSON values.
    pub async fn docs_ask(&self, q: &str, n: usize) -> Result<Vec<serde_json::Value>> {
        let query = urlencoding::encode(q);
        let value: serde_json::Value = self
            .get(&format!("/api/docs/ask?q={query}&n={n}"), None)
            .await?;
        Ok(value
            .get("sections")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default())
    }

    // ── Forum: categories / topics / posts (F2/F3) ────────────────────────
    //
    // All forum endpoints are auth-gated. Path shapes follow
    // FORUM-API-CONTRACT.md; response shapes mirror `src/routes/forum.rs`.

    /// `GET /api/forum/categories` — visible categories + topic counts (auth).
    pub async fn forum_categories(&self, token: &str) -> Result<ForumCategoriesResponse> {
        self.get("/api/forum/categories", Some(token)).await
    }

    /// `GET /api/forum/topics?category=&cursor=&limit=` — cursor-paginated
    /// topic list for a category (auth). `cursor` is the last topic id seen
    /// (from `next_cursor`); omit for the first page.
    pub async fn forum_topics(
        &self,
        token: &str,
        category: Option<&str>,
        cursor: Option<i64>,
        limit: u32,
    ) -> Result<ForumTopicList> {
        let mut path = format!("/api/forum/topics?limit={limit}");
        if let Some(cat) = category {
            path.push_str(&format!("&category={}", urlencoding::encode(cat)));
        }
        if let Some(c) = cursor {
            path.push_str(&format!("&cursor={c}"));
        }
        self.get(&path, Some(token)).await
    }

    /// `GET /api/forum/topics/{id}?after=` — topic detail + posts (auth).
    /// `after` is the last post id seen (from `next_cursor`); omit for the
    /// first page (OP + newest posts, default limit 25).
    pub async fn forum_topic(
        &self,
        token: &str,
        topic_id: i64,
        after: Option<i64>,
    ) -> Result<ForumTopicDetail> {
        let path = match after {
            Some(a) => format!("/api/forum/topics/{topic_id}?after={a}"),
            None => format!("/api/forum/topics/{topic_id}"),
        };
        self.get(&path, Some(token)).await
    }

    /// `GET /api/forum/topics/by-slug/{slug}` — topic detail resolved by the
    /// canonical slug (same shape as `forum_topic`, auth).
    pub async fn forum_topic_by_slug(&self, token: &str, slug: &str) -> Result<ForumTopicDetail> {
        let s = urlencoding::encode(slug);
        self.get(&format!("/api/forum/topics/by-slug/{s}"), Some(token))
            .await
    }

    /// `POST /api/forum/topics` — create a topic + OP post (auth).
    pub async fn forum_create_topic(
        &self,
        token: &str,
        title: &str,
        category_slug: &str,
        body: &str,
        payload: Option<serde_json::Value>,
    ) -> Result<ForumCreateTopicResponse> {
        let mut body_obj = serde_json::json!({
            "title": title,
            "category_slug": category_slug,
            "body": body,
        });
        if let Some(p) = payload {
            body_obj["payload"] = p;
        }
        self.post("/api/forum/topics", &body_obj, Some(token)).await
    }

    /// `POST /api/forum/topics/{id}/posts` — reply to a topic (auth).
    pub async fn forum_reply(
        &self,
        token: &str,
        topic_id: i64,
        body: &str,
        quote_of: Option<i64>,
    ) -> Result<ForumPostCreated> {
        let mut body_obj = serde_json::json!({ "body": body });
        if let Some(q) = quote_of {
            body_obj["quote_of"] = serde_json::json!(q);
        }
        self.post(
            &format!("/api/forum/topics/{topic_id}/posts"),
            &body_obj,
            Some(token),
        )
        .await
    }

    // ── Forum: follow / read state (F3/F4) ────────────────────────────────

    /// `POST /api/forum/topics/{id}/follow` — toggle follow (auth).
    pub async fn forum_follow(&self, token: &str, topic_id: i64) -> Result<ForumFollowState> {
        self.post(
            &format!("/api/forum/topics/{topic_id}/follow"),
            &serde_json::json!({}),
            Some(token),
        )
        .await
    }

    /// `GET /api/forum/topics/{id}/follow` — my follow state + follower count (auth).
    pub async fn forum_follow_state(&self, token: &str, topic_id: i64) -> Result<ForumFollowState> {
        self.get(&format!("/api/forum/topics/{topic_id}/follow"), Some(token))
            .await
    }

    /// `POST /api/forum/topics/{id}/read` — mark a topic read (auth).
    /// `last_read_post_id` defaults to the topic's newest post when `None`.
    pub async fn forum_mark_read(
        &self,
        token: &str,
        topic_id: i64,
        last_read_post_id: Option<i64>,
    ) -> Result<ForumMarkRead> {
        let body = match last_read_post_id {
            Some(n) => serde_json::json!({ "last_read_post_id": n }),
            None => serde_json::json!({}),
        };
        self.post(
            &format!("/api/forum/topics/{topic_id}/read"),
            &body,
            Some(token),
        )
        .await
    }

    // ── Forum: search (F4) ────────────────────────────────────────────────

    /// `GET /api/forum/search?q=&category=` — FTS over topics + posts (auth).
    pub async fn forum_search(
        &self,
        token: &str,
        q: &str,
        category: Option<&str>,
    ) -> Result<ForumSearchResponse> {
        let mut path = format!("/api/forum/search?q={}", urlencoding::encode(q));
        if let Some(cat) = category {
            path.push_str(&format!("&category={}", urlencoding::encode(cat)));
        }
        self.get(&path, Some(token)).await
    }

    // ── Forum: moderation (F5) / metamoderation (F6) ──────────────────────

    /// `GET /api/forum/moderation/status` — my points + eligibility (auth).
    pub async fn forum_moderation_status(&self, token: &str) -> Result<ForumModerationStatus> {
        self.get("/api/forum/moderation/status", Some(token)).await
    }

    /// `GET /api/forum/moderation/queue` — posts needing moderation (auth).
    pub async fn forum_moderation_queue(&self, token: &str) -> Result<ForumModerationQueue> {
        self.get("/api/forum/moderation/queue", Some(token)).await
    }

    /// `POST /api/forum/posts/{id}/moderate` — spend 1 point on a post (auth).
    pub async fn forum_moderate(
        &self,
        token: &str,
        post_id: i64,
        reason: &str,
    ) -> Result<ForumModerateResponse> {
        self.post(
            &format!("/api/forum/posts/{post_id}/moderate"),
            &serde_json::json!({ "reason": reason }),
            Some(token),
        )
        .await
    }

    /// `GET /api/forum/metamod/queue` — anonymized actions to rate (auth).
    pub async fn forum_metamod_queue(&self, token: &str) -> Result<ForumMetamodQueue> {
        self.get("/api/forum/metamod/queue", Some(token)).await
    }

    /// `POST /api/forum/metamod/{action_id}/vote` — rate a mod action (auth).
    /// `verdict` is one of `fair` | `unfair` | `unsure`.
    pub async fn forum_metamod_vote(
        &self,
        token: &str,
        action_id: i64,
        verdict: &str,
    ) -> Result<ForumMetamodVoteResponse> {
        self.post(
            &format!("/api/forum/metamod/{action_id}/vote"),
            &serde_json::json!({ "verdict": verdict }),
            Some(token),
        )
        .await
    }
}

/// Query parameter builder for advanced search.
#[derive(Debug, Clone, Default)]
pub struct SearchParams {
    /// Full-text query string.
    pub q: String,
    /// Page number (1-based).
    pub page: Option<usize>,
    /// Results per page.
    pub per_page: Option<usize>,
    /// Minimum word count filter.
    pub min_words: Option<i64>,
    /// Maximum word count filter.
    pub max_words: Option<i64>,
    /// Only return completed works when `true`.
    pub complete: Option<bool>,
    /// Source-site filter (e.g. `archiveofourown.org`).
    pub source: Option<String>,
    /// Fandom filter (comma-separated fandoms accepted).
    pub fandom: Option<String>,
    /// Exclude these fandoms (comma-separated).
    pub exclude_fandom: Option<String>,
    /// Main character/relationship attribute filter.
    pub main_char_attr: Option<String>,
    /// Minimum kudos filter.
    pub min_kudos: Option<i64>,
    /// Sort key (e.g. `kudos`, `updated`, `words`).
    pub sort: Option<String>,
    /// Require these tags (comma-separated).
    pub include_tags: Option<String>,
    /// Exclude these tags (comma-separated).
    pub exclude_tags: Option<String>,
}

impl SearchParams {
    /// Render as a query string for `GET /api/search`.
    pub fn to_query(&self) -> String {
        let mut qs = Vec::new();
        qs.push(format!("q={}", urlencoding::encode(&self.q)));
        if let Some(p) = self.page {
            qs.push(format!("page={p}"));
        }
        if let Some(p) = self.per_page {
            qs.push(format!("per_page={p}"));
        }
        if let Some(v) = self.min_words {
            qs.push(format!("min_words={v}"));
        }
        if let Some(v) = self.max_words {
            qs.push(format!("max_words={v}"));
        }
        if let Some(v) = self.complete {
            qs.push(format!("complete={v}"));
        }
        if let Some(v) = &self.source {
            qs.push(format!("source={}", urlencoding::encode(v)));
        }
        if let Some(v) = &self.fandom {
            qs.push(format!("fandom={}", urlencoding::encode(v)));
        }
        if let Some(v) = &self.exclude_fandom {
            qs.push(format!("exclude_fandom={}", urlencoding::encode(v)));
        }
        if let Some(v) = &self.main_char_attr {
            qs.push(format!("main_char_attr={}", urlencoding::encode(v)));
        }
        if let Some(v) = self.min_kudos {
            qs.push(format!("min_kudos={v}"));
        }
        if let Some(v) = &self.sort {
            qs.push(format!("sort={}", urlencoding::encode(v)));
        }
        if let Some(v) = &self.include_tags {
            qs.push(format!("include_tags={}", urlencoding::encode(v)));
        }
        if let Some(v) = &self.exclude_tags {
            qs.push(format!("exclude_tags={}", urlencoding::encode(v)));
        }
        qs.join("&")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    #[test]
    fn search_params_query_builds() {
        let p = SearchParams {
            q: "harry potter".into(),
            min_words: Some(50000),
            complete: Some(true),
            sort: Some("kudos".into()),
            ..Default::default()
        };
        let q = p.to_query();
        assert!(q.contains("q=harry%20potter"));
        assert!(q.contains("min_words=50000"));
        assert!(q.contains("complete=true"));
        assert!(q.contains("sort=kudos"));
    }

    #[test]
    fn search_params_omits_none() {
        let p = SearchParams {
            q: "drarry".into(),
            ..Default::default()
        };
        let q = p.to_query();
        assert_eq!(q, "q=drarry");
        assert!(!q.contains("page="));
        assert!(!q.contains("min_words="));
    }

    #[test]
    fn search_params_urlencodes_values() {
        let p = SearchParams {
            q: "dark harry".into(),
            main_char_attr: Some("Harry Potter|Dark Harry".into()),
            ..Default::default()
        };
        let q = p.to_query();
        assert!(q.contains("main_char_attr=Harry%20Potter%7CDark%20Harry"));
    }

    /// Regression: `/search` must request the real `/api/search` endpoint, not
    /// a bare query string (which hits the SPA fallback and returns HTML,
    /// failing JSON parse: "expected value at line 1 column 1").
    #[tokio::test]
    async fn search_hits_api_search_endpoint() {
        use std::sync::Arc;
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        // Echo server: record the request path, respond with a valid
        // SearchResponse JSON.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let requested_path = Arc::new(std::sync::Mutex::new(String::new()));
        let path_clone = Arc::clone(&requested_path);
        let server_path = Arc::clone(&requested_path);

        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 4096];
            let n = sock.read(&mut buf).await.unwrap();
            let req = String::from_utf8_lossy(&buf[..n]);
            let path = req.split_whitespace().nth(1).unwrap_or("").to_string();
            *server_path.lock().unwrap() = path;
            let body = r#"{"total":0,"results":[],"page":1,"per_page":20,"facets":{}}"#;
            let resp = format!(
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                body.len(),
                body
            );
            let _ = sock.write_all(resp.as_bytes()).await;
        });

        // Point the client at the echo server.
        let mut cfg = crate::config::BotConfig::default();
        cfg.base_url = format!("http://{addr}");
        let http = reqwest::Client::builder().build().unwrap();
        let client = FichubClient::with_client(Arc::new(cfg), http);

        let params = SearchParams { q: "jillian".into(), ..Default::default() };
        let _ = client.search(&params).await;

        server.await.unwrap();
        let path = path_clone.lock().unwrap().clone();
        assert!(
            path.starts_with("/api/search?"),
            "search() must request /api/search?..., got: {path}"
        );
        assert!(path.contains("q=jillian"), "path should carry q param, got: {path}");
    }

    // ── Forum endpoint tests ────────────────────────────────────────────
    //
    // Each test runs a tiny tokio echo server (no extra dev-deps) that
    // records the request line + body and replies with the documented forum
    // JSON shape. Mirrors the existing `search_hits_api_search_endpoint`
    // pattern.

    /// Accept one HTTP request, record (method, path, optional body),
    /// respond with `status` + `body`. Returns the recorded request.
    async fn serve_once(
        status: u16,
        body: &'static str,
    ) -> (
        tokio::task::JoinHandle<()>,
        std::net::SocketAddr,
        Arc<std::sync::Mutex<Option<(String, String, Option<String>)>>>,
    ) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let recorded = Arc::new(std::sync::Mutex::new(None));
        let rec = Arc::clone(&recorded);
        let resp_len = body.len();
        let handle = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 8192];
            let n = sock.read(&mut buf).await.unwrap();
            let req = String::from_utf8_lossy(&buf[..n]).to_string();
            let mut lines = req.lines();
            let request_line = lines.next().unwrap_or("").to_string();
            let mut parts = request_line.split_whitespace();
            let method = parts.next().unwrap_or("").to_string();
            let path = parts.next().unwrap_or("").to_string();
            // Split headers from body (headers end at the blank line).
            let body_str = req
                .split_once("\r\n\r\n")
                .map(|(_, b)| b.to_string())
                .unwrap_or_default();
            let req_body = if body_str.is_empty() { None } else { Some(body_str) };
            *rec.lock().unwrap() = Some((method, path, req_body));
            let resp = format!(
                "HTTP/1.1 {status} OK\r\ncontent-type: application/json\r\ncontent-length: {resp_len}\r\nconnection: close\r\n\r\n{body}"
            );
            let _ = sock.write_all(resp.as_bytes()).await;
        });
        (handle, addr, recorded)
    }

    /// Build a client pointed at the echo server (BotConfig::default reads
    /// env; the explicit base_url override wins).
    fn client_at(addr: std::net::SocketAddr) -> FichubClient {
        let mut cfg = crate::config::BotConfig::default();
        cfg.base_url = format!("http://{addr}");
        let http = reqwest::Client::builder().build().unwrap();
        FichubClient::with_client(Arc::new(cfg), http)
    }

    #[tokio::test]
    async fn forum_categories_sends_bearer_and_parses() {
        let (server, addr, recorded) = serve_once(
            200,
            r#"{"err":0,"items":[{"id":1,"slug":"recs","title":"Recs","description":"","position":0,"is_mod_only":false,"created_at":"2026-01-01T00:00:00Z","topic_count":3,"last_activity_at":null}]}"#,
        )
        .await;
        let client = client_at(addr);
        let resp = client.forum_categories("tok-123").await.unwrap();
        server.await.unwrap();
        let (method, path, _) = recorded.lock().unwrap().clone().unwrap();
        assert_eq!(method, "GET");
        assert_eq!(path, "/api/forum/categories");
        assert_eq!(resp.items.len(), 1);
        assert_eq!(resp.items[0].slug, "recs");
        assert_eq!(resp.items[0].topic_count, 3);
    }

    #[tokio::test]
    async fn forum_topics_builds_query_and_auth() {
        let (server, addr, recorded) = serve_once(
            200,
            r#"{"err":0,"items":[],"next_cursor":null,"category":"recs","limit":10}"#,
        )
        .await;
        let client = client_at(addr);
        let resp = client
            .forum_topics("tok-1", Some("fan fiction"), Some(42), 10)
            .await
            .unwrap();
        server.await.unwrap();
        let (method, path, _) = recorded.lock().unwrap().clone().unwrap();
        assert_eq!(method, "GET");
        assert!(path.starts_with("/api/forum/topics?"));
        assert!(path.contains("limit=10"));
        assert!(path.contains("category=fan%20fiction"));
        assert!(path.contains("cursor=42"));
        assert_eq!(resp.category, "recs");
    }

    #[tokio::test]
    async fn forum_topic_detail_parses_posts_and_op_flag() {
        let body = r#"{"err":0,"id":7,"title":"Hello","topic_slug":"hello-7","author_id":1,
            "author_username":"alice","category_slug":"meta","category_title":"Meta","status":"open",
            "body":"op text","payload":{},"view_count":12,"created_at":"2026-01-01T00:00:00Z",
            "updated_at":null,"items":[{"id":100,"author_id":1,"author_username":"alice","body":"op",
            "quote_of":null,"quote":null,"edited_at":null,"deleted_at":null,"created_at":"2026-01-01T00:00:00Z",
            "score":0,"is_op":true},{"id":101,"author_id":2,"author_username":"bob","body":"reply",
            "quote_of":100,"quote":{"author_username":"alice","preview":"op"},"edited_at":null,
            "deleted_at":null,"created_at":"2026-01-01T00:00:01Z","score":1,"is_op":false}],
            "next_cursor":null,"limit":25,"view_count_before":11}"#;
        let (server, addr, recorded) = serve_once(200, body).await;
        let client = client_at(addr);
        let resp = client.forum_topic("tok-9", 7, None).await.unwrap();
        server.await.unwrap();
        let (_, path, _) = recorded.lock().unwrap().clone().unwrap();
        assert_eq!(path, "/api/forum/topics/7");
        assert_eq!(resp.title, "Hello");
        assert_eq!(resp.items.len(), 2);
        assert!(resp.items[0].is_op);
        assert!(!resp.items[1].is_op);
        assert_eq!(resp.items[1].quote.as_ref().unwrap().author_username, "alice");
    }

    #[tokio::test]
    async fn forum_topic_by_slug_hits_slug_route() {
        let (server, addr, recorded) = serve_once(
            200,
            r#"{"err":0,"id":7,"title":"Hello","topic_slug":"hello-7","author_id":1,
            "author_username":"alice","category_slug":"meta","category_title":"Meta","status":"open",
            "body":"","payload":{},"view_count":1,"created_at":"2026-01-01T00:00:00Z",
            "updated_at":null,"items":[],"next_cursor":null,"limit":25,"view_count_before":0}"#,
        )
        .await;
        let client = client_at(addr);
        let _ = client.forum_topic_by_slug("tok-2", "hello-7").await.unwrap();
        server.await.unwrap();
        let (_, path, _) = recorded.lock().unwrap().clone().unwrap();
        assert_eq!(path, "/api/forum/topics/by-slug/hello-7");
    }

    #[tokio::test]
    async fn forum_create_topic_posts_json_and_parses() {
        let (server, addr, recorded) = serve_once(
            200,
            r#"{"err":0,"id":7,"post_id":100,"topic_slug":"hello-7","msg":"Topic created"}"#,
        )
        .await;
        let client = client_at(addr);
        let resp = client
            .forum_create_topic("tok-3", "Hello", "meta", "body text", Some(serde_json::json!({"fic":"x"})))
            .await
            .unwrap();
        server.await.unwrap();
        let (method, path, body) = recorded.lock().unwrap().clone().unwrap();
        assert_eq!(method, "POST");
        assert_eq!(path, "/api/forum/topics");
        let json: serde_json::Value = serde_json::from_str(&body.unwrap()).unwrap();
        assert_eq!(json["title"], "Hello");
        assert_eq!(json["category_slug"], "meta");
        assert_eq!(json["body"], "body text");
        assert_eq!(json["payload"]["fic"], "x");
        assert_eq!(resp.topic_slug.as_deref(), Some("hello-7"));
    }

    #[tokio::test]
    async fn forum_reply_posts_quote_of_when_present() {
        let (server, addr, recorded) = serve_once(
            200,
            r#"{"err":0,"id":101,"msg":"Post created"}"#,
        )
        .await;
        let client = client_at(addr);
        let resp = client.forum_reply("tok-4", 7, "nice", Some(100)).await.unwrap();
        server.await.unwrap();
        let (_, path, body) = recorded.lock().unwrap().clone().unwrap();
        assert_eq!(path, "/api/forum/topics/7/posts");
        let json: serde_json::Value = serde_json::from_str(&body.unwrap()).unwrap();
        assert_eq!(json["body"], "nice");
        assert_eq!(json["quote_of"], 100);
        assert_eq!(resp.id, 101);
    }

    #[tokio::test]
    async fn forum_follow_toggle_parses_state() {
        let (server, addr, _) = serve_once(
            200,
            r#"{"err":0,"following":true,"follower_count":3}"#,
        )
        .await;
        let client = client_at(addr);
        let resp = client.forum_follow("tok-5", 7).await.unwrap();
        server.await.unwrap();
        assert!(resp.following);
        assert_eq!(resp.follower_count, 3);
    }

    #[tokio::test]
    async fn forum_mark_read_posts_body() {
        let (server, addr, recorded) = serve_once(
            200,
            r#"{"err":0,"last_read_post_id":100,"updated_at":"2026-01-01T00:00:00Z"}"#,
        )
        .await;
        let client = client_at(addr);
        let resp = client.forum_mark_read("tok-6", 7, Some(100)).await.unwrap();
        server.await.unwrap();
        let (method, path, body) = recorded.lock().unwrap().clone().unwrap();
        assert_eq!(method, "POST");
        assert_eq!(path, "/api/forum/topics/7/read");
        let json: serde_json::Value = serde_json::from_str(&body.unwrap()).unwrap();
        assert_eq!(json["last_read_post_id"], 100);
        assert_eq!(resp.last_read_post_id, 100);
    }

    #[tokio::test]
    async fn forum_mark_read_defaults_when_none() {
        let (server, addr, recorded) = serve_once(
            200,
            r#"{"err":0,"last_read_post_id":50,"updated_at":"2026-01-01T00:00:00Z"}"#,
        )
        .await;
        let client = client_at(addr);
        let _ = client.forum_mark_read("tok-6", 7, None).await.unwrap();
        server.await.unwrap();
        let (_, _, body) = recorded.lock().unwrap().clone().unwrap();
        let json: serde_json::Value = serde_json::from_str(&body.unwrap()).unwrap();
        assert_eq!(json, serde_json::json!({}));
    }

    #[tokio::test]
    async fn forum_search_sends_q_and_category() {
        let (server, addr, recorded) = serve_once(
            200,
            r#"{"err":0,"q":"drarry","results":[],"next_cursor":null,"limit":20,"total":0}"#,
        )
        .await;
        let client = client_at(addr);
        let resp = client.forum_search("tok-7", "dark harry", Some("recs")).await.unwrap();
        server.await.unwrap();
        let (_, path, _) = recorded.lock().unwrap().clone().unwrap();
        assert!(path.starts_with("/api/forum/search?"));
        assert!(path.contains("q=dark%20harry"));
        assert!(path.contains("category=recs"));
        assert_eq!(resp.q, "drarry");
    }

    #[tokio::test]
    async fn forum_moderation_and_metamod_endpoints() {
        // status
        let (s1, a1, _) = serve_once(
            200,
            r#"{"err":0,"points_left":3,"expires_at":"2026-02-01T00:00:00Z","eligible":true}"#,
        )
        .await;
        let c1 = client_at(a1);
        let st = c1.forum_moderation_status("tok-8").await.unwrap();
        s1.await.unwrap();
        assert!(st.eligible);
        assert_eq!(st.points_left, 3);

        // queue
        let (s2, a2, _) = serve_once(
            200,
            r#"{"err":0,"items":[{"post_id":5,"topic_id":1,"author_username":"bob","body":"x","score":-1,"mod_count":1,"reason":null,"created_at":"2026-01-01T00:00:00Z"}],"count":1,"pool_too_small":false}"#,
        )
        .await;
        let c2 = client_at(a2);
        let q = c2.forum_moderation_queue("tok-8").await.unwrap();
        s2.await.unwrap();
        assert_eq!(q.items.len(), 1);
        assert_eq!(q.items[0].post_id, 5);

        // moderate
        let (s3, a3, recorded) = serve_once(
            200,
            r#"{"err":0,"delta":-1,"score_after":-2,"hidden_until":null}"#,
        )
        .await;
        let c3 = client_at(a3);
        let m = c3.forum_moderate("tok-8", 5, "spam").await.unwrap();
        s3.await.unwrap();
        let (method, path, body) = recorded.lock().unwrap().clone().unwrap();
        assert_eq!(method, "POST");
        assert_eq!(path, "/api/forum/posts/5/moderate");
        let json: serde_json::Value = serde_json::from_str(&body.unwrap()).unwrap();
        assert_eq!(json["reason"], "spam");
        assert_eq!(m.delta, -1);
        assert_eq!(m.score_after, -2);

        // metamod queue
        let (s4, a4, _) = serve_once(
            200,
            r#"{"err":0,"items":[{"action_id":9,"post_id":5,"topic_id":1,"excerpt":"x","reason":"spam","delta":-1,"score_after":-2,"created_at":"2026-01-01T00:00:00Z"}],"count":1,"pool_too_small":false}"#,
        )
        .await;
        let c4 = client_at(a4);
        let mq = c4.forum_metamod_queue("tok-8").await.unwrap();
        s4.await.unwrap();
        assert_eq!(mq.items.len(), 1);
        assert_eq!(mq.items[0].action_id, 9);

        // metamod vote
        let (s5, a5, recorded) = serve_once(200, r#"{"err":0}"#).await;
        let c5 = client_at(a5);
        let v = c5.forum_metamod_vote("tok-8", 9, "fair").await.unwrap();
        s5.await.unwrap();
        let (_, path, body) = recorded.lock().unwrap().clone().unwrap();
        assert_eq!(path, "/api/forum/metamod/9/vote");
        let json: serde_json::Value = serde_json::from_str(&body.unwrap()).unwrap();
        assert_eq!(json["verdict"], "fair");
        assert_eq!(v.err, 0);
    }
}