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
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
//! Interactive mode for herald

use crate::config::Config;
use crate::error::Result;
use crate::generator::TweetTemplates;
use crate::scheduler::Scheduler;
use crate::twitter::TwitterClient;
use crate::ui;
use chant::{choose, input};
use glyphs::{style, Color};

/// Main interactive menu
pub async fn run(config: &Config) -> Result<()> {
    ui::welcome();
    
    loop {
        let action = choose(&[
            "📝 Create a tweet",
            "📦 Announce a release",
            "🎯 Use a template",
            "📅 Schedule a tweet",
            "📬 View queue",
            "⚙️  Configure",
            "🚪 Exit",
        ])
        .cursor("")
        .run();

        match action.as_deref() {
            Some("📝 Create a tweet") => create_tweet(config).await?,
            Some("📦 Announce a release") => announce_release(config).await?,
            Some("🎯 Use a template") => use_template(config).await?,
            Some("📅 Schedule a tweet") => schedule_tweet(config).await?,
            Some("📬 View queue") => view_queue(config).await?,
            Some("⚙️  Configure") => configure(config).await?,
            Some("🚪 Exit") | None => {
                println!();
                println!(
                    " {} {}",
                    style("👋").fg(Color::White),
                    style("See you next time!").fg(Color::Rgb { r: 150, g: 150, b: 150 })
                );
                println!();
                break;
            }
            _ => {}
        }
        
        println!();
    }

    Ok(())
}

/// Create and post a tweet interactively
async fn create_tweet(config: &Config) -> Result<()> {
    ui::header("Create a Tweet");
    
    let content = input("Tweet:")
        .placeholder("What's happening?")
        .char_limit(280)
        .run();

    if content.is_empty() {
        ui::warning("Tweet cancelled");
        return Ok(());
    }

    let char_count = content.chars().count();
    ui::tweet_preview(&content, char_count);

    if char_count > 280 {
        ui::error("Tweet is too long! Please shorten it.");
        return Ok(());
    }

    let action = choose(&[
        "🚀 Post now",
        "📅 Schedule for later",
        "📋 Copy to clipboard",
        "❌ Cancel",
    ])
    .header("What next?")
    .cursor("")
    .run();

    match action.as_deref() {
        Some("🚀 Post now") => {
            if !config.twitter.is_configured() {
                ui::error("Twitter not configured. Run 'herald init' first.");
                return Ok(());
            }
            
            let client = TwitterClient::new(config.twitter.clone())?;
            let posted = ui::with_spinner_async("Posting...", client.post_tweet(&content)).await?;
            ui::tweet_posted(&posted.url);
        }
        Some("📅 Schedule for later") => {
            let scheduler = Scheduler::new(config.schedule.clone())?;
            let scheduled = scheduler.schedule_text(&content, None)?;
            ui::success(&format!("Scheduled for {}", scheduled.scheduled_for.format("%Y-%m-%d %H:%M UTC")));
        }
        Some("📋 Copy to clipboard") => {
            copy_to_clipboard(&content);
            ui::success("Copied to clipboard!");
        }
        _ => {
            ui::info("Cancelled");
        }
    }

    Ok(())
}

