cai 0.13.0

User friendly CLI tool for AI tasks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
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
use std::io::stdin;
use std::io::{read_to_string, IsTerminal};

use cai::{
  analyze_file_content, create_commits, exec_tool, extract_text_from_file,
  generate_changelog, google_ocr_file, prompt_with_lang_cntxt, submit_prompt,
  transcribe_audio_file, Commands, ExecOptions, Model, Provider,
};
use chrono::NaiveDateTime;
use clap::crate_description;
use clap::{builder::styling, crate_version, Parser};
use color_print::cformat;
use futures::future::join_all;
use serde_json::{json, Value};
use std::error::Error;

// Rename a single file
async fn process_rename(
  opts: &ExecOptions,
  file: &str,
) -> Result<(), Box<dyn Error + Send + Sync>> {
  match analyze_file_content(opts, file).await {
    Ok(analysis) => {
      let timestamp_str = analysis.timestamp.unwrap_or_default();
      let timestamp_norm = timestamp_str.trim().to_lowercase();
      let valid_timestamp =
        NaiveDateTime::parse_from_str(&timestamp_norm, "%Y-%m-%dt%H:%Mz")
          .or_else(|_| {
            NaiveDateTime::parse_from_str(
              &(timestamp_norm.clone() + "t00:00z"),
              "%Y-%m-%dt%H:%Mz",
            )
          })
          .is_ok();
      let timestamp = if valid_timestamp {
        timestamp_norm.replace([':', 'z'], "").replace("t0000", "")
      } else {
        chrono::Local::now().format("%Y-%m-%dt%H%M").to_string()
      };
      let description = analysis //
        .description
        .trim()
        .to_lowercase()
        .replace(' ', "_")
        // Remove any non-alphanumeric characters
        .replace(
          |c: char| {
            !c.is_ascii_alphanumeric()
              && c != '_'
              && c != '-'
              && c != 'ä'
              && c != 'ö'
              && c != 'ü'
              && c != 'ß'
          },
          "",
        );
      rename_file(file.to_string(), timestamp, description);
      Ok(())
    }
    Err(error) => match error.downcast_ref::<std::io::Error>() {
      Some(err) if err.kind() == std::io::ErrorKind::InvalidData => {
        // If it's not a text file, use the creation time
        let timestamp = std::fs::metadata(file)
          .map(|meta| {
            meta
              .created()
              .map(|created| {
                chrono::DateTime::<chrono::Local>::from(created)
                  .format("%Y-%m-%dt%H%M")
                  .to_string()
              })
              .unwrap_or_else(|_| {
                chrono::Local::now().format("%Y-%m-%dt%H%M").to_string()
              })
          })
          .unwrap_or_else(|_| {
            chrono::Local::now().format("%Y-%m-%dt%H%M").to_string()
          });

        std::path::Path::new(file)
          .file_stem()
          .and_then(|file_name_no_ext| {
            file_name_no_ext.to_str().map(|s| s.to_string())
          })
          .map(|file_name| rename_file(file.to_string(), timestamp, file_name))
          .ok_or_else(|| {
            // Could not rename -> propagate error
            Box::<dyn Error + Send + Sync>::from("Failed to rename file")
          })?;
        Ok(())
      }
      _ => Err(error),
    },
  }
}

const CRATE_VERSION: &str = crate_version!();

#[derive(Parser, Debug)]
// #[command(version, about, long_about = None)]
#[clap(
  trailing_var_arg = true,
  about = color_print::cformat!(
    "<bold,underline>Cai {}</bold,underline>\n\n\
      <black,bold>{}</black,bold>",
    CRATE_VERSION,
    crate_description!(),
  ), /**/
  after_help = color_print::cformat!(
"
<bold,underline>Examples:</bold,underline>
  <dim># Send a prompt to the default model</dim>
  <b>cai</b> Which year did the Titanic sink

  <dim># Send a prompt to each provider's default model</dim>
  <b>cai all</b> Which year did the Titanic sink

  <dim># Send a prompt to Anthropic's Claude Opus</dim>
  <b>cai anthropic claude-opus</b> Which year did the Titanic sink
  <b>cai an claude-opus</b> Which year did the Titanic sink
  <b>cai cl</b> Which year did the Titanic sink
  <b>cai anthropic claude-opus-4-1</b> Which year did the Titanic sink

  <dim># Send a prompt to locally running Ollama server</dim>
  <b>cai ollama llama3</b> Which year did the Titanic sink
  <b>cai ol ll</b> Which year did the Titanic sink

  <dim># Use the `local` shortcut for using Ollama's default model</dim>
  <b>cai local</b> Which year did the Titanic sink

  <dim># Add data via stdin</dim>
  cat main.rs | <b>cai</b> Explain this code

  <dim># Get raw output without any metadata</dim>
  <b>cai --raw capital of Germany</b>

  <dim># Use a JSON schema to specify the output format</dim>
  <b>cai \
    --json-schema='{}' \
    gp Barack Obama
  </b>
",
"{\"properties\":{\"age\":{\"type\":\"number\"}},\"required\":[\"age\"]}"
  ),
  styles = styling::Styles::styled()
    .literal(styling::AnsiColor::Blue.on_default() | styling::Effects::BOLD)
    .placeholder(styling::AnsiColor::Yellow.on_default())
)]
struct Args {
  #[arg(long, short, action, help = "Print raw response without any metadata")]
  raw: bool,

