molten-herald 0.1.0

Automated viral tweet generation and scheduling for developer releases 📢
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Herald CLI - Automated viral tweets for developers
//!
//! Usage:
//!   herald init              Create default configuration
//!   herald generate          Generate tweets from detected events
//!   herald post <text>       Post a tweet immediately
//!   herald schedule <text>   Schedule a tweet for later
//!   herald queue             View scheduled tweets
//!   herald config            Show current configuration

use clap::{Parser, Subcommand};
use molten_herald::{
    ui, Config, EventDetector, EventType, Result,
    Scheduler, TweetGenerator, TweetTemplates, TwitterClient,
};
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "herald")]
#[command(author = "Molten Labs")]
#[command(version)]
#[command(about = "📢 Automated viral tweet generation and scheduling for developers")]
#[command(long_about = None)]
struct Cli {
    /// Configuration file path
    #[arg(short, long, global = true)]
    config: Option<PathBuf>,

    /// Enable verbose output
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Disable fancy output (no colors/spinners)
    #[arg(long, global = true)]
    plain: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Interactive mode - guided tweet creation
    #[command(name = "i", alias = "interactive")]
    Interactive,

    /// Initialize configuration
    Init {
        /// Force overwrite existing config
        #[arg(short, long)]
        force: bool,
    },

    /// Generate tweets for project events
    Generate {
        /// Project name to generate for
        #[arg(short, long)]
        project: Option<String>,

        /// Event type (release, commit, pr)
        #[arg(short, long)]
        event: Option<String>,

        /// Number of variations to generate
        #[arg(short = 'n', long, default_value = "1")]
        count: usize,

        /// Don't post, just preview
        #[arg(long)]
        dry_run: bool,
    },

    /// Post a tweet immediately
    Post {
        /// Tweet text
        text: String,

        /// Post as a thread (separate tweets by ---)
        #[arg(long)]
        thread: bool,
    },

    /// Schedule a tweet for later
    Schedule {
        /// Tweet text
        text: String,

        /// Scheduled time (ISO 8601 or relative like "2h", "tomorrow 9am")
        #[arg(short, long)]
        time: Option<String>,
    },

    /// View and manage scheduled tweets
    Queue {
        #[command(subcommand)]
        action: Option<QueueAction>,
    },

    /// Process due tweets (for cron jobs)
    Process,

    /// Show configuration
    Config {
        /// Show example configuration
        #[arg(long)]
        example: bool,
    },

    /// Quick templates for common tweets
    Template {
        #[command(subcommand)]
        template: TemplateType,
    },

    /// Detect events from projects
    Detect {
        /// Project name
        project: Option<String>,
    },

    /// Demo all Molten TUI libraries
    Demo,
}

#[derive(Subcommand)]
enum QueueAction {
    /// List pending tweets
    List,
    /// Cancel a scheduled tweet
    Cancel { id: String },
    /// Reschedule a tweet
    Reschedule {
        id: String,
        #[arg(short, long)]
        time: String,
    },
    /// Clean up completed/failed tweets
    Cleanup,
    /// Show queue statistics
    Stats,
}