/// Announce a release interactively
async fn announce_release(config: &Config) -> Result<()> {
    ui::header("Announce a Release");

    let project = input("Project name:")
        .placeholder("e.g., herald")
        .run();

    if project.is_empty() {
        ui::warning("Cancelled");
        return Ok(());
    }

    let version = input("Version:")
        .placeholder("e.g., 1.0.0")
        .run();

    if version.is_empty() {
        ui::warning("Cancelled");
        return Ok(());
    }

    let tagline = input("Tagline:")
        .placeholder("What makes it awesome?")
        .run();

    if tagline.is_empty() {
        ui::warning("Cancelled");
        return Ok(());
    }

    let platform = choose(&[
        "📦 crates.io (Rust)",
        "📦 npm (JavaScript)",
        "🐙 GitHub Release",
        "🔗 Custom URL",
    ])
    .header("Where is it published?")
    .cursor("")
    .run();

    let url = match platform.as_deref() {
        Some("📦 crates.io (Rust)") => format!("https://crates.io/crates/{}", project),
        Some("📦 npm (JavaScript)") => format!("https://www.npmjs.com/package/{}", project),
        Some("🐙 GitHub Release") => {
            let repo = input("GitHub repo (user/repo):")
                .placeholder("e.g., moltenlabs/herald")
                .run();
            format!("https://github.com/{}/releases/tag/v{}", repo, version)
        }
        Some("🔗 Custom URL") => {
            input("URL:")
                .placeholder("https://...")
                .run()
        }
        _ => return Ok(()),
    };

    let tweet = TweetTemplates::crate_release(&project, &version, &tagline, &url);
    let char_count = tweet.chars().count();
    
    ui::tweet_preview(&tweet, char_count);

    let action = choose(&[
        "🚀 Post now",
        "📅 Schedule for later",
        "📋 Copy to clipboard",
        "✏️  Edit manually",
        "❌ Cancel",
    ])
    .header("What next?")
    .cursor("")
    .run();

    match action.as_deref() {
        Some("🚀 Post now") => {
            if !config.twitter.is_configured() {
                ui::error("Twitter not configured. Run 'herald init' first.");
                return Ok(());
            }
            let client = TwitterClient::new(config.twitter.clone())?;
            let posted = ui::with_spinner_async("Posting...", client.post_tweet(&tweet)).await?;
            ui::tweet_posted(&posted.url);
        }
        Some("📅 Schedule for later") => {
            let scheduler = Scheduler::new(config.schedule.clone())?;
            let scheduled = scheduler.schedule_text(&tweet, None)?;
            ui::success(&format!("Scheduled for {}", scheduled.scheduled_for.format("%Y-%m-%d %H:%M UTC")));
        }
        Some("📋 Copy to clipboard") => {
            copy_to_clipboard(&tweet);
            ui::success("Copied to clipboard!");
        }
        Some("✏️  Edit manually") => {
            let edited = input("Edit tweet:")
                .default(&tweet)
                .char_limit(280)
                .run();
            if !edited.is_empty() {
                copy_to_clipboard(&edited);
                ui::success("Copied to clipboard!");
            }
        }
        _ => {
            ui::info("Cancelled");
        }
    }

    Ok(())
}

/// Use a template interactively
async fn use_template(config: &Config) -> Result<()> {
    ui::header("Tweet Templates");

    let template = choose(&[
        "📦 Crate/Package Release",
        "🌟 Open Source Announcement",
        "✨ Feature Announcement",
        "🎉 Milestone Celebration",
        "🧵 Thread Starter",
        "⬅️  Back",
    ])
    .header("Choose a template:")
    .cursor("")
    .run();

    let tweet = match template.as_deref() {
        Some("📦 Crate/Package Release") => {
            let name = input("Name:").placeholder("project name").run();
            if name.is_empty() { return Ok(()); }
            let version = input("Version:").placeholder("1.0.0").run();
            if version.is_empty() { return Ok(()); }
            let tagline = input("Tagline:").placeholder("what it does").run();
            if tagline.is_empty() { return Ok(()); }
            TweetTemplates::crate_release(&name, &version, &tagline, &format!("https://crates.io/crates/{}", name))
        }
        Some("🌟 Open Source Announcement") => {
            let name = input("Name:").placeholder("project name").run();
            if name.is_empty() { return Ok(()); }
            let desc = input("Description:").placeholder("what it does").run();
            if desc.is_empty() { return Ok(()); }
            let url = input("URL:").placeholder("https://github.com/...").run();
            if url.is_empty() { return Ok(()); }
            TweetTemplates::open_source(&name, &desc, &url)
        }
        Some("✨ Feature Announcement") => {
            let name = input("Project:").placeholder("project name").run();
            if name.is_empty() { return Ok(()); }
            let feature = input("Feature:").placeholder("new feature").run();
            if feature.is_empty() { return Ok(()); }
            let benefit = input("Benefit:").placeholder("why it's great").run();
            if benefit.is_empty() { return Ok(()); }
            TweetTemplates::feature(&name, &feature, &benefit)
        }
        Some("🎉 Milestone Celebration") => {
            let name = input("Project:").placeholder("project name").run();
            if name.is_empty() { return Ok(()); }
            let metric = input("Metric:").placeholder("downloads, stars, etc").run();
            if metric.is_empty() { return Ok(()); }
            let value = input("Value:").placeholder("10,000").run();
            if value.is_empty() { return Ok(()); }
            TweetTemplates::milestone(&name, &metric, &value)
        }
        Some("🧵 Thread Starter") => {
            let topic = input("Topic:").placeholder("what's the thread about?").run();
            if topic.is_empty() { return Ok(()); }
            let count = input("Number of points:").placeholder("5").run();
            let count: usize = count.parse().unwrap_or(5);
            TweetTemplates::thread_opener(&topic, count)
        }
        _ => return Ok(()),
    };

    let char_count = tweet.chars().count();
    ui::tweet_preview(&tweet, char_count);

    let action = choose(&[
        "🚀 Post now",
        "📅 Schedule",
        "📋 Copy",
        "❌ Cancel",
    ])
    .cursor("")
    .run();

    match action.as_deref() {
        Some("🚀 Post now") => {
            if !config.twitter.is_configured() {
                ui::error("Twitter not configured. Run 'herald init' first.");
                return Ok(());
            }
            let client = TwitterClient::new(config.twitter.clone())?;
            let posted = ui::with_spinner_async("Posting...", client.post_tweet(&tweet)).await?;
            ui::tweet_posted(&posted.url);
        }
        Some("📅 Schedule") => {
            let scheduler = Scheduler::new(config.schedule.clone())?;
            let scheduled = scheduler.schedule_text(&tweet, None)?;
            ui::success(&format!("Scheduled for {}", scheduled.scheduled_for.format("%Y-%m-%d %H:%M UTC")));
        }
        Some("📋 Copy") => {
            copy_to_clipboard(&tweet);
            ui::success("Copied to clipboard!");
        }
        _ => {}
    }

    Ok(())
}

