gen-bsky 0.1.22

A Library to generate and post a bluesky post
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
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
//! # BlogPost Module Documentation
//!
//! ## Overview
//!
//! The `BlogPost` module provides functionality for processing blog posts and
//! converting them into Bluesky social media posts. It handles front matter
//! parsing, link generation, short URL creation, and Bluesky post formatting
//! with character/grapheme limits.
//!
//! ## Core Components
//!
//! ### `BlogPost` Struct
//!
//! The main struct representing a blog post with all necessary metadata and
//! functionality for Bluesky integration.
//!
//! #### Fields
//!
//! - `path: PathBuf` - Path to the original blog post file
//! - `frontmatter: front_matter::FrontMatter` - Parsed front matter containing
//!   post metadata
//! - `post_link: Url` - Full URL link to the post
//! - `redirector: Redirector` - HTML redirector for creating short links
//! - `post_short_link: Option<Url>` - Generated short URL (if created)
//! - `bluesky_count: u8` - Counter tracking how many times this post has been
//!   written to Bluesky
//!
//! ### `BlogPostError` Enum
//!
//! Comprehensive error handling for various failure scenarios:
//!
//! #### Error Variants
//!
//! - `PostTooManyCharacters(String, usize)` - Post exceeds 300 character limit
//! - `PostTooManyGraphemes(String, usize)` - Post exceeds 300 grapheme limit
//! - `BlueSkyPostNotConstructed` - Bluesky record hasn't been built
//! - `PostBasenameNotSet` - Post filename/basename is missing
//! - `BskySdk(bsky_sdk::Error)` - Bluesky SDK errors
//! - `RedirectorError(link_bridge::RedirectorError)` - Link redirector errors
//! - `Io(std::io::Error)` - File I/O errors
//! - `SerdeJsonError(serde_json::error::Error)` - JSON serialization errors
//! - `DraftNotAllowed` - Draft posts are disabled
//! - `PostTooOld(Datetime)` - Post is older than minimum allowed date
//! - `Toml(toml::de::Error)` - TOML parsing errors
//! - `UrlParse(url::ParseError)` - URL parsing errors
//!
//! ## Public API
//!
//! ### Constructor
//!
//! ```rust
//! pub fn new(
//!     blog_path: &PathBuf,
//!     min_date: Datetime,
//!     allow_draft: bool,
//!     base_url: &Url,
//!     www_src_root: &Path,
//! ) -> Result<BlogPost, BlogPostError>
//! ```
//!
//! Creates a new `BlogPost` instance from a blog file path.
//!
//! **Parameters:**
//! - `blog_path` - Path to the blog post file relative to `www_src_root`
//! - `min_date` - Minimum publication date for posts
//! - `allow_draft` - Whether to allow processing of draft posts
//! - `base_url` - Base URL for generating post links
//! - `www_src_root` - Root directory containing blog content
//!
//! **Returns:** `Result<BlogPost, BlogPostError>`
//!
//! ### Accessor Methods
//!
//! ```rust
//! pub fn title(&self) -> &str
//! ```
//! Returns the post title from front matter.
//!
//! ### Core Functionality
//!
//! ```rust
//! pub async fn get_bluesky_record(&self) -> Result<RecordData, BlogPostError>
//! ```
//!
//! Generates a Bluesky `RecordData` structure from the blog post content.
//!
//! **Features:**
//! - Builds formatted post text with title, description, tags, and link
//! - Uses rich text processing to detect facets (mentions, links, hashtags)
//! - Validates character and grapheme limits (300 max)
//! - Creates proper Bluesky API record format
//!
//! ```rust
//! pub fn write_referrer_file_to(
//!     &mut self,
//!     store_dir: &Path,
//!     base_url: &Url,
//! ) -> Result<(), BlogPostError>
//! ```
//!
//! Creates a redirect HTML file and generates a short URL for the post.
//!
//! **Parameters:**
//! - `store_dir` - Directory to write the redirect file
//! - `base_url` - Base URL for constructing the short link
//!
//! ```rust
//! pub async fn write_bluesky_record_to(&mut self, store_dir: &Path) -> Result<(), BlogPostError>
//! ```
//!
//! Writes the Bluesky post record as JSON to the specified directory.
//!
//! **Features:**
//! - Generates unique filename using base62 encoding of path components
//! - Creates JSON file with `.post` extension
//! - Increments internal post counter
//! - Handles file I/O with proper error propagation
//!
//! ## Implementation Details
//!
//! ### Post Text Format
//!
//! The generated Bluesky post follows this format:
//! ```
//! {
//!     title
//! }
//!
//! {
//!     description
//! }
//! {
//!     tags
//! }
//!
//! {
//!     short_link_or_full_link
//! }
//! ```
//!
//! ### Character Limits
//!
//! - Maximum 300 characters (byte length)
//! - Maximum 300 graphemes (Unicode grapheme clusters)
//! - Both limits are enforced to ensure Bluesky compatibility
//!
//! ### Short Link Generation
//!
//! - Uses `link_bridge::Redirector` for HTML redirect creation
//! - Generates short URLs by trimming base paths
//! - Stores short link in `post_short_link` field for reuse
//!
//! ### Unique Post Naming
//!
//! Post files are named using base62 encoding of:
//! 1. Full post path UTF-16 sum
//! 2. Filename UTF-16 sum
//! 3. Directory path (without filename) UTF-16 sum
//!
//! This ensures unique filenames even for posts with similar names.
//!
//! ## Dependencies
//!
//! - `bsky_sdk` - Bluesky API integration and rich text processing
//! - `link_bridge` - URL redirection and short link generation
//! - `toml` - Front matter parsing
//! - `url` - URL parsing and manipulation
//! - `unicode_segmentation` - Proper grapheme counting
//! - `serde_json` - JSON serialization for post records
//! - `thiserror` - Structured error handling
//!
//! ## Usage Example
//!
//! ```rust
//! use std::path::PathBuf;
//!
//! use toml::value::Datetime;
//! use url::Url;
//!
//! // Create a new blog post
//! let blog_path = PathBuf::from("content/posts/my-post.md");
//! let min_date =
//!     Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
//! let base_url = Url::parse("https://example.com").unwrap();
//! let www_root = Path::new("./www");
//!
//! let mut post = BlogPost::new(
//!     &blog_path, min_date, false, // don't allow drafts
//!     &base_url, www_root,
//! )
//! .unwrap();
//!
//! // Generate short link
//! post.write_referrer_file_to(Path::new("./static"), &base_url)
//!     .unwrap();
//!
//! // Create and save Bluesky post
//! post.write_bluesky_record_to(Path::new("./output"))
//!     .await
//!     .unwrap();
//! ```
//!
//! ## Error Handling
//!
//! The module uses comprehensive error handling with the `BlogPostError` enum.
//! All errors are properly wrapped and provide context about the failure. The
//! `thiserror` crate is used for structured error definitions with automatic
//! `Display` and `Error` trait implementations.
//!
//! ## Logging
//!
//! The module includes extensive logging at various levels:
//! - `info!` - High-level operations
//! - `debug!` - Detailed processing information
//! - `trace!` - Fine-grained debugging data
//!
//! Enable logging to get insights into the post processing pipeline.