  #[arg(long, short, action, help = "Prompt LLM in JSON output mode")]
  json: bool,

  #[arg(long, action, help = "JSON schema to validate the output against")]
  json_schema: Option<String>,

  #[command(subcommand)]
  command: Option<Commands>,

  /// The prompt to send to the AI model
  #[clap(allow_hyphen_values = true)]
  prompt: Vec<String>,
}

fn capitalize_str(str: &str) -> String {
  let mut chars = str.chars();
  match chars.next() {
    None => String::new(),
    Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
  }
}

fn shell_single_quote(arg: &str) -> String {
  // Wrap an argument for POSIX shells using single quotes,
  // escaping any embedded single quotes.
  if arg.is_empty() {
    "''".to_string()
  } else {
    format!("'{}'", arg.replace('\'', "'\\''"))
  }
}

async fn exec_with_args(args: Args, stdin: &str) {
  let stdin = if stdin.is_empty() {
    "".into()
  } else {
    format!("{stdin}\n")
  };
  let opts = ExecOptions {
    is_raw: args.raw,
    is_json: args.json,
    json_schema: args
      .json_schema
      .and_then(|schema_str| {
        serde_json::from_str(&schema_str).expect("Invalid JSON schema")
      })
      .map(|schema: Value| {
        let mut schema_obj = schema.as_object().unwrap().clone();
        schema_obj.insert("additionalProperties".to_string(), false.into());
        if !schema_obj.contains_key("type") {
          schema_obj.insert("type".to_string(), "object".into());
        }
        json!({
          "name": "requested_json_schema",
          "strict": true,
          "schema": schema_obj,
        })
      }),
    subcommand: args.command.clone(),
  };

  match args.command {
    None => {
      // No subcommand provided -> Use input as prompt for the default model
      submit_prompt(
        &None,
        &opts,
        &format!("{stdin}{}", &args.prompt.join(" ")), //
      )
      .await
    }
    Some(cmd) => match &cmd {
      Commands::Fast { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Groq,
            "openai/gpt-oss-20b".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Local { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Ollama, "llama3.2".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Value { prompt } => {
        let value_prompt = format!(
          "I want you to return only a plain value without explanation or additional text. \
          Respond with the answer and nothing else. Do not include any explanation, \
          reasoning, or additional information. Just give me the answer value.\n\n{}",
          prompt.join(" ")
        );
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-4.1".to_string())),
          &opts,
          &format!("{stdin}{value_prompt}"),
        )
        .await
      }
      Commands::Short { prompt } => {
        let short_prompt = format!(
          "Please provide a short, compact, and focused answer to the following question. \
          Be concise and to the point while still being accurate and complete. \
          Avoid unnecessary elaboration or tangential information.\n\n{}",
          prompt.join(" ")
        );
        submit_prompt(&None, &opts, &format!("{stdin}{short_prompt}")).await
      }
      Commands::Svg { prompt } => {
        // Force raw so only the SVG markup is printed
        let mut opts_svg = opts.clone();
        opts_svg.is_raw = true;

        let svg_prompt = format!(
          "Generate an SVG image according to the following description. \
           Respond ONLY with valid SVG markup – no explanations, no code fences.\n\n{}",
          prompt.join(" ")
        );

        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-4o-mini".to_string())),
          &opts_svg,
          &format!("{stdin}{svg_prompt}"),
        )
        .await
      }
      Commands::Edit {} => {
        // Create a temp file and open it in the user's editor
        let mut tmp_path = std::env::temp_dir();
        let ts = chrono::Local::now().format("%Y%m%d%H%M%S");
        tmp_path.push(format!("cai_prompt_{ts}.txt"));

        // Ensure the file exists
        if let Err(err) = std::fs::File::create(&tmp_path) {
          eprintln!("Failed to create temp file: {err}");
          std::process::exit(1);
        }

        let tmp_str = tmp_path.to_string_lossy().to_string();

        // Prefer VISUAL, then EDITOR, else sensible OS-specific fallbacks
        let editor_var = std::env::var("VISUAL")
          .ok()
          .or_else(|| std::env::var("EDITOR").ok());

        let status = if let Some(editor_cmd) = editor_var {
          if editor_cmd.contains(' ') {
            // Complex editor command with args, run via shell
            let cmdline =
              format!("{} {}", editor_cmd, shell_single_quote(&tmp_str));
            std::process::Command::new("sh")
              .arg("-c")
              .arg(cmdline)
              .status()
          } else {
            std::process::Command::new(editor_cmd)
              .arg(&tmp_str)
              .status()
          }
        } else if cfg!(target_os = "macos") {
          std::process::Command::new("open")
            .args(["-t", "-W", &tmp_str])
            .status()
        } else if cfg!(target_os = "windows") {
          std::process::Command::new("cmd")
            .args(["/C", "start", "/WAIT", "notepad", &tmp_str])
            .status()
        } else {
          // Generic UNIX fallback
          std::process::Command::new("nano").arg(&tmp_str).status()
        };

        match status {
          Ok(st) if st.success() => {}
          _ => {
            eprintln!("Failed to launch editor or editor exited with error");
            std::process::exit(1);
          }
        }

        let content = std::fs::read_to_string(&tmp_path)
          .unwrap_or_default()
          .trim()
          .to_string();

        if content.is_empty() {
          eprintln!("No prompt written (file empty). Aborting.");
          std::process::exit(1);
        }

        // Echo the prompt back to the user unless raw mode is requested
        if !opts.is_raw {
          let echoed = content.replace('\n', "\n> ");
          println!("> {echoed}\n");
        }

        submit_prompt(&None, &opts, &content).await
      }
      Commands::Config {} => {
        use cai::get_full_config;
        let xdg_dirs = xdg::BaseDirectories::with_prefix("cai").unwrap();
        let secrets_path = xdg_dirs
          .place_config_file("secrets.yaml")
          .expect("Couldn't create configuration directory");
        let secrets_path_str = secrets_path.to_str().unwrap();

        match get_full_config(secrets_path_str) {
          Ok(config) => {
            println!("Configuration loaded from: {secrets_path_str}\n");
            println!("Settings:");

            // Sort keys for consistent output
            let mut keys: Vec<_> = config.keys().collect();
            keys.sort();

            for key in keys {
              let value = config.get(key).unwrap();
              // Mask sensitive API keys - show first 4 and last 4 characters
              if key.contains("api_key") && value.len() > 12 {
                let masked =
                  format!("{}...{}", &value[..4], &value[value.len() - 4..]);
                println!("  {}: {}", key, masked);
              } else if key.contains("api_key") && !value.is_empty() {
                println!("  {}: ****", key);
              } else if !value.is_empty() {
                println!("  {}: {}", key, value);
              }
            }
          }
          Err(err) => {
            eprintln!("Failed to load configuration: {err}");
            std::process::exit(1);
          }
        }
      }
      Commands::Ocr { file } => {
        if let Err(err) = extract_text_from_file(&opts, file).await {
          eprintln!("Error extracting text: {err}");
          std::process::exit(1);
        }
      }
      Commands::GoogleOcr { file } => {
        if let Err(err) = google_ocr_file(&opts, file).await {
          eprintln!("Error extracting text with Google OCR: {err}");
          std::process::exit(1);
        }
      }
      Commands::Rename { files } => {
        for file in files {
          if let Err(e) = process_rename(&opts, file).await {
            eprintln!("{e}");
            std::process::exit(1);
          }
        }
      }
      Commands::Changelog { commit_hash } => {
        if let Err(err) = generate_changelog(&opts, commit_hash).await {
          eprintln!("Error generating changelog: {err}");
          std::process::exit(1);
        }
      }
      Commands::Commit {} => {
        if let Err(err) = create_commits(&opts).await {
          eprintln!("Error creating commits: {err}");
          std::process::exit(1);
        }
      }
      Commands::Reply { prompt } => {
        if stdin.is_empty() {
          eprintln!("Please pipe the conversation into cai via stdin.");
          std::process::exit(1);
        }
        let username = whoami::username();
        let reply_prompt = format!(
          "Given the following conversation, write the best possible reply. \
            Do not print a timestamp or a name at the beginning of your reply. \
            You are {username} and you reply to the other person/persons.\n\
            Conversation:\n{stdin}\n\n\
            Reply guidance: {}\n",
          prompt.join(" ")
        );

        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-4.1".to_string())),
          &opts,
          &reply_prompt,
        )
        .await
      }
      Commands::Rewrite { prompt } => {
        if stdin.is_empty() {
          eprintln!("Please pipe the text to be rewritten into cai via stdin.");
          std::process::exit(1);
        }
        let base_rewrite_prompt = "\
          Fix any spelling mistakes, grammatical errors, \
            and wording issues in the following text. \
          Maintain the original meaning and tone \
            while improving clarity and correctness. \
          Return only the corrected text \
            without any explanations or additional commentary.";

        let rewrite_prompt = if prompt.is_empty() {
          format!(
            "{base_rewrite_prompt}\n\n\
            Text to rewrite:\n{stdin}"
          )
        } else {
          format!(
            "{base_rewrite_prompt}\n\n
            Additional instructions: {}\n\n\
            Text to correct:\n\
            {stdin}",
            prompt.join(" ")
          )
        };

        let mut rewrite_opts = opts.clone();
        rewrite_opts.is_raw = true;

        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-4.1".to_string())),
          &rewrite_opts,
          &rewrite_prompt,
        )
        .await
      }
      Commands::Transcribe { file } => {
        if let Err(_err) = transcribe_audio_file(&opts, file).await {
          eprintln!("Error transcribing file: {{_err}}");
          std::process::exit(1);
        }
      }
      Commands::Say { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::OpenAI,
            "gpt-4o-mini-tts".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Image { prompt } => {
        let image_prompt = prompt.join(" ").to_string();
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-image-1.5".to_string())),
          &opts,
          &format!("{stdin}{image_prompt}"),
        )
        .await
      }
      Commands::Photo { prompt } => {
        let photo_prompt = format!(
          "Generate a photorealistic image that looks like it was taken with a camera. \
          The image should have natural lighting, realistic textures, and appear as an \
          authentic photograph rather than a digital illustration or rendering. \
          Subject: {}",
          prompt.join(" ")
        );
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-image-1.5".to_string())),
          &opts,
          &format!("{stdin}{photo_prompt}"),
        )
        .await
      }

      //////////////////////////////////////////////////////////////////////////
      //=============================== MODELS =================================
      //////////////////////////////////////////////////////////////////////////
      Commands::SectionModels {} => {}
      Commands::Google { model, prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Google, model.to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Gemini { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Google,
            "gemini-2.5-flash".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::GeminiFlash { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Google,
            "gemini-2.5-flash".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::GoogleImage { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Google,
            "gemini-2.5-flash-image".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Groq { model, prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Groq, model.to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Llama3 { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Groq,
            "llama-3.1-8b-instant".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Cerebras { model, prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Cerebras, model.to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Deepseek { model, prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::DeepSeek, model.to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Openai { model, prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, model.to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Gpt5 { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-5".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Gpt5Mini { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-5-mini".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Gpt5Nano { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-5-nano".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Gpt41 { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-4.1".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Gpt41Mini { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-4.1-mini".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Gpt41Nano { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "gpt-4.1-nano".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::O1Pro { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::OpenAI, "o1-pro".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Anthropic { model, prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Anthropic, model.to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::ClaudeOpus { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Anthropic,
            "claude-opus-4-1".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::ClaudeSonnet { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Anthropic,
            "claude-sonnet-4-5".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::ClaudeHaiku { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Anthropic,
            "claude-3-5-haiku-latest".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Llamafile { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Llamafile, "".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await //
      }
      Commands::Ollama { model, prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Ollama, model.to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await //
      }
      Commands::Xai { model, prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::XAI, model.to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await //
      }
      Commands::Grok { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::XAI, "grok-4-latest".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Perplexity { model, prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Perplexity, model.to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::Sonar { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Perplexity, "sonar".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::SonarPro { prompt } => {
        submit_prompt(
          &Some(&Model::Model(Provider::Perplexity, "sonar-pro".to_string())),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::SonarReasoning { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Perplexity,
            "sonar-reasoning".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::SonarReasoningPro { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Perplexity,
            "sonar-reasoning-pro".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::SonarDeepResearch { prompt } => {
        submit_prompt(
          &Some(&Model::Model(
            Provider::Perplexity,
            "sonar-deep-research".to_string(),
          )),
          &opts,
          &format!("{stdin}{}", prompt.join(" ")),
        )
        .await
      }
      Commands::All { prompt } => {
        let models = vec![
          Model::Model(Provider::Anthropic, "claude-sonnet-4-5".to_string()),
          Model::Model(Provider::Cerebras, "gpt-oss-120b".to_string()),
          Model::Model(Provider::Google, "gemini-2.5-flash".to_string()),
          Model::Model(Provider::Groq, "openai/gpt-oss-20b".to_string()),
          Model::Model(Provider::Llamafile, "".to_string()),
          Model::Model(Provider::Ollama, "llama3".to_string()),
          Model::Model(Provider::OpenAI, "gpt-5-mini".to_string()),
          Model::Model(Provider::XAI, "grok-3-mini-latest".to_string()),
          Model::Model(Provider::Perplexity, "sonar".to_string()),
        ];

        let mut handles = vec![];

        for model in models.into_iter() {
          let prompt_str = format!("{}\n{}", stdin, prompt.join(" "));
          let model_fmt = model.to_string();
          let opts_clone = opts.clone();

          handles.push(tokio::spawn(async move {
            match exec_tool(&Some(&model), &opts_clone, &prompt_str).await {
              Ok(_) => {}
              Err(err) => {
                let err_fmt = capitalize_str(&err.to_string());
                eprintln!(
                  "{}",
                  cformat!(
                    "<bold>⏱️    0 ms</bold> | \
                    <bold>🧠 {}</bold><red>\nERROR:\n{}</red>\n",
                    model_fmt,
                    err_fmt
                  )
                );
              }
            }
          }));
        }

        join_all(handles).await;
      }

      //////////////////////////////////////////////////////////////////////////
      //================================ CODING ================================
      //////////////////////////////////////////////////////////////////////////
      Commands::SectionCoding {} => {}
      Commands::Bash { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::C { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Cpp { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Cs { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Elm { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Fish { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Fs { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Gd { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Gl { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Golang { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Hs { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Java { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Js { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Kt { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Ly { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Lua { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Nix { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Oc { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Php { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Pg { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Ps { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Py { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Rb { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Rs { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Sql { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Sw { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Ts { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Ty { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Wl { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Zig { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Docker { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Git { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }
      Commands::Jq { prompt } => {
        prompt_with_lang_cntxt(&opts, &cmd, prompt).await
      }

      //////////////////////////////////////////////////////////////////////////
      //============================== DATABASE ================================
      //////////////////////////////////////////////////////////////////////////
      Commands::SectionDatabase {} => {}
      Commands::Query { database, prompt } => {
        if let Err(err) =
          cai::query_database(&opts, database, &prompt.join(" ")).await
        {
          eprintln!("Error querying database: {err}");
          std::process::exit(1);
        }
      }
    },
  };
}

fn rename_file(file: String, timestamp: String, description: String) {
  let path = std::path::Path::new(&file);
  let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or("");
  let mut new_name = path
    .parent()
    .unwrap_or_else(|| std::path::Path::new(""))
    .join(format!("{timestamp}_{description}.{ext}"))
    .to_str()
    .unwrap()
    .to_string();

  let mut counter = 0;
  loop {
    if std::path::Path::new(&new_name).exists() {
      counter += 1;
      new_name = format!("{timestamp}_{description}_{counter}.{ext}")
    } else {
      break;
    }
  }

  if let Err(err) = std::fs::rename(&file, &new_name) {
    eprintln!("Error renaming file: {err}");
    std::process::exit(1);
  }
  println!("Renamed {file} to {new_name}");
}

#[tokio::main]
async fn main() {
  let stdin = stdin();
  let mut args_vector = std::env::args().collect::<Vec<_>>();
  let args = Args::parse_from(&args_vector);

  match &args.command {
    Some(Commands::Rename { .. }) => {
      exec_with_args(args, "").await;
    }
    _ => {
      if stdin.is_terminal() {
        exec_with_args(args, "").await;
      } else {
        let input = read_to_string(stdin).unwrap();
        let only_stdin = !input.is_empty() && args_vector.len() <= 1;

        if only_stdin {
          args_vector.push("".to_string());
        }

        let mut args = Args::parse_from(args_vector);

        if only_stdin {
          args.prompt = vec![input];
          exec_with_args(args, "").await;
        } else {
          exec_with_args(args, input.trim()).await;
        }
      }
    }
  }
}

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

  #[test]
  fn test_parse_args() {
    let parse_res = Args::try_parse_from(["gpt"]);
    assert!(parse_res.is_err());
    assert!(&parse_res.unwrap_err().to_string().contains("Usage: gpt"));
  }
}