xmaster 1.6.0

Enterprise-grade X/Twitter CLI — post, reply, like, retweet, DM, search, and more
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
use serde::Serialize;

/// Heuristic post quality analysis. Checks for common patterns that hurt or
/// help reach based on estimated 2026 X algorithm signals. This is NOT a direct
/// algorithm score — it's a quality lint.
///
/// Reference: xai-org/x-algorithm (January 2026, Grok-based transformer).
/// Exact weight constants are NOT published. Estimates below from code structure
/// + empirical data.
///
/// Top positive signals (estimated): follow_author (~30x), share_via_dm (~25x),
///   reply (~20x), share_via_copy_link (~20x), quote (~18x), profile_click (~12x)
/// Negative signals: report (~-369x), block (~-74x), mute (~-40x), not_interested (~-20x)
pub const ALGORITHM_SOURCE: &str = "xai-org/x-algorithm (January 2026, Grok-based)";

// ---------------------------------------------------------------------------
// Context passed into analyze()
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize)]
pub enum PostMode {
    Standalone,
    Reply,
    Quote,
}

impl Default for PostMode {
    fn default() -> Self {
        Self::Standalone
    }
}

#[derive(Debug, Clone, Serialize)]
pub enum MediaKind {
    Image,
    Video,
    Gif,
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct AnalyzeContext {
    pub goal: Option<String>,
    pub mode: Option<PostMode>,
    pub has_media: bool,
    pub media_kind: Option<MediaKind>,
    pub has_poll: bool,
    pub target_text: Option<String>,
    pub author_voice: Option<String>,
    /// Whether the user has X Premium (drives char limit: 25k vs 280).
    pub premium: bool,
}

impl AnalyzeContext {
    pub fn goal_str(&self) -> Option<&str> {
        self.goal.as_deref()
    }

    pub fn is_reply(&self) -> bool {
        matches!(self.mode, Some(PostMode::Reply))
    }

    pub fn is_quote(&self) -> bool {
        matches!(self.mode, Some(PostMode::Quote))
    }
}

// ---------------------------------------------------------------------------
// Proxy signal scores
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize)]
pub struct ProxyScores {
    pub reply: f32,
    pub quote: f32,
    pub profile_click: f32,
    pub follow_author: f32,
    pub share_via_dm: f32,
    pub share_via_copy_link: f32,
    pub dwell: f32,
    pub media_expand: f32,
    pub negative_risk: f32,
}

#[derive(Debug, Clone, Serialize)]
pub struct GoalScores {
    pub replies: u32,
    pub quotes: u32,
    pub shares: u32,
    pub follows: u32,
    pub impressions: u32,
}

// ---------------------------------------------------------------------------
// PreflightResult
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize)]
pub struct PreflightResult {
    pub text: String,
    pub score: u32,
    pub grade: String,
    pub issues: Vec<Issue>,
    pub suggestions: Vec<String>,
    pub features: FeatureVector,
    pub suggested_next_commands: Vec<String>,
    pub proxy_scores: ProxyScores,
    pub goal_scores: GoalScores,
}