use std::{
    fs::File,
    path::{Path, PathBuf},
};

use chrono::{TimeZone, Utc};

pub(crate) mod front_matter;

use bsky_sdk::{
    api::{app::bsky::feed::post::RecordData, types::string::Datetime as BskyDatetime},
    rich_text::RichText,
};
use link_bridge::Redirector;
use thiserror::Error;
use toml::value::Datetime;
use unicode_segmentation::UnicodeSegmentation;
use url::Url;

/// Error enum for BlogPost type
#[non_exhaustive]
#[derive(Error, Debug)]
pub(super) enum BlogPostError {
    /// Generated post contains two many characters for a bluesky post.
    /// Reduce the size of the components contributing to the post such
    /// as description and tag list.
    #[error("bluesky post for `{0}` contains too many characters: {1}")]
    PostTooManyCharacters(String, usize),
    /// Generated post contains two many graphemes for a bluesky post.
    /// Reduce the size of the components contributing to the post such
    /// as description and tag list.
    #[error("bluesky post for `{0}` contains too many graphemes: {1}")]
    PostTooManyGraphemes(String, usize),
    /// The bluesky post record has not been constructed. Use
    /// the `get_bluesky_record` method to generate the bluesky post
    /// record.
    #[error("bluesky post has not been constructed")]
    BlueSkyPostNotConstructed,
    /// The post basename is has not been set.
    #[error("post basename is not set")]
    PostBasenameNotSet,
    /// Error reported by the Bluesky SDK library.
    #[error("bsky_sdk error says: {0:?}")]
    BskySdk(#[from] bsky_sdk::Error),
    /// Error reported by the link-bridge library
    #[error("link-bridge error says: {0:?}")]
    RedirectorError(#[from] link_bridge::RedirectorError),
    /// Error reported by IO library
    #[error("io error says: {0:?}")]
    Io(#[from] std::io::Error),
    /// Error reported by the serde_json library
    #[error("serde_json create_session error says: {0:?}")]
    SerdeJsonError(#[from] serde_json::error::Error),
    /// Draft posts not allowed
    #[error("processing of draft posts is not allowed")]
    DraftNotAllowed,

    /// Post too old
    #[error("Post is older than allowed by minimum date setting {0}")]
    PostTooOld(Datetime),

    /// Error reported by the Toml library.
    #[error("toml deserialization error says: {0:?}")]
    Toml(#[from] toml::de::Error),

    /// Error reported by the Url library.
    #[error("url error says: {0:?}")]
    UrlParse(#[from] url::ParseError),

    /// Error writing back to frontmatter.
    #[error("frontmatter write-back error: {0:?}")]
    FmWrite(#[from] crate::frontmatter_writeback::FmWriteError),
}

/// Type representing the blog post.
#[derive(Debug, Clone)]
pub(super) struct BlogPost {
    /// The path to the original blog post.
    path: PathBuf,
    /// The front matter from the blog post that is salient
    /// to the production of bluesky posts.
    frontmatter: front_matter::FrontMatter,
    /// The full link to the post.
    post_link: Url,
    /// The short link redirection HTML string
    redirector: Redirector,
    /// The generated short link URL for the post.
    post_short_link: Option<Url>,
    /// Count of bluesky post writing, increment each time a post is written.
    bluesky_count: u8,
}

/// Report values in private fields
impl BlogPost {
    pub fn title(&self) -> &str {
        self.frontmatter.title()
    }

    #[cfg(test)]
    pub fn bluesky_count(&self) -> u8 {
        self.bluesky_count
    }
}

impl BlogPost {
    pub fn new(
        blog_path: &PathBuf,
        min_date: Datetime,
        allow_draft: bool,
        base_url: &Url,
        www_src_root: &Path,
    ) -> Result<BlogPost, BlogPostError> {
        let blog_file = www_src_root.join(blog_path);

        let frontmatter = match front_matter::FrontMatter::read(&blog_file, min_date, allow_draft) {
            Ok(fm) => fm,
            Err(e) => match e {
                front_matter::FrontMatterError::DraftNotAllowed => {
                    return Err(BlogPostError::DraftNotAllowed)
                }
                front_matter::FrontMatterError::PostTooOld(md) => {
                    return Err(BlogPostError::PostTooOld(md))
                }
                front_matter::FrontMatterError::Io(e) => return Err(BlogPostError::Io(e)),
                front_matter::FrontMatterError::Toml(e) => return Err(BlogPostError::Toml(e)),
            },
        };

        let mut post_link = blog_path.clone();
        post_link.set_extension("");

        log::trace!("Post link with extension stripped: `{post_link:?}`");
        // Strip root and content prefix
        let post_link = post_link.as_path().to_string_lossy().to_string();
        log::trace!("Post link as string: `{post_link}`");
        let post_link = post_link
            .trim_start_matches(&www_src_root.to_string_lossy().to_string())
            .trim_start_matches('/')
            .trim_start_matches("content");

        log::trace!("Post link as trimmed: `{post_link}`");

        let link = base_url.join(post_link)?;

        // Initialise the short link html redirector
        let redirector = Redirector::new(post_link)?;

        Ok(BlogPost {
            path: blog_file.clone(),
            frontmatter,
            post_link: link,
            redirector,
            post_short_link: None,
            bluesky_count: 0,
        })
    }

    /// Get bluesky record based on frontmatter data.
    ///
    /// If `created_at_override` is `Some`, the provided `BskyDatetime` is used as
    /// `createdAt` instead of the current time.  This ensures the `.post` file's
    /// timestamp is stable across re-runs once `[bluesky].created` is written to the
    /// frontmatter.
    pub async fn get_bluesky_record(
        &self,
        created_at_override: Option<BskyDatetime>,
    ) -> Result<RecordData, BlogPostError> {
        log::info!("Blog post: {self:#?}");
        log::debug!("Building post text");
        let post_text = self.build_post_text()?;

        log::trace!("Post text: {post_text}");

        let rt = RichText::new_with_detect_facets(&post_text).await?;

        log::trace!("Rich text: {rt:#?}");

        let record_data = RecordData {
            created_at: created_at_override.unwrap_or_else(BskyDatetime::now),
            embed: None,
            entities: None,
            facets: rt.facets,
            labels: None,
            langs: None,
            reply: None,
            tags: None,
            text: rt.text,
        };

        log::trace!("{record_data:?}");

        Ok(record_data)
    }

    fn build_post_text(&self) -> Result<String, BlogPostError> {
        log::debug!(
            "Building post text with post dir: `{}`",
            self.path.display()
        );

        if log::log_enabled!(log::Level::Debug) {
            self.log_post_details();
        }

        let post_text = format!(
            "{}\n\n{} {}\n\n{}",
            self.frontmatter.title(),
            self.frontmatter.bluesky_description(),
            self.frontmatter.bluesky_tags().join(" "),
            if let Some(sl) = self.post_short_link.as_ref() {
                sl
            } else {
                &self.post_link
            }
        );

        if post_text.len() > 300 {
            return Err(BlogPostError::PostTooManyCharacters(
                self.frontmatter.title().to_string(),
                post_text.len(),
            ));
        }

        if post_text.graphemes(true).count() > 300 {
            return Err(BlogPostError::PostTooManyGraphemes(
                self.frontmatter.title().to_string(),
                post_text.graphemes(true).count(),
            ));
        }

        Ok(post_text)
    }

    /// Write the referrer file to the `store_dir` location.
    pub fn write_referrer_file_to(
        &mut self,
        store_dir: &Path,
        base_url: &Url,
        root: &Path,
    ) -> Result<(), BlogPostError> {
        log::debug!("Building link with `{base_url}` as root of url",);

        self.redirector.set_path(store_dir);

        let short_link = self.redirector.write_redirect()?;
        log::debug!("redirect written and short link returned: {short_link}");

        self.post_short_link = Some(
            base_url.join(
                short_link
                    .trim_start_matches(&root.to_string_lossy().to_string())
                    .trim_start_matches("/")
                    .trim_start_matches("static/"),
            )?,
        );
        log::debug!("Saved short post link {:#?}", self.post_short_link);
        Ok(())
    }

    /// Write the bluesky record to the `store_dir` location.
    /// The write function generates a short name based on post link
    /// and filename to ensure that similarly named posts have unique
    /// bluesky post names.
    ///
    /// Idempotency: if `[bluesky].created` is already set in the post's frontmatter,
    /// the write is skipped entirely (the draft was already generated on a previous run).
    pub async fn write_bluesky_record_to(&mut self, store_dir: &Path) -> Result<(), BlogPostError> {
        log::trace!("Store path to write to bluesky record: `{store_dir:#?}`");
        log::trace!(
            "Path for basename contains a filename: {:#?}",
            self.path.is_file()
        );

        // Primary idempotency guard: skip if frontmatter already has [bluesky].created.
        if self.frontmatter.bluesky_created().is_some() {
            log::debug!(
                "Skipping draft — [bluesky].created already set in `{}`",
                self.path.display()
            );
            return Ok(());
        }

        let Some(filename) = self.path.as_path().file_name() else {
            return Err(BlogPostError::PostBasenameNotSet);
        };
        let filename = filename.to_str().unwrap();

        // Write `created = <today>` into the blog post's TOML frontmatter.
        let today = super::today();
        crate::frontmatter_writeback::write_bluesky_date_field(&self.path, "created", today)?;
        log::debug!(
            "Wrote [bluesky].created = {} to `{}`",
            today,
            self.path.display()
        );

        // Build the BskyDatetime from today's date so createdAt is stable.
        let created_at_bsky = toml_date_to_bsky_datetime(today);

        let bluesky_post = match self.get_bluesky_record(Some(created_at_bsky)).await {
            Ok(p) => p,
            Err(e) => {
                log::warn!(
                    "failed to create bluesky record for `{}` because `{e}`",
                    self.title()
                );
                return Err(BlogPostError::BlueSkyPostNotConstructed);
            }
        };

        let postname = format!(
            "{}{}{}",
            base62::encode(self.post_link.path().encode_utf16().sum::<u16>()),
            base62::encode(filename.encode_utf16().sum::<u16>()),
            base62::encode(
                self.post_link
                    .path()
                    .trim_end_matches(filename)
                    .encode_utf16()
                    .sum::<u16>()
            )
        );

        log::trace!("Bluesky post: {bluesky_post:#?}");

        let post_file = format!("{postname}.post");
        let post_file = store_dir.to_path_buf().join(post_file);
        log::debug!("Write filename: `{filename}` as `{postname}`");
        log::debug!("Write file: `{}`", post_file.display());

        // Secondary guard: never overwrite an existing .post file.
        if !should_write_post_file(&post_file) {
            log::debug!(
                "Skipping write — post file already exists: `{}`",
                post_file.display()
            );
            return Ok(());
        }

        let file = File::create(post_file)?;

        // Include source_path so bsky post can write back [bluesky].published.
        let post_file_record = crate::post::bsky_post::PostFile {
            record: bluesky_post,
            source_path: Some(self.path.clone()),
        };
        serde_json::to_writer_pretty(&file, &post_file_record)?;
        file.sync_all()?;
        self.bluesky_count += 1;

        Ok(())
    }

    fn log_post_details(&self) {
        log::debug!("Post link: {}", self.post_link);
        log::debug!(
            "Length of post link: {} characters and {} graphemes",
            self.post_link.as_str().len(),
            self.post_link.as_str().graphemes(true).count()
        );
        log::debug!(
            "Length of post short link: {} characters and {} graphemes",
            self.post_short_link
                .as_ref()
                .map_or(0, |link| link.as_str().len()),
            self.post_short_link
                .as_ref()
                .map_or(0, |link| link.as_str().graphemes(true).count())
        );
        self.frontmatter.log_post_details();
    }
}

/// Convert a `toml::value::Datetime` (date-only, e.g. `2026-04-03`) to a `BskyDatetime`
/// set to midnight UTC on that date.  Falls back to `BskyDatetime::now()` if the TOML
/// datetime has no date component.
fn toml_date_to_bsky_datetime(dt: toml::value::Datetime) -> BskyDatetime {
    if let Some(d) = dt.date {
        if let Some(naive_date) =
            chrono::NaiveDate::from_ymd_opt(d.year as i32, d.month as u32, d.day as u32)
        {
            let naive_dt = naive_date.and_time(chrono::NaiveTime::MIN);
            let utc_dt = Utc.from_utc_datetime(&naive_dt).fixed_offset();
            return BskyDatetime::new(utc_dt);
        }
    }
    BskyDatetime::now()
}

/// Returns `true` if a bluesky post file should be written (i.e. it does not yet exist).
/// Returning `false` prevents overwriting an existing file and re-generating a new
/// `createdAt` timestamp, which would mark the file as changed and cause an infinite CI push loop.
fn should_write_post_file(path: &Path) -> bool {
    !path.exists()
}

#[cfg(test)]
mod tests {
    use std::{fs, str::FromStr};

    use log::LevelFilter;
    use toml::value::Datetime;

    use super::*;
    use crate::util::test_utils;

    fn create_test_blog_file(path: &Path, filename: &str, content: &str) -> PathBuf {
        if !path.exists() {
            fs::create_dir_all(path).unwrap();
        }

        let file_path = path.join(filename);
        fs::write(&file_path, content).expect("Failed to write test file");
        file_path
    }

    fn create_test_frontmatter_content() -> String {
        r#"+++
title = "Test Blog Post"
date = 2024-01-15
description = "A test blog post for unit testing"
draft = false
[taxonomies]
tags = ["rust", "testing"]
+++"#
            .to_string()
    }

    #[test]
    fn test_blog_post_new_success() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Trace);
        let content = format!(
            "{}\n\nThis is the blog post content.",
            create_test_frontmatter_content()
        );
        log::debug!("Blog post content: {content:#?}");

        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "test-post.md", &content);
        log::debug!("Path to blog_file: `{blog_file:?}`");

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
        log::debug!("Minimum date: {min_date:#?}");

        let result = BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path());
        log::debug!("BlogPost::new result: {result:?}");

        assert!(result.is_ok());
        let post = result.unwrap();
        assert_eq!(post.title(), "Test Blog Post");
        assert_eq!(post.bluesky_count(), 0);
        assert_eq!(
            post.post_link.as_str(),
            "https://www.example.com/blog/test-post"
        );
    }

    #[test]
    fn test_blog_post_new_with_directory_path() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content_dir = temp_dir.path().join("content").join("posts");
        fs::create_dir_all(&content_dir).unwrap();

        let blog_path = PathBuf::from("content/posts/");
        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();

        let result = BlogPost::new(&blog_path, min_date, false, &base_url, temp_dir.path());

        if let Ok(post) = result {
            assert_eq!(
                post.post_link.as_str(),
                "https://www.example.com/blog/posts/"
            );
        }
    }

    #[test]
    fn test_blog_post_draft_not_allowed_error() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let mut content = create_test_frontmatter_content();
        content = content.replace("draft = false", "draft = true");
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "draft-post.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();

        let result = BlogPost::new(
            &blog_file,
            min_date,
            false, // don't allow drafts
            &base_url,
            temp_dir.path(),
        );
        log::debug!("Result of new post generation:/n{result:#?}");
        assert!(matches!(result, Err(BlogPostError::DraftNotAllowed)));
    }

    #[test]
    fn test_blog_post_too_old_error() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = create_test_frontmatter_content();
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "old-post.md", &content);