/// Schedule a tweet interactively
async fn schedule_tweet(config: &Config) -> Result<()> {
    ui::header("Schedule a Tweet");

    let content = input("Tweet:")
        .placeholder("What's happening?")
        .char_limit(280)
        .run();

    if content.is_empty() {
        ui::warning("Cancelled");
        return Ok(());
    }

    let char_count = content.chars().count();
    ui::tweet_preview(&content, char_count);

    if char_count > 280 {
        ui::error("Tweet is too long!");
        return Ok(());
    }

    let timing = choose(&[
        "⏰ Next available slot",
        "🌅 Tomorrow morning (9 AM)",
        "🌆 Tomorrow afternoon (3 PM)",
        "📅 Custom time",
        "❌ Cancel",
    ])
    .header("When to post?")
    .cursor("")
    .run();

    let scheduled_time = match timing.as_deref() {
        Some("⏰ Next available slot") => None,
        Some("🌅 Tomorrow morning (9 AM)") => {
            let tomorrow = chrono::Utc::now() + chrono::Duration::days(1);
            Some(tomorrow.date_naive().and_hms_opt(9, 0, 0).unwrap().and_utc())
        }
        Some("🌆 Tomorrow afternoon (3 PM)") => {
            let tomorrow = chrono::Utc::now() + chrono::Duration::days(1);
            Some(tomorrow.date_naive().and_hms_opt(15, 0, 0).unwrap().and_utc())
        }
        Some("📅 Custom time") => {
            let time_str = input("Time (YYYY-MM-DD HH:MM):")
                .placeholder("2024-01-15 09:00")
                .run();
            if time_str.is_empty() {
                return Ok(());
            }
            // Parse custom time
            chrono::NaiveDateTime::parse_from_str(&time_str, "%Y-%m-%d %H:%M")
                .ok()
                .map(|dt| dt.and_utc())
        }
        _ => return Ok(()),
    };

    let scheduler = Scheduler::new(config.schedule.clone())?;
    let scheduled = scheduler.schedule_text(&content, scheduled_time)?;
    
    ui::success("Tweet scheduled!");
    ui::kv("Time", &scheduled.scheduled_for.format("%Y-%m-%d %H:%M UTC").to_string());
    ui::kv("ID", &scheduled.id[..8]);

    Ok(())
}