#[derive(Subcommand)]
enum TemplateType {
    /// Crate release template
    CrateRelease {
        /// Crate name
        name: String,
        /// Version
        version: String,
        /// Tagline
        tagline: String,
    },
    /// Open source announcement
    OpenSource {
        /// Project name
        name: String,
        /// Description
        description: String,
        /// GitHub URL
        url: String,
    },
    /// Feature announcement
    Feature {
        /// Project name
        name: String,
        /// Feature name
        feature: String,
        /// Benefit/value
        benefit: String,
    },
    /// Milestone celebration
    Milestone {
        /// Project name
        name: String,
        /// Metric (downloads, stars, etc.)
        metric: String,
        /// Value
        value: String,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Load configuration
    let config = match &cli.config {
        Some(path) => Config::load_from(path)?,
        None => Config::load().unwrap_or_default(),
    };

    match cli.command {
        Commands::Interactive => molten_herald::interactive::run(&config).await,
        Commands::Init { force } => cmd_init(force).await,
        Commands::Generate { project, event, count, dry_run } => {
            cmd_generate(&config, project, event, count, dry_run).await
        }
        Commands::Post { text, thread } => cmd_post(&config, &text, thread).await,
        Commands::Schedule { text, time } => cmd_schedule(&config, &text, time).await,
        Commands::Queue { action } => cmd_queue(&config, action).await,
        Commands::Process => cmd_process(&config).await,
        Commands::Config { example } => cmd_config(&config, example),
        Commands::Template { template } => cmd_template(template),
        Commands::Detect { project } => cmd_detect(&config, project).await,
        Commands::Demo => {
            ui::demo();
            Ok(())
        }
    }
}

async fn cmd_init(force: bool) -> Result<()> {
    ui::banner();
    
    let config_path = Config::default_path()?;

    if config_path.exists() && !force {
        ui::warning(&format!("Configuration already exists at: {}", config_path.display()));
        ui::info("Use --force to overwrite");
        return Ok(());
    }

    let config = Config::example();
    config.save_to(&config_path)?;

    ui::config_created(&config_path.display().to_string());

    Ok(())
}

async fn cmd_generate(
    config: &Config,
    project: Option<String>,
    event_type: Option<String>,
    count: usize,
    dry_run: bool,
) -> Result<()> {
    ui::banner();
    
    let generator = TweetGenerator::new(config.llm.clone(), config.defaults.clone());

    // Create event from parameters or detect
    let event = if let (Some(proj), Some(evt)) = (&project, &event_type) {
        let event_type = match evt.as_str() {
            "release" => EventType::Release,
            "commit" => EventType::Commit,
            "pr" | "pull_request" => EventType::PullRequest,
            "feature" => EventType::MajorFeature,
            _ => EventType::Custom(evt.clone()),
        };

        EventDetector::create_manual_event(
            proj,
            &format!("{} update", proj),
            None,
            None,
            event_type,
        )
    } else {
        // Try to detect from configured projects
        ui::info("Detecting events from configured projects...");
        
        let detector = EventDetector::new();
        let mut events = Vec::new();

        for proj in &config.projects {
            if let Ok(mut detected) = ui::with_spinner_async(
                &format!("Checking {}...", proj.name),
                detector.detect(proj)
            ).await {
                events.append(&mut detected);
            }
        }

        events.into_iter().next().ok_or_else(|| {
            molten_herald::HeraldError::NoEvents
        })?
    };

    ui::subheader(&format!("Generating {} tweet(s) for: {}", count, event.title));
    println!();

    if count > 1 {
        let tweets = ui::with_spinner_async(
            "Generating variations...",
            generator.generate_variations(&event, count)
        ).await?;
        
        for (i, tweet) in tweets.iter().enumerate() {
            ui::header(&format!("Variation {}", i + 1));
            ui::generated_tweet(&tweet.content, tweet.length, Some(&format!("{:?}", event.event_type)));
        }
    } else {
        let tweet = ui::with_spinner_async(
            "Generating tweet...",
            generator.generate(&event)
        ).await?;
        
        ui::generated_tweet(&tweet.content, tweet.length, Some(&format!("{:?}", event.event_type)));

        if !dry_run {
            if ui::confirm_prompt("Post this tweet?") {
                let client = TwitterClient::new(config.twitter.clone())?;
                let posted = ui::with_spinner_async(
                    "Posting to Twitter...",
                    client.post_tweet(&tweet.content)
                ).await?;
                ui::tweet_posted(&posted.url);
            }
        }
    }

    Ok(())
}

async fn cmd_post(config: &Config, text: &str, thread: bool) -> Result<()> {
    ui::banner();
    
    let client = TwitterClient::new(config.twitter.clone())?;

    if thread {
        let tweets: Vec<String> = text.split("---")
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

        ui::info(&format!("Posting thread with {} tweets...", tweets.len()));
        
        for (i, tweet) in tweets.iter().enumerate() {
            ui::tweet_preview(tweet, tweet.chars().count());
            if i < tweets.len() - 1 {
                println!("  ↓");
            }
        }
        
        if ui::confirm_prompt("Post this thread?") {
            let posted = ui::with_spinner_async(
                "Posting thread...",
                client.post_thread(&tweets)
            ).await?;
            
            let urls: Vec<String> = posted.iter().map(|p| p.url.clone()).collect();
            ui::thread_posted(&urls);
        }
    } else {
        ui::tweet_preview(text, text.chars().count());
        
        if ui::confirm_prompt("Post this tweet?") {
            let posted = ui::with_spinner_async(
                "Posting to Twitter...",
                client.post_tweet(text)
            ).await?;
            ui::tweet_posted(&posted.url);
        }
    }

    Ok(())
}

async fn cmd_schedule(config: &Config, text: &str, time: Option<String>) -> Result<()> {
    ui::banner();
    
    let scheduler = Scheduler::new(config.schedule.clone())?;

    let scheduled_time = if let Some(ref t) = time {
        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(t) {
            dt.with_timezone(&chrono::Utc)
        } else {
            scheduler.next_available_slot()
        }
    } else {
        scheduler.next_available_slot()
    };

    ui::tweet_preview(text, text.chars().count());
    
    let scheduled = scheduler.schedule_text(text, Some(scheduled_time))?;

    ui::success("Tweet scheduled!");
    println!();
    ui::kv("Time", &scheduled.scheduled_for.format("%Y-%m-%d %H:%M UTC").to_string());
    ui::kv("ID", &scheduled.id[..8]);

    Ok(())
}

async fn cmd_queue(config: &Config, action: Option<QueueAction>) -> Result<()> {
    let scheduler = Scheduler::new(config.schedule.clone())?;

    match action {
        None | Some(QueueAction::List) => {
            ui::banner();
            
            let pending = scheduler.pending()?;
            
            if pending.is_empty() {
                ui::info("No scheduled tweets");
                return Ok(());
            }

            let tweets: Vec<(String, String, String, String)> = pending
                .iter()
                .map(|t| (
                    t.id.clone(),
                    t.scheduled_for.format("%Y-%m-%d %H:%M UTC").to_string(),
                    format!("{:?}", t.status),
                    t.content.clone(),
                ))
                .collect();
            
            ui::scheduled_tweets_table(&tweets);
        }

        Some(QueueAction::Cancel { id }) => {
            scheduler.cancel(&id)?;
            ui::success(&format!("Cancelled tweet: {}", &id[..8.min(id.len())]));
        }

        Some(QueueAction::Reschedule { id, time }) => {
            if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&time) {
                scheduler.reschedule(&id, dt.with_timezone(&chrono::Utc))?;
                ui::success(&format!("Rescheduled {} to {}", &id[..8.min(id.len())], time));
            } else {
                ui::error("Invalid time format. Use ISO 8601 (e.g., 2024-01-15T09:00:00Z)");
            }
        }

        Some(QueueAction::Cleanup) => {
            let removed = scheduler.cleanup()?;
            ui::success(&format!("Removed {} completed/failed tweets", removed));
        }

        Some(QueueAction::Stats) => {
            ui::banner();
            let stats = scheduler.stats()?;
            ui::queue_stats(stats.pending, stats.posted, stats.failed, stats.cancelled);
        }
    }