        let min_date = Datetime::from_str("2024-12-01T00:00:00Z").unwrap(); // Future date

        let result = BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path());

        assert!(matches!(result, Err(BlogPostError::PostTooOld(_))));
    }

    #[tokio::test]
    async fn test_get_bluesky_record_success() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = format!(
            "{}\n\nThis is the blog post content.",
            create_test_frontmatter_content()
        );
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "test-post.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();

        let post = BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        let result = post.get_bluesky_record(None).await;
        assert!(result.is_ok());

        let record = result.unwrap();
        assert!(record.text.contains("Test Blog Post"));
        assert!(record
            .text
            .contains("https://www.example.com/blog/test-post"));
        assert!(record.text.len() <= 300);
    }

    #[tokio::test]
    async fn test_build_post_text_format() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Trace);
        let content = format!(
            "{}\n\nThis is the blog post content.",
            create_test_frontmatter_content()
        );
        log::debug!("Content of blog file: `{content}`");
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "format-test.md", &content);
        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();

        let post = BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        let post_text = post.build_post_text().unwrap();
        log::debug!("Generated post text:\n{post_text:#?}");

        // Check format: title + double newline + description + tags + double newline +
        // link
        let lines: Vec<&str> = post_text.split("\n\n").collect();
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0], "Test Blog Post");
        assert!(lines[1].contains("A test blog post for unit testing"));
        assert!(lines[1].contains("#Rust #Testing"));
        assert_eq!(lines[2], "https://www.example.com/blog/format-test");
    }

    #[tokio::test]
    async fn test_post_text_too_many_characters() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Trace);

        // Create content that will exceed 300 characters
        let long_description = "A".repeat(250);
        let long_content = format!(
            r#"+++
title = "Very Long Title That Will Cause Character Limit Issues"
date = 2024-01-15T10:30:00Z
description = "{long_description}"
tags = ["verylongtag1", "verylongtag2", "verylongtag3", "verylongtag4"]
draft = false
+++

Long content here."#
        );

        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "long-post.md", &long_content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();

        let post_res = BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path());
        log::debug!("Post result: {post_res:#?}");
        let post = post_res.unwrap();

        let result = post.build_post_text();
        log::debug!("Result: {result:?}");
        assert!(matches!(
            result,
            Err(BlogPostError::PostTooManyCharacters(_, _))
        ));
    }

    #[test]
    fn test_write_referrer_file_to() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = format!("{}\n\nContent here.", create_test_frontmatter_content());
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "referrer-test.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
        let store_dir = temp_dir.path().join("static");
        fs::create_dir_all(&store_dir).unwrap();

        let mut post =
            BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        assert!(post.post_short_link.is_none());

        let result = post.write_referrer_file_to(&store_dir, &base_url, temp_dir.path());
        assert!(result.is_ok());
        assert!(post.post_short_link.is_some());
        let short_link = post.post_short_link.unwrap();
        log::debug!("The short link is: `{:?}`", short_link.as_str());
        assert!(short_link.as_str().starts_with("https://www.example.com/"));
    }

    #[tokio::test]
    async fn test_write_bluesky_record_to() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = format!("{}\n\nContent here.", create_test_frontmatter_content());
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "bluesky-test.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
        let store_dir = temp_dir.path().join("posts");
        fs::create_dir_all(&store_dir).unwrap();

        let mut post =
            BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        assert_eq!(post.bluesky_count(), 0);

        let result = post.write_bluesky_record_to(&store_dir).await;
        assert!(result.is_ok());
        assert_eq!(post.bluesky_count(), 1);

        // Check that a .post file was created
        let post_files: Vec<_> = fs::read_dir(&store_dir)
            .unwrap()
            .filter_map(|entry| {
                let entry = entry.ok()?;
                let path = entry.path();
                if path.extension()? == "post" {
                    Some(path)
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(post_files.len(), 1);

        // Verify the JSON content
        let json_content = fs::read_to_string(&post_files[0]).unwrap();
        let record_data: serde_json::Value = serde_json::from_str(&json_content).unwrap();
        log::debug!("Record data: `{record_data}`");
        assert!(record_data.get("text").is_some());
        assert!(record_data.get("createdAt").is_some());
    }

    #[tokio::test]
    async fn test_write_bluesky_record_multiple_times() {
        // Now that write_bluesky_record_to is idempotent, repeated calls for the same
        // post must not overwrite the file or re-increment bluesky_count.
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = format!("{}\n\nContent here.", create_test_frontmatter_content());
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "multi-test.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
        let store_dir = temp_dir.path().join("posts");
        fs::create_dir_all(&store_dir).unwrap();

        let mut post =
            BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        post.write_bluesky_record_to(&store_dir).await.unwrap();
        assert_eq!(post.bluesky_count(), 1, "first write should succeed");

        // Second and third calls: file already exists — skip silently
        post.write_bluesky_record_to(&store_dir).await.unwrap();
        assert_eq!(post.bluesky_count(), 1, "count must not change on repeat");

        post.write_bluesky_record_to(&store_dir).await.unwrap();
        assert_eq!(post.bluesky_count(), 1, "count must not change on repeat");
    }

    // #[tokio::test]
    // async fn test_post_basename_not_set_error() {
    //     let (temp_dir, base_url) =
    // test_utils::setup_test_environment(LevelFilter::Trace);     let content =
    // format!("{}\n\nContent here.", create_test_frontmatter_content());
    //     let blog_path = temp_dir.path().join("content").join("blog/");
    //     let _blog_file = create_test_blog_file(&blog_path, "basename-test.md",
    // &content);

    //     // Create a blog path that doesn't have a filename
    //     let _min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
    //     let store_dir = temp_dir.path().join("posts");
    //     let mut fm = FrontMatter::new("Test", "Test desc");
    //     let taxonomies =
    // front_matter::Taxonomies::new(vec!["#test".to_string()]);
    //     fm.taxonomies = Some(taxonomies);
    //     fs::create_dir_all(&store_dir).unwrap();

    //     let mut post = BlogPost {
    //         path: blog_path,
    //         frontmatter: fm,
    //         post_link: base_url.clone(),
    //         redirector: link_bridge::Redirector::new("/test").unwrap(),
    //         post_short_link: None,
    //         bluesky_count: 0,
    //     };

    //     let result = post.write_bluesky_record_to(&store_dir).await;
    //     log::debug!("Result says: `{result:?}`");
    //     assert!(matches!(result, Err(BlogPostError::PostBasenameNotSet)));
    // }

    #[test]
    fn test_error_display_formatting() {
        let error = BlogPostError::PostTooManyCharacters("Test Post".to_string(), 350);
        assert!(format!("{error}").contains("Test Post"));
        assert!(format!("{error}").contains("350"));

        let error = BlogPostError::PostTooManyGraphemes("Another Post".to_string(), 400);
        assert!(format!("{error}").contains("Another Post"));
        assert!(format!("{error}").contains("400"));

        let date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
        let error = BlogPostError::PostTooOld(date);
        assert!(format!("{error}").contains("2024-01-01T00:00:00Z"));
    }

    #[test]
    fn test_blog_post_accessors() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = format!("{}\n\nContent here.", create_test_frontmatter_content());
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "accessor-test.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();

        let post = BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        assert_eq!(post.title(), "Test Blog Post");
        assert_eq!(post.bluesky_count(), 0);
    }

    #[test]
    fn test_unicode_grapheme_handling() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);

        // Create content with Unicode characters that have different byte vs grapheme
        // counts
        let unicode_content = r##"+++