/// View and manage queue
async fn view_queue(config: &Config) -> Result<()> {
    let scheduler = Scheduler::new(config.schedule.clone())?;
    
    loop {
        ui::header("Tweet Queue");
        
        let stats = scheduler.stats()?;
        ui::queue_stats(stats.pending, stats.posted, stats.failed, stats.cancelled);
        
        println!();
        
        let action = choose(&[
            "📋 List pending tweets",
            "🗑️  Cancel a tweet",
            "🧹 Clean up old tweets",
            "⬅️  Back",
        ])
        .cursor("")
        .run();

        match action.as_deref() {
            Some("📋 List pending tweets") => {
                let pending = scheduler.pending()?;
                if pending.is_empty() {
                    ui::info("No pending tweets");
                } else {
                    let tweets: Vec<(String, String, String, String)> = pending
                        .iter()
                        .map(|t| (
                            t.id.clone(),
                            t.scheduled_for.format("%Y-%m-%d %H:%M").to_string(),
                            format!("{:?}", t.status),
                            t.content.clone(),
                        ))
                        .collect();
                    ui::scheduled_tweets_table(&tweets);
                }
            }
            Some("🗑️  Cancel a tweet") => {
                let pending = scheduler.pending()?;
                if pending.is_empty() {
                    ui::info("No pending tweets to cancel");
                } else {
                    let options: Vec<String> = pending
                        .iter()
                        .map(|t| format!("{} - {}...", &t.id[..8], t.content.chars().take(30).collect::<String>()))
                        .collect();
                    
                    if let Some(selected) = choose(&options).header("Select tweet to cancel:").cursor("").run() {
                        let id = selected.split(" - ").next().unwrap();
                        // Find the full ID
                        if let Some(tweet) = pending.iter().find(|t| t.id.starts_with(id)) {
                            if chant::confirm(&format!("Cancel tweet '{}'?", &tweet.content.chars().take(30).collect::<String>())).run() {
                                scheduler.cancel(&tweet.id)?;
                                ui::success("Tweet cancelled");
                            }
                        }
                    }
                }
            }
            Some("🧹 Clean up old tweets") => {
                let removed = scheduler.cleanup()?;
                ui::success(&format!("Removed {} old tweets", removed));
            }
            Some("⬅️  Back") | None => break,
            _ => {}
        }
    }

    Ok(())
}

/// Configuration menu
async fn configure(config: &Config) -> Result<()> {
    let mut config = config.clone();
    
    loop {
        ui::header("Configuration");

        let config_path = Config::default_path()?;
        
        ui::kv("Config file", &config_path.display().to_string());
        ui::kv("Twitter configured", if config.twitter.is_configured() { "✓ Yes" } else { "✗ No" });
        ui::kv("LLM configured", if !config.llm.api_key.is_empty() { "✓ Yes" } else { "✗ No" });
        ui::kv("LLM provider", &config.llm.provider);
        ui::kv("Default tone", &config.defaults.tone);
        
        println!();
        
        let action = choose(&[
            "🔑 Set Twitter credentials",
            "🤖 Set LLM API key", 
            "🎨 Set tweet defaults",
            "📝 Edit config file",
            "📋 Show full config",
            "⬅️  Back",
        ])
        .cursor("")
        .run();

        match action.as_deref() {
            Some("🔑 Set Twitter credentials") => {
                setup_twitter(&mut config).await?;
            }
            Some("🤖 Set LLM API key") => {
                setup_llm(&mut config).await?;
            }
            Some("🎨 Set tweet defaults") => {
                setup_defaults(&mut config).await?;
            }
            Some("📝 Edit config file") => {
                let editor = std::env::var("EDITOR").unwrap_or_else(|_| "nano".to_string());
                ui::info(&format!("Opening in {}...", editor));
                std::process::Command::new(&editor)
                    .arg(&config_path)
                    .status()
                    .ok();
            }
            Some("📋 Show full config") => {
                let toml = toml::to_string_pretty(&config).unwrap_or_default();
                println!();
                println!("{}", style("".repeat(50)).fg(Color::BrightBlack));
                println!("{}", toml);
                println!("{}", style("".repeat(50)).fg(Color::BrightBlack));
                println!();
                ui::info("Press Enter to continue...");
                let _ = input("").run();
            }
            Some("⬅️  Back") | None => break,
            _ => {}
        }
    }

    Ok(())
}