#[derive(Debug, Clone, Serialize)]
pub struct Issue {
    pub severity: Severity,
    pub code: String,
    pub message: String,
    pub fix: Option<String>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub enum Severity {
    Critical,
    Warning,
    Info,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Severity::Critical => write!(f, "CRITICAL"),
            Severity::Warning => write!(f, "WARNING"),
            Severity::Info => write!(f, "INFO"),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct FeatureVector {
    pub char_count: usize,
    pub word_count: usize,
    pub has_link: bool,
    pub link_position: Option<String>,
    pub has_media: bool,
    pub hashtag_count: usize,
    pub has_question: bool,
    pub has_numbers: bool,
    pub has_cta: bool,
    pub hook_strength: u32,
    pub line_count: usize,
    pub starts_with_i: bool,
    pub content_type_guess: String,
    pub est_dwell_seconds: f64,
    pub sentiment: String,
}

// ---------------------------------------------------------------------------
// Core analysis
// ---------------------------------------------------------------------------

pub fn analyze(text: &str, ctx: &AnalyzeContext) -> PreflightResult {
    let trimmed = text.trim();
    let mut features = extract_features(trimmed);
    let goal = ctx.goal_str();

    if ctx.has_media {
        features.has_media = true;
    }

    let mut issues = Vec::new();
    let mut score: i32 = 70;

    // --- Critical issues (score -= 30) ---
    if trimmed.is_empty() {
        issues.push(Issue {
            severity: Severity::Critical,
            code: "empty_content".into(),
            message: "Tweet is empty or whitespace-only".into(),
            fix: Some("Add tweet text".into()),
        });
        score -= 30;
    }

    let char_limit = if ctx.premium { 25_000 } else { 280 };
    if features.char_count > char_limit {
        issues.push(Issue {
            severity: Severity::Critical,
            code: "over_limit".into(),
            message: format!(
                "Post is {} characters (limit: {})",
                features.char_count, char_limit
            ),
            fix: Some(format!(
                "Remove {} characters",
                features.char_count - char_limit
            )),
        });
        score -= 30;
    }

    if features.has_link && features.link_position.as_deref() == Some("body") {
        issues.push(Issue {
            severity: Severity::Critical,
            code: "link_in_body".into(),
            message: "External link in tweet body kills reach — X suppresses linked tweets".into(),
            fix: Some("Move the link to a reply instead".into()),
        });
        score -= 30;
    }

    // --- Warning issues (score -= 15) ---
    let first_line = trimmed.lines().next().unwrap_or("");
    let weak_openers = ["I ", "So ", "Just ", "The "];
    if weak_openers.iter().any(|w| first_line.starts_with(w)) {
        issues.push(Issue {
            severity: Severity::Warning,
            code: "weak_hook".into(),
            message: format!(
                "Weak opening — \"{}...\" doesn't grab attention",
                crate::utils::safe_truncate(first_line, 30)
            ),
            fix: Some("Lead with a number, question, or bold claim".into()),
        });
        score -= 15;
    }

    let lower = trimmed.to_lowercase();
    let bait_phrases = ["like if", "rt if", "follow for"];
    if bait_phrases.iter().any(|b| lower.contains(b)) {
        issues.push(Issue {
            severity: Severity::Warning,
            code: "engagement_bait".into(),
            message: "Engagement bait detected — X algorithm penalizes this".into(),
            fix: Some("Remove explicit engagement requests".into()),
        });
        score -= 15;
    }

    if features.hashtag_count > 2 {
        issues.push(Issue {
            severity: Severity::Warning,
            code: "excessive_hashtags".into(),
            message: format!(
                "{} hashtags — more than 2 looks spammy and hurts reach",
                features.hashtag_count
            ),
            fix: Some("Keep to 1-2 relevant hashtags max".into()),
        });
        score -= 15;
    }

    if !features.has_numbers && !has_proper_nouns(trimmed) {
        issues.push(Issue {
            severity: Severity::Warning,
            code: "low_specificity".into(),
            message: "No numbers, names, or data — specificity drives engagement".into(),
            fix: Some("Add a concrete number, name, or data point".into()),
        });
        score -= 15;
    }

    if features.char_count < 30 && !features.has_media && !features.has_question {
        issues.push(Issue {
            severity: Severity::Info,
            code: "too_short".into(),
            message: "Very short post — longer content drives more dwell time (a scoring signal)"
                .into(),
            fix: Some("Consider adding depth — the algorithm rewards dwell time".into()),
        });
        score -= 5;
    }

    if trimmed.starts_with('@') {
        issues.push(Issue {
            severity: Severity::Warning,
            code: "starts_with_mention".into(),
            message: "Starting with @mention limits visibility to mutual followers".into(),
            fix: Some("Put a word before the @mention, e.g. \".@user\"".into()),
        });
        score -= 15;
    }

    // --- Info issues (score -= 5) ---
    if !features.has_question {
        issues.push(Issue {
            severity: Severity::Info,
            code: "no_question".into(),
            message: "No question mark — questions drive replies (~20x weight, estimated)".into(),
            fix: Some("Consider ending with a question to invite discussion".into()),
        });
        score -= 5;
    }

    if features.line_count <= 1 && features.char_count > 100 {
        issues.push(Issue {
            severity: Severity::Info,
            code: "no_formatting".into(),
            message: "Wall of text — line breaks improve readability and stop-rate".into(),
            fix: Some("Break into 2-3 short lines".into()),
        });
        score -= 5;
    }

    if trimmed == lower && trimmed.chars().any(|c| c.is_alphabetic()) {
        issues.push(Issue {
            severity: Severity::Info,
            code: "all_lowercase".into(),
            message: "All lowercase — proper capitalization looks more authoritative".into(),
            fix: None,
        });
        score -= 5;
    }

    // --- Positive signals ---
    if features.has_numbers {
        score += 10;
    }
    if features.has_question {
        score += 5;
        if goal == Some("replies") {
            score += 10;
        }
    }
    if features.char_count > 0 && features.char_count < 200 {
        score += 5;
    }
    if features.line_count > 1 {
        score += 5;
    }
    if features.hook_strength >= 70 {
        score += 10;
    }

    if features.est_dwell_seconds >= 10.0 {
        score += 5;
    }

    // --- Sentiment check ---
    if features.sentiment == "negative" {
        issues.push(Issue {
            severity: Severity::Warning,
            code: "negative_sentiment".into(),
            message: "Combative or negative tone — Grok predicts P(block) and P(mute) and suppresses pre-emptively".into(),
            fix: Some("Reframe constructively — critique the idea, not the person".into()),
        });
        score -= 15;
    } else if features.sentiment == "mixed" {
        issues.push(Issue {
            severity: Severity::Info,
            code: "mixed_sentiment".into(),
            message: "Mildly negative language detected — may elevate P(mute) prediction".into(),
            fix: Some(
                "Consider softening — the algorithm penalises predicted negative reactions".into(),
            ),
        });
        score -= 5;
    }

    let score = score.clamp(0, 100) as u32;
    let grade = match score {
        90..=100 => "A",
        75..=89 => "B",
        60..=74 => "C",
        40..=59 => "D",
        _ => "F",
    }
    .to_string();

    let proxy_scores = estimate_proxies(trimmed, &features, ctx);
    let goal_scores = score_goals(&proxy_scores);
    let suggestions = suggest_improvements(&issues, &features, &proxy_scores, goal);
    let suggested_next_commands = build_next_commands(trimmed, score);

    let display_text = if trimmed.chars().count() > 200 {
        format!("{}...", crate::utils::safe_truncate(trimmed, 200))
    } else {
        trimmed.to_string()
    };

    PreflightResult {
        text: display_text,
        score,
        grade,
        issues,
        suggestions,
        features,
        suggested_next_commands,
        proxy_scores,
        goal_scores,
    }
}

// ---------------------------------------------------------------------------
// Proxy signal estimation
// ---------------------------------------------------------------------------

fn estimate_proxies(text: &str, features: &FeatureVector, ctx: &AnalyzeContext) -> ProxyScores {
    let lower = text.to_lowercase();

    let p_reply = {
        let mut s: f32 = 0.15;
        if features.has_question {
            s += 0.30;
        }
        let open_ended = ["what", "how", "why", "which", "where", "who"];
        if open_ended
            .iter()
            .any(|w| lower.starts_with(w) || lower.contains(&format!(" {w} ")))
        {
            s += 0.10;
        }
        let debate = [
            "unpopular opinion",
            "hot take",
            "controversial",
            "change my mind",
            "am i wrong",
            "disagree",
            "debate",
        ];
        if debate.iter().any(|d| lower.contains(d)) {
            s += 0.15;
        }
        if features.has_numbers || has_proper_nouns(text) {
            s += 0.05;
        }
        if ctx.is_reply() {
            s += 0.10;
        }
        s.min(1.0)
    };

    let p_quote = {
        let mut s: f32 = 0.08;
        if features.content_type_guess == "data" {
            s += 0.20;
        }
        let contrarian = [
            "actually",
            "most people",
            "nobody talks about",
            "the truth is",
            "unpopular",
        ];
        if contrarian.iter().any(|c| lower.contains(c)) {
            s += 0.15;
        }
        if lower.contains("1.") || lower.contains("1)") || lower.contains("step 1") {
            s += 0.10;
        }
        if features.word_count <= 30 && features.hook_strength >= 60 {
            s += 0.10;
        }
        if ctx.is_quote() {
            s += 0.10;
        }
        s.min(1.0)
    };

    let p_profile_click = {
        let mut s: f32 = 0.10;
        let curiosity = [
            "i spent",
            "after years of",
            "i've been",
            "here's what i learned",
            "lessons from",
        ];
        if curiosity.iter().any(|c| lower.contains(c)) {
            s += 0.20;
        }
        let authority = [
            "ceo", "founder", "built", "shipped", "years", "clients", "revenue", "raised",
        ];
        if authority.iter().any(|a| lower.contains(a)) {
            s += 0.10;
        }
        if ctx.author_voice.is_some() {
            s += 0.05;
        }
        if features.hook_strength >= 70 {
            s += 0.10;
        }
        s.min(1.0)
    };

    let p_follow = {
        let mut s: f32 = 0.05;
        if features.content_type_guess == "how-to" || features.content_type_guess == "data" {
            s += 0.15;
        }
        if lower.contains("thread") || lower.contains("1.") {
            s += 0.10;
        }
        if features.has_numbers && has_proper_nouns(text) {
            s += 0.10;
        }
        s += p_profile_click * 0.2;
        s.min(1.0)
    };

    let p_dm_share = {
        let mut s: f32 = 0.05;
        let practical = [
            "how to",
            "step by step",
            "guide",
            "tutorial",
            "template",
            "checklist",
            "framework",
            "playbook",
            "here's how",
            "hack",
            "trick",
            "tip",
        ];
        if practical.iter().any(|p| lower.contains(p)) {
            s += 0.25;
        }
        let insider = [
            "nobody talks about",
            "most people don't know",
            "insider",
            "behind the scenes",
            "secret",
            "hidden",
            "underrated",
        ];
        if insider.iter().any(|i| lower.contains(i)) {
            s += 0.20;
        }
        if features.content_type_guess == "data" {
            s += 0.15;
        }
        s.min(1.0)
    };

    let p_link_share = {
        let mut s: f32 = 0.05;
        if features.word_count <= 25 && features.hook_strength >= 60 {
            s += 0.15;
        }
        if features.has_numbers && features.content_type_guess == "data" {
            s += 0.15;
        }
        if features.content_type_guess == "announcement" {
            s += 0.15;
        }
        s.min(1.0)
    };

    let p_dwell = {
        let mut s: f32 = (features.est_dwell_seconds as f32 / 30.0).min(0.6);
        if features.line_count > 2 {
            s += 0.10;
        }
        if features.has_media {
            s += 0.15;
        }
        if ctx.has_poll {
            s += 0.10;
        }
        s.min(1.0)
    };

    let p_media_expand = if features.has_media {
        let mut s: f32 = 0.40;
        match ctx.media_kind {
            Some(MediaKind::Video) => s += 0.25,
            Some(MediaKind::Gif) => s += 0.15,
            Some(MediaKind::Image) => s += 0.10,
            None => {}
        }
        s.min(1.0)
    } else {
        0.0
    };

    let p_negative = {
        let mut s: f32 = 0.0;
        if features.sentiment == "negative" {
            s += 0.40;
        } else if features.sentiment == "mixed" {
            s += 0.15;
        }
        let bait = ["like if", "rt if", "follow for"];
        if bait.iter().any(|b| lower.contains(b)) {
            s += 0.20;
        }
        let attacks = ["you're wrong", "shut up", "stfu", "cope", "ratio", "l + ratio"];
        if attacks.iter().any(|a| lower.contains(a)) {
            s += 0.25;
        }
        s.min(1.0)
    };

    ProxyScores {
        reply: p_reply,
        quote: p_quote,
        profile_click: p_profile_click,
        follow_author: p_follow,
        share_via_dm: p_dm_share,
        share_via_copy_link: p_link_share,
        dwell: p_dwell,
        media_expand: p_media_expand,
        negative_risk: p_negative,
    }
}

// ---------------------------------------------------------------------------
// Goal scoring
// ---------------------------------------------------------------------------

fn score_goals(proxies: &ProxyScores) -> GoalScores {
    let neg_penalty = 1.0 - (proxies.negative_risk * 0.6);

    let replies = ((proxies.reply * 0.65
        + proxies.dwell * 0.15
        + proxies.profile_click * 0.10
        + proxies.quote * 0.10)
        * neg_penalty
        * 100.0) as u32;

    let quotes = ((proxies.quote * 0.55
        + proxies.share_via_copy_link * 0.20
        + proxies.profile_click * 0.15
        + proxies.reply * 0.10)
        * neg_penalty
        * 100.0) as u32;

    let shares = ((proxies.share_via_dm * 0.45
        + proxies.share_via_copy_link * 0.35
        + proxies.dwell * 0.10
        + proxies.follow_author * 0.10)
        * neg_penalty
        * 100.0) as u32;

    let follows = ((proxies.follow_author * 0.50
        + proxies.profile_click * 0.25
        + proxies.share_via_dm * 0.15
        + proxies.dwell * 0.10)
        * neg_penalty
        * 100.0) as u32;

    let impressions = ((proxies.dwell * 0.25
        + proxies.reply * 0.20
        + proxies.share_via_dm * 0.15
        + proxies.share_via_copy_link * 0.10
        + proxies.quote * 0.10
        + proxies.media_expand * 0.10
        + proxies.follow_author * 0.10)
        * neg_penalty
        * 100.0) as u32;

    GoalScores {
        replies: replies.min(100),
        quotes: quotes.min(100),
        shares: shares.min(100),
        follows: follows.min(100),
        impressions: impressions.min(100),
    }
}

// ---------------------------------------------------------------------------
// Feature extraction
// ---------------------------------------------------------------------------

fn extract_features(text: &str) -> FeatureVector {
    let char_count = text.chars().count();
    let word_count = text.split_whitespace().count();
    let line_count = text.lines().count();

    let has_link = text.contains("http://") || text.contains("https://");
    let link_position = if has_link { Some("body".into()) } else { None };

    let hashtag_count = text.matches('#').count();
    let has_question = text.contains('?');
    let has_numbers = text.chars().any(|c| c.is_ascii_digit());
    let starts_with_i = text.starts_with("I ") || text.starts_with("I'");

    let cta_patterns = [
        "check out",
        "click",
        "sign up",
        "subscribe",
        "join",
        "try it",
        "grab it",
        "get it",
        "learn more",
        "read more",
        "download",
    ];
    let lower = text.to_lowercase();
    let has_cta = cta_patterns.iter().any(|p| lower.contains(p));

    let hook_strength = score_hook(text.lines().next().unwrap_or(""));
    let content_type_guess = detect_content_type(text);

    let est_dwell_seconds = 1.0 + (word_count as f64 / 200.0) * 60.0;

    let negative_words = [
        "stupid",
        "idiot",
        "dumb",
        "hate",
        "terrible",
        "awful",
        "disgusting",
        "pathetic",
        "garbage",
        "trash",
        "worst",
        "moron",
        "clown",
        "fraud",
        "scam",
        "sucks",
        "useless",
        "incompetent",
        "liar",
        "bs",
        "stfu",
        "shut up",
        "you're wrong",
        "cope",
        "ratio",
    ];
    let aggressive_patterns = [
        "imagine thinking",
        "tell me you",
        "nobody asked",
        "stay mad",
        "cry about it",
        "skill issue",
        "l + ratio",
    ];
    let neg_count = negative_words
        .iter()
        .filter(|w| lower.contains(*w))
        .count();
    let aggro_count = aggressive_patterns
        .iter()
        .filter(|p| lower.contains(*p))
        .count();

    let sentiment = if neg_count >= 2 || aggro_count >= 1 {
        "negative".to_string()
    } else if neg_count == 1 {
        "mixed".to_string()
    } else {
        "neutral".to_string()
    };

    FeatureVector {
        char_count,
        word_count,
        has_link,
        link_position,
        has_media: false,
        hashtag_count,
        has_question,
        has_numbers,
        has_cta,
        hook_strength,
        line_count,
        starts_with_i,
        content_type_guess,
        est_dwell_seconds,
        sentiment,
    }
}

fn score_hook(first_line: &str) -> u32 {
    let trimmed = first_line.trim();
    if trimmed.is_empty() {
        return 0;
    }

    let mut score: u32 = 40;

    if trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        score += 30;
    }
    if trimmed.ends_with('?') {
        score += 20;
    }

    let bold_words = [
        "never", "always", "stop", "wrong", "truth", "secret", "nobody", "everyone",
    ];
    let lower = trimmed.to_lowercase();
    if bold_words.iter().any(|w| lower.contains(w)) {
        score += 15;
    }

    let weak = ["I ", "So ", "Just ", "The ", "It's ", "This is "];
    if weak.iter().any(|w| trimmed.starts_with(w)) {
        score = score.saturating_sub(20);
    }

    score.min(100)
}

fn detect_content_type(text: &str) -> String {
    let lower = text.to_lowercase();

    if lower.contains('?') && lower.lines().count() <= 3 {
        return "question".into();
    }

    let how_to_signals = ["how to", "step 1", "here's how", "guide", "tutorial", "tip:"];
    if how_to_signals.iter().any(|s| lower.contains(s)) {
        return "how-to".into();
    }

    let data_signals = ["%", "million", "billion", "$", "data shows", "study", "research"];
    if data_signals.iter().any(|s| lower.contains(s)) && text.chars().any(|c| c.is_ascii_digit()) {
        return "data".into();
    }

    let announcement_signals = [
        "announcing",
        "launching",
        "introducing",
        "excited to",
        "just shipped",
        "now available",
        "new:",
        "release",
    ];
    if announcement_signals.iter().any(|s| lower.contains(s)) {
        return "announcement".into();
    }

    "opinion".into()
}

fn has_proper_nouns(text: &str) -> bool {
    let words: Vec<&str> = text.split_whitespace().collect();
    for (i, word) in words.iter().enumerate() {
        if i == 0 {
            continue;
        }
        let prev = words[i - 1];
        if prev.ends_with('.') || prev.ends_with('!') || prev.ends_with('?') {
            continue;
        }
        if word.chars().next().is_some_and(|c| c.is_uppercase())
            && !word.starts_with('#')
            && !word.starts_with('@')
            && !word.starts_with("http")
        {
            return true;
        }
    }
    false
}

fn suggest_improvements(
    issues: &[Issue],
    features: &FeatureVector,
    proxies: &ProxyScores,
    goal: Option<&str>,
) -> Vec<String> {
    let mut suggestions = Vec::new();

    for issue in issues {
        if let Some(ref fix) = issue.fix {
            suggestions.push(fix.clone());
        }
    }

    match goal {
        Some("replies") => {
            if !features.has_question {
                suggestions.push(
                    "Add a question — questions are the #1 driver of replies (~20x weight)".into(),
                );
            }
            if proxies.reply < 0.30 {
                suggestions.push(
                    "Try an open-ended question (what/how/why) to boost reply probability".into(),
                );
            }
        }
        Some("impressions") => {
            if features.hook_strength < 70 {
                suggestions.push(
                    "Strengthen your hook — first line determines if people stop scrolling".into(),
                );
            }
            if features.line_count <= 1 && features.char_count > 80 {
                suggestions.push(
                    "Add line breaks — visual spacing increases dwell time (a scoring signal)"
                        .into(),
                );
            }
            if proxies.dwell < 0.20 {
                suggestions
                    .push("Add more depth — longer dwell time increases distribution".into());
            }
        }
        Some("shares") => {
            if proxies.share_via_dm < 0.15 {
                suggestions.push(
                    "Add practical value (how-to, data, framework) — it drives DM shares (~25x weight)".into(),
                );
            }
        }
        Some("follows") => {
            if proxies.profile_click < 0.20 {
                suggestions.push(
                    "Add a curiosity gap or credentials — profile clicks are the gateway to follows"
                        .into(),
                );
            }
        }
        Some("quotes") => {
            if proxies.quote < 0.15 {
                suggestions.push(
                    "Make it quotable — contrarian takes, data points, or short punchy claims"
                        .into(),
                );
            }
        }
        _ => {}
    }

    if features.est_dwell_seconds < 5.0 && features.char_count > 0 {
        suggestions.push(format!(
            "Est. dwell time: {:.0}s — longer posts drive more dwell_time signal. Consider adding depth.",
            features.est_dwell_seconds
        ));
    }

    if features.content_type_guess == "opinion" && !features.has_numbers {
        suggestions
            .push("Data-backed opinions outperform pure takes — add a number or citation".into());
    }

    if features.content_type_guess == "data" || features.content_type_guess == "how-to" {
        suggestions.push(
            "This looks DM-shareable — insider data and how-tos drive share_via_dm (~25x signal)"
                .into(),
        );
    }

    if proxies.negative_risk >= 0.30 {
        suggestions
            .push("High negative-reaction risk — Grok will suppress this. Soften the tone.".into());
    }

    suggestions.dedup();
    suggestions
}

fn build_next_commands(text: &str, score: u32) -> Vec<String> {
    let escaped = text.replace('"', "\\\"");
    if score >= 75 {
        vec![format!("xmaster post \"{}\"", escaped)]
    } else {
        vec!["xmaster analyze \"<your revised text>\" --goal replies".to_string()]
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn default_ctx() -> AnalyzeContext {
        AnalyzeContext::default()
    }

    fn ctx_with_goal(goal: &str) -> AnalyzeContext {
        AnalyzeContext {
            goal: Some(goal.to_string()),
            ..Default::default()
        }
    }

    #[test]
    fn empty_tweet_is_critical() {
        let result = analyze("", &default_ctx());
        assert!(result.score < 50);
        assert_eq!(result.issues[0].code, "empty_content");
    }

    #[test]
    fn link_in_body_detected() {
        let result = analyze("Check this out https://example.com", &default_ctx());
        assert!(result.issues.iter().any(|i| i.code == "link_in_body"));
    }

    #[test]
    fn over_280_is_critical_without_premium() {
        let long = "a".repeat(300);
        let result = analyze(&long, &default_ctx());
        assert!(result.issues.iter().any(|i| i.code == "over_limit"));
    }

    #[test]
    fn over_280_ok_with_premium() {
        let long = "a".repeat(300);
        let ctx = AnalyzeContext { premium: true, ..Default::default() };
        let result = analyze(&long, &ctx);
        assert!(!result.issues.iter().any(|i| i.code == "over_limit"));
    }

    #[test]
    fn over_25000_is_critical_even_with_premium() {
        let long = "a".repeat(25_001);
        let ctx = AnalyzeContext { premium: true, ..Default::default() };
        let result = analyze(&long, &ctx);
        assert!(result.issues.iter().any(|i| i.code == "over_limit"));
    }

    #[test]
    fn clean_tweet_scores_well() {
        let result = analyze(
            "7 things I learned building a startup in 2024:\n\n1. Speed beats perfection\n2. Talk to users daily\n3. Ship or die",
            &default_ctx(),
        );
        assert!(result.score >= 60, "score was {}", result.score);
        assert!(!result.features.content_type_guess.is_empty());
    }

    #[test]
    fn question_detected() {
        let result = analyze(
            "What's the hardest lesson you learned this year?",
            &ctx_with_goal("replies"),
        );
        assert!(result.features.has_question);
        assert!(result.score >= 50, "score was {}", result.score);
    }

    #[test]
    fn weak_hook_flagged() {
        let result = analyze(
            "I think this is an interesting take on the market",
            &default_ctx(),
        );
        assert!(result.issues.iter().any(|i| i.code == "weak_hook"));
    }

    #[test]
    fn grade_mapping() {
        let result = analyze(
            "Stop sleeping on Rust.\n\n3 reasons it will dominate backend in 2025:",
            &default_ctx(),
        );
        assert!(
            ["A", "B", "C"].contains(&result.grade.as_str()),
            "grade was {}",
            result.grade
        );
    }

    #[test]
    fn link_in_body_is_critical() {
        let result = analyze(
            "Great article https://example.com about Rust",
            &default_ctx(),
        );
        let issue = result
            .issues
            .iter()
            .find(|i| i.code == "link_in_body")
            .unwrap();
        assert_eq!(issue.severity, Severity::Critical);
    }

    #[test]
    fn engagement_bait_detected() {
        let result = analyze(
            "Like if you agree with this take on AI",
            &default_ctx(),
        );
        assert!(result.issues.iter().any(|i| i.code == "engagement_bait"));
    }

    #[test]
    fn starts_with_mention_flagged() {
        let result = analyze(
            "@elonmusk what do you think about this?",
            &default_ctx(),
        );
        assert!(result
            .issues
            .iter()
            .any(|i| i.code == "starts_with_mention"));
    }

    #[test]
    fn at_281_is_over_limit_without_premium() {
        let long = "x".repeat(281);
        let result = analyze(&long, &default_ctx());
        let issue = result
            .issues
            .iter()
            .find(|i| i.code == "over_limit")
            .unwrap();
        assert_eq!(issue.severity, Severity::Critical);
    }

    #[test]
    fn at_281_is_fine_with_premium() {
        let long = "x".repeat(281);
        let ctx = AnalyzeContext { premium: true, ..Default::default() };
        let result = analyze(&long, &ctx);
        assert!(!result.issues.iter().any(|i| i.code == "over_limit"));
    }

    #[test]
    fn short_question_not_penalized_as_too_short() {
        let result = analyze("What's your biggest regret?", &default_ctx());
        assert!(result.features.has_question);
        assert!(
            !result.issues.iter().any(|i| i.code == "too_short"),
            "short question should not be flagged as too_short"
        );
    }

    #[test]
    fn specific_numbers_boost_score() {
        let with_numbers = analyze(
            "3 things I learned building startups in 2024",
            &default_ctx(),
        );
        let without_numbers = analyze(
            "Things I learned building startups recently",
            &default_ctx(),
        );
        assert!(
            with_numbers.score > without_numbers.score,
            "with_numbers={} should beat without_numbers={}",
            with_numbers.score,
            without_numbers.score
        );
    }

    #[test]
    fn perfect_tweet_scores_high() {
        let text = "3 things Google taught me about scaling:\n\n1. Cache everything\n2. Fail fast\n\nWhat would you add?";
        let result = analyze(text, &default_ctx());
        assert!(
            result.score >= 75,
            "perfect tweet score was {}",
            result.score
        );
        assert!(
            result.grade == "A" || result.grade == "B",
            "grade was {}",
            result.grade
        );
    }

    #[test]
    fn empty_text_is_critical() {
        let result = analyze("   ", &default_ctx());
        let issue = result
            .issues
            .iter()
            .find(|i| i.code == "empty_content")
            .unwrap();
        assert_eq!(issue.severity, Severity::Critical);
    }

    #[test]
    fn rt_if_detected_as_engagement_bait() {
        let result = analyze(
            "RT if you think Rust is the future of systems programming",
            &default_ctx(),
        );
        assert!(result.issues.iter().any(|i| i.code == "engagement_bait"));
    }

    #[test]
    fn excessive_hashtags_warned() {
        let result = analyze(
            "Great day #rust #programming #code #dev",
            &default_ctx(),
        );
        assert!(result
            .issues
            .iter()
            .any(|i| i.code == "excessive_hashtags"));
    }

    // --- Proxy signal tests ---

    #[test]
    fn question_drives_reply_proxy() {
        let q = analyze(
            "What's the biggest mistake founders make?",
            &default_ctx(),
        );
        let s = analyze(
            "Founders make a lot of mistakes in their journey.",
            &default_ctx(),
        );
        assert!(
            q.proxy_scores.reply > s.proxy_scores.reply,
            "question reply={:.2} should beat statement reply={:.2}",
            q.proxy_scores.reply,
            s.proxy_scores.reply
        );
    }

    #[test]
    fn data_content_drives_quote_proxy() {
        let data = analyze(
            "73% of startups fail because of premature scaling — research from 2024",
            &default_ctx(),
        );
        let opinion = analyze(
            "I think startups fail because of bad decisions",
            &default_ctx(),
        );
        assert!(
            data.proxy_scores.quote > opinion.proxy_scores.quote,
            "data quote={:.2} should beat opinion quote={:.2}",
            data.proxy_scores.quote,
            opinion.proxy_scores.quote
        );
    }

    #[test]
    fn practical_content_drives_dm_share() {
        let howto = analyze(
            "How to build a CLI in Rust — step by step guide:",
            &default_ctx(),
        );
        let opinion = analyze(
            "Rust is a great language for building tools",
            &default_ctx(),
        );
        assert!(
            howto.proxy_scores.share_via_dm > opinion.proxy_scores.share_via_dm,
            "howto dm_share={:.2} should beat opinion dm_share={:.2}",
            howto.proxy_scores.share_via_dm,
            opinion.proxy_scores.share_via_dm
        );
    }

    #[test]
    fn negative_tone_raises_negative_risk() {
        let neg = analyze(
            "This is stupid garbage and you're an idiot if you believe it",
            &default_ctx(),
        );
        let pos = analyze(
            "Here's a thoughtful take on why this approach works better",
            &default_ctx(),
        );
        assert!(
            neg.proxy_scores.negative_risk > pos.proxy_scores.negative_risk,
            "negative risk={:.2} should beat positive risk={:.2}",
            neg.proxy_scores.negative_risk,
            pos.proxy_scores.negative_risk
        );
    }

    #[test]
    fn media_context_drives_media_expand() {
        let with_media = analyze(
            "Check this out",
            &AnalyzeContext {
                has_media: true,
                media_kind: Some(MediaKind::Image),
                ..Default::default()
            },
        );
        let without_media = analyze("Check this out", &default_ctx());
        assert!(
            with_media.proxy_scores.media_expand > without_media.proxy_scores.media_expand,
            "media expand={:.2} should beat no-media={:.2}",
            with_media.proxy_scores.media_expand,
            without_media.proxy_scores.media_expand
        );
    }

    #[test]
    fn goal_scores_populated() {
        let result = analyze(
            "3 things Google taught me about scaling:\n\n1. Cache everything\n2. Fail fast\n\nWhat would you add?",
            &default_ctx(),
        );
        assert!(result.goal_scores.replies > 0);
        assert!(result.goal_scores.impressions > 0);
    }

    #[test]
    fn goal_scores_capped_at_100() {
        let result = analyze(
            "What's the #1 thing nobody talks about in startups? Here's how to build a $1M ARR company step by step — the secret framework:",
            &default_ctx(),
        );
        assert!(result.goal_scores.replies <= 100);
        assert!(result.goal_scores.quotes <= 100);
        assert!(result.goal_scores.shares <= 100);
        assert!(result.goal_scores.follows <= 100);
        assert!(result.goal_scores.impressions <= 100);
    }
}