    Ok(())
}

async fn cmd_process(config: &Config) -> Result<()> {
    let scheduler = Scheduler::new(config.schedule.clone())?;
    let client = TwitterClient::new(config.twitter.clone())?;

    let due = scheduler.due()?;
    
    if due.is_empty() {
        return Ok(());
    }

    for tweet in due {
        match client.post_tweet(&tweet.content).await {
            Ok(posted) => {
                scheduler.mark_posted(&tweet.id, &posted.id)?;
                ui::success(&format!("Posted: {}", posted.url));
            }
            Err(e) => {
                scheduler.mark_failed(&tweet.id, &e.to_string())?;
                ui::error(&format!("Failed to post {}: {}", &tweet.id[..8], e));
            }
        }
    }

    Ok(())
}

fn cmd_config(config: &Config, example: bool) -> Result<()> {
    if example {
        let example = Config::example();
        let toml = toml::to_string_pretty(&example)
            .map_err(|e| molten_herald::HeraldError::Config(e.to_string()))?;
        println!("{}", toml);
    } else {
        let toml = toml::to_string_pretty(config)
            .map_err(|e| molten_herald::HeraldError::Config(e.to_string()))?;
        println!("{}", toml);
    }
    Ok(())
}

fn cmd_template(template: TemplateType) -> Result<()> {
    let tweet = match template {
        TemplateType::CrateRelease { name, version, tagline } => {
            TweetTemplates::crate_release(&name, &version, &tagline, &format!("https://crates.io/crates/{}", name))
        }
        TemplateType::OpenSource { name, description, url } => {
            TweetTemplates::open_source(&name, &description, &url)
        }
        TemplateType::Feature { name, feature, benefit } => {
            TweetTemplates::feature(&name, &feature, &benefit)
        }
        TemplateType::Milestone { name, metric, value } => {
            TweetTemplates::milestone(&name, &metric, &value)
        }
    };

    ui::banner();
    ui::generated_tweet(&tweet, tweet.chars().count(), None);
    ui::info("Tip: Pipe to pbcopy (macOS) or xclip (Linux) to copy");

    Ok(())
}

async fn cmd_detect(config: &Config, project: Option<String>) -> Result<()> {
    ui::banner();
    
    let detector = EventDetector::new();

    let projects: Vec<_> = if let Some(ref name) = project {
        config.projects.iter().filter(|p| p.name == *name).collect()
    } else {
        config.projects.iter().collect()
    };

    if projects.is_empty() {
        ui::warning("No projects configured. Add projects to your config file.");
        return Ok(());
    }

    for proj in projects {
        ui::subheader(&format!("Detecting events for: {}", proj.name));
        
        match ui::with_spinner_async(
            "Fetching...",
            detector.detect(proj)
        ).await {
            Ok(events) => {
                if events.is_empty() {
                    ui::info("No recent events found");
                } else {
                    for event in events {
                        ui::list_item(
                            "•",
                            &format!("{:?}: {} ({})", 
                                event.event_type,
                                event.title,
                                event.timestamp.format("%Y-%m-%d")
                            )
                        );
                    }
                }
            }
            Err(e) => {
                ui::error(&format!("Error: {}", e));
            }
        }
        println!();
    }

    Ok(())
}