title = "Test 👋 Post 🦀"
date = 2024-01-15T10:30:00Z
description = "Testing unicode: 🚀 émojis and àccénts"
tags = ["#test", "#unicode"]
draft = false
+++

Content with unicode characters."##
            .to_string();

        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "unicode-test.md", &unicode_content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();

        let post = BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        let post_text = post.build_post_text().unwrap();

        // Verify both character and grapheme counts are within limits
        assert!(post_text.len() <= 300);
        assert!(post_text.graphemes(true).count() <= 300);

        // Verify Unicode characters are preserved
        assert!(post_text.contains("👋"));
        assert!(post_text.contains("🦀"));
        assert!(post_text.contains("🚀"));
        assert!(post_text.contains("émojis"));
        assert!(post_text.contains("àccénts"));
    }

    // RED: frontmatter created/published tracking (issue #909)

    fn create_test_frontmatter_with_bluesky_created() -> String {
        r#"+++
title = "Test Blog Post"
date = 2024-01-15
description = "A test blog post for unit testing"
draft = false
[taxonomies]
tags = ["rust", "testing"]
[bluesky]
description = "My bsky description"
created = 2026-04-03
+++"#
            .to_string()
    }

    #[tokio::test]
    async fn test_write_bluesky_record_skips_when_created_in_frontmatter() {
        // If [bluesky].created is already set, write_bluesky_record_to must be a no-op.
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = format!(
            "{}\n\nThis is the blog post content.",
            create_test_frontmatter_with_bluesky_created()
        );
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "drafted-post.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
        let store_dir = temp_dir.path().join("posts");
        fs::create_dir_all(&store_dir).unwrap();

        let mut post =
            BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        // The frontmatter already has created — draft should be skipped entirely
        post.write_bluesky_record_to(&store_dir).await.unwrap();
        assert_eq!(
            post.bluesky_count(),
            0,
            "bluesky_count must stay 0 when frontmatter.bluesky.created is already set"
        );

        // No .post file should have been created
        let post_files: Vec<_> = fs::read_dir(&store_dir)
            .unwrap()
            .filter_map(|e| {
                let p = e.ok()?.path();
                if p.extension()? == "post" {
                    Some(p)
                } else {
                    None
                }
            })
            .collect();
        assert_eq!(
            post_files.len(),
            0,
            "no .post files should be created when already drafted"
        );
    }

    #[tokio::test]
    async fn test_write_bluesky_record_sets_created_in_frontmatter() {
        // After write_bluesky_record_to, the .md file must have [bluesky].created set.
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = format!(
            "{}\n\nThis is the blog post content.",
            create_test_frontmatter_content()
        );
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "new-post.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
        let store_dir = temp_dir.path().join("posts");
        fs::create_dir_all(&store_dir).unwrap();

        let mut post =
            BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        post.write_bluesky_record_to(&store_dir).await.unwrap();
        assert_eq!(post.bluesky_count(), 1);

        // The .md file should now have [bluesky].created
        let md_content = fs::read_to_string(&blog_file).unwrap();
        assert!(
            md_content.contains("created ="),
            ".md file should have created date: {md_content}"
        );
    }

    #[tokio::test]
    async fn test_write_bluesky_record_created_at_matches_frontmatter_created() {
        // The .post file's createdAt must be derived from frontmatter created date.
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = format!(
            "{}\n\nThis is the blog post content.",
            create_test_frontmatter_content()
        );
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "ts-post.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
        let store_dir = temp_dir.path().join("posts");
        fs::create_dir_all(&store_dir).unwrap();

        let mut post =
            BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        post.write_bluesky_record_to(&store_dir).await.unwrap();

        // Read the .post file and check createdAt starts with the today's date
        let post_files: Vec<_> = fs::read_dir(&store_dir)
            .unwrap()
            .filter_map(|e| {
                let p = e.ok()?.path();
                if p.extension()? == "post" {
                    Some(p)
                } else {
                    None
                }
            })
            .collect();
        assert_eq!(post_files.len(), 1);
        let json_content = fs::read_to_string(&post_files[0]).unwrap();
        let record: serde_json::Value = serde_json::from_str(&json_content).unwrap();
        let created_at = record.get("createdAt").unwrap().as_str().unwrap();
        // The created date in frontmatter is today; createdAt should start with today's date
        let md_content = fs::read_to_string(&blog_file).unwrap();
        // Extract "created = YYYY-MM-DD" from the md
        let created_line = md_content
            .lines()
            .find(|l| l.trim_start().starts_with("created ="))
            .expect("created line should exist in .md file");
        let date_str = created_line.split('=').nth(1).unwrap().trim();
        assert!(
            created_at.starts_with(date_str),
            "createdAt `{created_at}` should start with frontmatter date `{date_str}`"
        );
    }

    // RED: should_write_post_file pure function (issue #906)

    #[test]
    fn test_should_write_post_file_when_absent() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("nonexistent.post");
        assert!(
            should_write_post_file(&path),
            "should return true when file does not exist"
        );
    }

    #[test]
    fn test_should_not_write_post_file_when_exists() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("existing.post");
        fs::write(&path, b"{}").unwrap();
        assert!(
            !should_write_post_file(&path),
            "should return false when file already exists"
        );
    }

    // GREEN: write_bluesky_record_to idempotency (issue #906)
    // Second and third calls must skip the write — bluesky_count stays at 1.

    #[tokio::test]
    async fn test_write_bluesky_record_to_is_idempotent() {
        let (temp_dir, base_url) = test_utils::setup_test_environment(LevelFilter::Debug);
        let content = format!("{}\n\nContent here.", create_test_frontmatter_content());
        let blog_path = temp_dir.path().join("content").join("blog");
        let blog_file = create_test_blog_file(&blog_path, "idempotent-test.md", &content);

        let min_date = Datetime::from_str("2024-01-01T00:00:00Z").unwrap();
        let store_dir = temp_dir.path().join("posts");
        fs::create_dir_all(&store_dir).unwrap();

        let mut post =
            BlogPost::new(&blog_file, min_date, false, &base_url, temp_dir.path()).unwrap();

        post.write_bluesky_record_to(&store_dir).await.unwrap();
        assert_eq!(
            post.bluesky_count(),
            1,
            "first write should increment count"
        );

        post.write_bluesky_record_to(&store_dir).await.unwrap();
        assert_eq!(
            post.bluesky_count(),
            1,
            "second write must skip — file already exists"
        );

        post.write_bluesky_record_to(&store_dir).await.unwrap();
        assert_eq!(
            post.bluesky_count(),
            1,
            "third write must skip — file already exists"
        );

        // Exactly one .post file on disk
        let post_files: Vec<_> = fs::read_dir(&store_dir)
            .unwrap()
            .filter_map(|e| {
                let p = e.ok()?.path();
                if p.extension()? == "post" {
                    Some(p)
                } else {
                    None
                }
            })
            .collect();
        assert_eq!(post_files.len(), 1, "exactly one .post file should exist");
    }
}