/// Interactive Twitter credential setup
async fn setup_twitter(config: &mut Config) -> Result<()> {
    ui::header("Twitter API Setup");
    
    println!("{}", style("Go to: https://developer.twitter.com/en/portal/projects").fg(Color::Cyan).bold());
    println!();
    
    println!("{}", style("Step 1: Get Consumer Keys").fg(Color::Yellow).bold());
    ui::list_item("", "Go to your App → Keys and tokens");
    ui::list_item("", "Under 'Consumer Keys', copy API Key and API Secret");
    println!();

    let api_key = input("API Key:")
        .placeholder("e.g. AhzM2iI2j3ytCe28AWsMrry8T")
        .run();
    
    if api_key.is_empty() {
        ui::warning("Cancelled");
        return Ok(());
    }
    
    // Validate - API keys are typically 25 chars
    if api_key.len() < 20 || api_key.len() > 30 {
        ui::warning(&format!("API Key looks unusual (length: {}). Expected ~25 chars.", api_key.len()));
        if !chant::confirm("Continue anyway?").run() {
            return Ok(());
        }
    }

    let api_secret = input("API Secret:")
        .placeholder("e.g. GWZ8hLGh1KdmSFvo...")
        .run();
    
    if api_secret.is_empty() {
        ui::warning("Cancelled");
        return Ok(());
    }
    
    // Validate - API secrets are typically 50 chars
    if api_secret.len() < 40 || api_secret.len() > 60 {
        ui::warning(&format!("API Secret looks unusual (length: {}). Expected ~50 chars.", api_secret.len()));
        if !chant::confirm("Continue anyway?").run() {
            return Ok(());
        }
    }

    println!();
    println!("{}", style("Step 2: Get Access Token & Secret").fg(Color::Yellow).bold());
    println!("{}", style("⚠️  NOT the Bearer Token! Scroll down to 'Authentication Tokens'").fg(Color::Red));
    ui::list_item("", "Under 'Authentication Tokens' section");
    ui::list_item("", "Click 'Generate' next to 'Access Token and Secret'");
    ui::list_item("", "Make sure you have Read and Write permissions!");
    println!();

    let access_token = input("Access Token:")
        .placeholder("e.g. 1234567890-AbCdEf...")
        .run();
    
    if access_token.is_empty() {
        ui::warning("Cancelled");
        return Ok(());
    }
    
    // Validate - access tokens typically start with numbers and contain a dash
    if access_token.starts_with("AAAA") {
        ui::error("That looks like a Bearer Token, not an Access Token!");
        ui::info("The Access Token starts with numbers like '1234567890-...'");
        ui::info("Look under 'Authentication Tokens', not 'Bearer Token'");
        return Ok(());
    }
    
    if !access_token.contains('-') {
        ui::warning("Access Token usually contains a dash (e.g. 1234567890-AbCdEf...)");
        if !chant::confirm("Continue anyway?").run() {
            return Ok(());
        }
    }

    let access_token_secret = input("Access Token Secret:")
        .placeholder("e.g. xYz123AbC...")
        .run();
    
    if access_token_secret.is_empty() {
        ui::warning("Cancelled");
        return Ok(());
    }
    
    // Validate - access token secrets are typically 45 chars and don't contain %
    if access_token_secret.contains('%') || access_token_secret.len() > 60 {
        ui::error("That doesn't look like an Access Token Secret!");
        ui::info("The Access Token Secret is about 45 characters, no special URL encoding");
        return Ok(());
    }

    // Update config
    config.twitter.api_key = api_key;
    config.twitter.api_secret = api_secret;
    config.twitter.access_token = access_token;
    config.twitter.access_token_secret = access_token_secret;

    // Save to file
    config.save()?;
    
    println!();
    ui::success("Twitter credentials saved!");
    ui::kv("Config", &Config::default_path()?.display().to_string());

    Ok(())
}

/// Interactive LLM API key setup
async fn setup_llm(config: &mut Config) -> Result<()> {
    ui::header("LLM API Setup");
    
    let provider = choose(&[
        "🟠 Anthropic (Claude)",
        "🟢 OpenAI (GPT-4)",
        "🦙 Ollama (Local)",
        "⬅️  Cancel",
    ])
    .header("Choose your LLM provider:")
    .cursor("")
    .run();

    match provider.as_deref() {
        Some("🟠 Anthropic (Claude)") => {
            ui::info("Get your API key from https://console.anthropic.com");
            println!();
            
            let api_key = input("Anthropic API Key:")
                .placeholder("sk-ant-...")
                .run();
            
            if api_key.is_empty() {
                ui::warning("Cancelled");
                return Ok(());
            }

            config.llm.provider = "anthropic".to_string();
            config.llm.api_key = api_key;
            config.llm.model = "claude-sonnet-4-20250514".to_string();
            
            config.save()?;
            ui::success("Anthropic API key saved!");
        }
        Some("🟢 OpenAI (GPT-4)") => {
            ui::info("Get your API key from https://platform.openai.com");
            println!();
            
            let api_key = input("OpenAI API Key:")
                .placeholder("sk-...")
                .run();
            
            if api_key.is_empty() {
                ui::warning("Cancelled");
                return Ok(());
            }

            config.llm.provider = "openai".to_string();
            config.llm.api_key = api_key;
            config.llm.model = "gpt-4".to_string();
            
            config.save()?;
            ui::success("OpenAI API key saved!");
        }
        Some("🦙 Ollama (Local)") => {
            ui::info("Make sure Ollama is running locally");
            println!();
            
            let model = input("Model name:")
                .placeholder("llama2")
                .default("llama2")
                .run();

            config.llm.provider = "ollama".to_string();
            config.llm.api_key = String::new();
            config.llm.model = model;
            config.llm.base_url = Some("http://localhost:11434/api/generate".to_string());
            
            config.save()?;
            ui::success("Ollama configured!");
        }
        _ => {}
    }

    Ok(())
}

/// Interactive defaults setup
async fn setup_defaults(config: &mut Config) -> Result<()> {
    ui::header("Tweet Defaults");
    
    let tone = choose(&[
        "😎 Casual - Developer-friendly, conversational",
        "👔 Professional - Informative, credible",
        "🚀 Hype - Exciting, high energy",
        "🔧 Technical - Focus on technical details",
    ])
    .header("Default tone:")
    .cursor("")
    .run();

    match tone.as_deref() {
        Some(t) if t.contains("Casual") => config.defaults.tone = "casual".to_string(),
        Some(t) if t.contains("Professional") => config.defaults.tone = "professional".to_string(),
        Some(t) if t.contains("Hype") => config.defaults.tone = "hype".to_string(),
        Some(t) if t.contains("Technical") => config.defaults.tone = "technical".to_string(),
        _ => return Ok(()),
    }

    let emojis = choose(&[
        "✅ Yes - Include emojis",
        "❌ No - No emojis",
    ])
    .header("Include emojis?")
    .cursor("")
    .run();

    config.defaults.emojis = emojis.as_deref().map(|e| e.contains("Yes")).unwrap_or(true);

    let hashtags = choose(&[
        "❌ No - No hashtags (recommended)",
        "✅ Yes - Include hashtags",
    ])
    .header("Include hashtags?")
    .cursor("")
    .run();

    config.defaults.hashtags = hashtags.as_deref().map(|h| h.contains("Yes")).unwrap_or(false);

    config.save()?;
    ui::success("Defaults saved!");

    Ok(())
}

/// Copy text to clipboard (macOS/Linux/Windows)
fn copy_to_clipboard(text: &str) {
    #[cfg(target_os = "macos")]
    {
        use std::process::{Command, Stdio};
        use std::io::Write;
        
        if let Ok(mut child) = Command::new("pbcopy")
            .stdin(Stdio::piped())
            .spawn()
        {
            if let Some(mut stdin) = child.stdin.take() {
                stdin.write_all(text.as_bytes()).ok();
            }
            child.wait().ok();
        }
    }

    #[cfg(target_os = "linux")]
    {
        use std::process::{Command, Stdio};
        use std::io::Write;
        
        // Try xclip first, then xsel
        let result = Command::new("xclip")
            .args(["-selection", "clipboard"])
            .stdin(Stdio::piped())
            .spawn();
            
        if let Ok(mut child) = result {
            if let Some(mut stdin) = child.stdin.take() {
                stdin.write_all(text.as_bytes()).ok();
            }
            child.wait().ok();
        }
    }

    #[cfg(target_os = "windows")]
    {
        use std::process::{Command, Stdio};
        use std::io::Write;
        
        if let Ok(mut child) = Command::new("clip")
            .stdin(Stdio::piped())
            .spawn()
        {
            if let Some(mut stdin) = child.stdin.take() {
                stdin.write_all(text.as_bytes()).ok();
            }
            child.wait().ok();
        }
    }
}