simian 0.2.1

A command-line tool for exploring and implementing Machine Learning algorithms in Rust.
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
use anyhow::{Context, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::Duration;

pub enum RenderFormat {
  Html,
  Url,
}

pub fn render(format: RenderFormat, content: &str) {
  let final_url = match format {
    RenderFormat::Html => {
      use base64::{Engine as _, engine::general_purpose};
      format!(
        "data:text/html;base64,{}",
        general_purpose::STANDARD.encode(content)
      )
    }
    RenderFormat::Url => content.to_string(),
  };

  println!(
    "__SIMIAN_BEGIN_CONTENT\n{}\n__SIMIAN_END_CONTENT",
    final_url
  );
}

const GITHUB_CLIENT_ID: &str = "Ov23liic5h1kFHG61swj";

#[derive(Serialize, Deserialize, Debug)]
struct DeviceAuthResponse {
  device_code: String,
  user_code: String,
  verification_uri: String,
  expires_in: u64,
  interval: u64,
}

#[derive(Serialize, Deserialize, Debug)]
struct AccessTokenResponse {
  access_token: Option<String>,
  token_type: Option<String>,
  scope: Option<String>,
  error: Option<String>,
  error_description: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
struct StoredAuth {
  access_token: String,
}

fn get_auth_file() -> Result<PathBuf> {
  let home = dirs::home_dir().context("Could not find HOME directory")?;
  let path = home.join(".simian").join("oauth").join("github.json");
  if let Some(parent) = path.parent() {
    std::fs::create_dir_all(parent)?;
  }
  Ok(path)
}

async fn authenticate(client: &Client) -> Result<String> {
  let auth_file = get_auth_file()?;
  if auth_file.exists()
    && let Ok(content) = std::fs::read_to_string(&auth_file)
    && let Ok(stored) = serde_json::from_str::<StoredAuth>(&content)
  {
    return Ok(stored.access_token);
  }

  let client_id =
    std::env::var("SIMIAN_GITHUB_CLIENT_ID").unwrap_or_else(|_| GITHUB_CLIENT_ID.to_string());
  if client_id == "YOUR_GITHUB_APP_CLIENT_ID" {
    anyhow::bail!(
      "GitHub Client ID is not configured. Please set the SIMIAN_GITHUB_CLIENT_ID environment variable or update GITHUB_CLIENT_ID in src/paper.rs."
    );
  }

  tracing::info!("Authenticating with GitHub...");

  // 1. Request device code
  let res = client
    .post("https://github.com/login/device/code")
    .header("Accept", "application/json")
    .json(&serde_json::json!({
        "client_id": &client_id,
        "scope": "public_repo",
    }))
    .send()
    .await?;

  let res_body = res.text().await?;
  let device_auth: DeviceAuthResponse = serde_json::from_str(&res_body).map_err(|e| {
    anyhow::anyhow!(
      "Failed to parse GitHub device auth response: {}\nResponse body: {}",
      e,
      res_body
    )
  })?;

  tracing::info!("--------------------------------------------------");
  tracing::info!("Please visit: {}", device_auth.verification_uri);
  tracing::info!("And enter code: {}", device_auth.user_code);
  tracing::info!("--------------------------------------------------");

  // Open browser automatically
  let _ = open::that(&device_auth.verification_uri);

  // 2. Poll for the token
  let mut interval = device_auth.interval;
  loop {
    tokio::time::sleep(Duration::from_secs(interval)).await;

    let res = client
      .post("https://github.com/login/oauth/access_token")
      .header("Accept", "application/json")
      .json(&serde_json::json!({
          "client_id": &client_id,
          "device_code": &device_auth.device_code,
          "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
      }))
      .send()
      .await?;

    let res_body = res.text().await?;
    let token_res: AccessTokenResponse = serde_json::from_str(&res_body).map_err(|e| {
      anyhow::anyhow!(
        "Failed to parse GitHub token response: {}\nResponse body: {}",
        e,
        res_body
      )
    })?;

    if let Some(token) = token_res.access_token {
      tracing::info!("Successfully authenticated!");
      let stored = StoredAuth {
        access_token: token.clone(),
      };
      std::fs::write(&auth_file, serde_json::to_string_pretty(&stored)?)?;
      return Ok(token);
    } else if let Some(err) = token_res.error {
      match err.as_str() {
        "authorization_pending" => continue,
        "slow_down" => {
          interval += 5;
          continue;
        }
        "expired_token" => anyhow::bail!("The device code expired. Please try again."),
        "access_denied" => anyhow::bail!("User canceled the authorization request."),
        _ => anyhow::bail!("OAuth Error: {} - {:?}", err, token_res.error_description),
      }
    }
  }
}

fn get_paper_dir(id: &str) -> Result<PathBuf> {
  let p_path = Path::new(id);
  if id.contains('/') || id.contains('\\') {
    if p_path.exists() {
      if p_path.extension().is_some_and(|ext| ext == "smn") {
        return Ok(p_path.parent().unwrap().to_path_buf());
      }
      return Ok(p_path.to_path_buf());
    }
    anyhow::bail!("Path {} does not exist", id);
  }

  let local_dir = std::env::current_dir()?.join(id);
  if local_dir.exists() {
    return Ok(local_dir);
  }

  let home = dirs::home_dir().context("Could not find HOME directory")?;
  let simian_dir = home.join(".simian").join("papers").join(id);
  if simian_dir.exists() {
    return Ok(simian_dir);
  }

  anyhow::bail!(
    "Paper '{}' not found in current directory or ~/.simian/papers/",
    id
  );
}

pub async fn submit(id: String, dry: bool) -> Result<()> {
  let paper_dir = get_paper_dir(&id)?;
  let source_file = paper_dir.join("source.smn");
  if !source_file.exists() {
    anyhow::bail!("No source.smn found in paper directory: {:?}", paper_dir);
  }

  let client = Client::builder().user_agent("Simian-CLI").build()?;

  // Attempt authentication first
  let token = authenticate(&client).await?;

  tracing::info!(
    "Authentication successful. Token begins with: {}...",
    &token[..4]
  );

  // Create bundle directory
  let bundle_dir = paper_dir.join(".bundle");
  if bundle_dir.exists() {
    std::fs::remove_dir_all(&bundle_dir)?;
  }
  std::fs::create_dir_all(&bundle_dir)?;
  let bundle_assets = bundle_dir.join("assets");
  std::fs::create_dir_all(&bundle_assets)?;

  tracing::info!("Parsing source.smn and collecting active plots...");
  let source_content = std::fs::read_to_string(&source_file)?;
  let ast: serde_json::Value = serde_json::from_str(&source_content)?;

  fn extract_markdown_text(children: &[serde_json::Value]) -> String {
    let mut text = String::new();
    for child in children {
      let child_type = child.get("type").and_then(|v| v.as_str()).unwrap_or("");
      if child_type == "latex-inline" {
        if let Some(subchildren) = child.get("children").and_then(|v| v.as_array()) {
          text.push('$');
          text.push_str(&extract_markdown_text(subchildren));
          text.push('$');
        }
      } else if let Some(t) = child.get("text").and_then(|v| v.as_str()) {
        text.push_str(t);
      }
    }
    text
  }

  let mut title_text = String::new();
  if let Some(blocks) = ast.as_array() {
    for block in blocks {
      if let Some(block_type) = block.get("type").and_then(|v| v.as_str())
        && block_type == "title"
      {
        if let Some(children) = block.get("children").and_then(|v| v.as_array()) {
          title_text = extract_markdown_text(children);
        }
        break;
      }
    }
  }
  let title_text = title_text.trim().to_string();

  let metadata_path = paper_dir.join("metadata.json");
  let mut slug = String::new();
  let mut metadata_json = serde_json::json!({});

  if metadata_path.exists()
    && let Ok(content) = std::fs::read_to_string(&metadata_path)
    && let Ok(json) = serde_json::from_str::<serde_json::Value>(&content)
  {
    metadata_json = json.clone();
    if let Some(s) = json.get("slug").and_then(|v| v.as_str()) {
      slug = s.to_string();
    }
  }

  let mut version = metadata_json
    .get("version")
    .and_then(|v| v.as_u64())
    .unwrap_or(1);
  if !dry && metadata_json.get("publishedAt").is_some() {
    version += 1;
    let obj = metadata_json.as_object_mut().unwrap();
    obj.remove("publishedAt");
    obj.remove("approvers");
    obj.insert("version".to_string(), serde_json::json!(version));

    // Write the updated metadata.json to disk so the user has the new version locally
    std::fs::write(
      &metadata_path,
      serde_json::to_string_pretty(&metadata_json)?,
    )?;
  } else if metadata_json.get("version").is_none() {
    metadata_json["version"] = serde_json::json!(version);
    if !dry {
      std::fs::write(
        &metadata_path,
        serde_json::to_string_pretty(&metadata_json)?,
      )?;
    }
  }

  let theme = dialoguer::theme::ColorfulTheme::default();

  if slug.is_empty() {
    let suffix = if id.starts_with("paper-") && id.len() > 6 {
      &id[6..]
    } else {
      &id
    };

    let base_slug = slug::slugify(&title_text);
    let suggested_slug = if base_slug.is_empty() {
      format!("paper-{}", suffix)
    } else {
      format!("{}-{}", base_slug, suffix)
    };

    let confirmation = dialoguer::Confirm::with_theme(&theme)
      .with_prompt(format!(
        "We extracted the title '{}'. Do you want to publish this paper as `{}`?",
        title_text, suggested_slug
      ))
      .default(true)
      .interact()?;

    if confirmation {
      slug = suggested_slug;
    } else {
      slug = dialoguer::Input::with_theme(&theme)
        .with_prompt("Please enter a custom slug for this paper")
        .interact_text()?;
    }

    metadata_json["slug"] = serde_json::json!(slug);
  }

  if metadata_json.get("authors").is_none() {
    tracing::info!("Fetching your GitHub profile...");
    let auth_client = reqwest::Client::builder()
      .user_agent("Simian-CLI")
      .default_headers({
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
          "Authorization",
          format!("Bearer {}", token).parse().unwrap(),
        );
        headers.insert("Accept", "application/vnd.github.v3+json".parse().unwrap());
        headers
      })
      .build()?;

    let user_res: serde_json::Value = auth_client
      .get("https://api.github.com/user")
      .send()
      .await?
      .json()
      .await?;

    let primary_id = user_res.get("id").and_then(|v| v.as_u64()).context("Failed to get GitHub user ID. Try checking your internet connection or removing ~/.simian/oauth/github.json.")?;
    let mut authors = vec![primary_id];

    let co_authors: String = dialoguer::Input::with_theme(&theme)
      .with_prompt("Enter any co-author GitHub handles (comma-separated), or leave blank")
      .allow_empty(true)
      .interact_text()?;

    if !co_authors.trim().is_empty() {
      for handle in co_authors.split(',') {
        let handle = handle.trim();
        if !handle.is_empty() {
          let co_res: serde_json::Value = client
            .get(format!("https://api.github.com/users/{}", handle))
            .send()
            .await?
            .json()
            .await?;
          if let Some(uid) = co_res.get("id").and_then(|v| v.as_u64()) {
            authors.push(uid);
          } else {
            tracing::warn!("Could not find GitHub user '{}'", handle);
          }
        }
      }
    }

    metadata_json["authors"] = serde_json::json!(authors);
  }

  if metadata_json.get("submittedAt").is_none() {
    metadata_json["submittedAt"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
  }

  std::fs::write(
    &metadata_path,
    serde_json::to_string_pretty(&metadata_json)?,
  )?;

  // Create symlink if needed
  if id != slug {
    let home = dirs::home_dir().context("Could not find HOME directory")?;
    let simian_papers = home.join(".simian").join("papers");
    let link_path = simian_papers.join(&slug);
    if !link_path.exists() {
      #[cfg(unix)]
      let _ = std::os::unix::fs::symlink(&paper_dir, &link_path);
      #[cfg(windows)]
      let _ = std::os::windows::fs::symlink_dir(&paper_dir, &link_path);
    }
  }

  let mut markdown = format!("# Paper: {}\n\n", title_text);

  if let Some(blocks) = ast.as_array() {
    for block in blocks {
      let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");

      if block_type == "paragraph" || block_type == "text" {
        let text = if let Some(children) = block.get("children").and_then(|v| v.as_array()) {
          extract_markdown_text(children)
        } else {
          String::new()
        };
        markdown.push_str(&text);
        markdown.push_str("\n\n");
      } else if block_type == "latex-block" {
        let code = if let Some(children) = block.get("children").and_then(|v| v.as_array()) {
          extract_markdown_text(children)
        } else {
          String::new()
        };
        markdown.push_str(&format!("$$\n{}\n$$\n\n", code));
      } else if block_type == "code-block" {
        let mut code = String::new();
        if let Some(children) = block.get("children").and_then(|v| v.as_array()) {
          for child in children {
            if let Some(t) = child.get("text").and_then(|v| v.as_str()) {
              code.push_str(t);
            }
          }
        }
        let lang = block
          .get("language")
          .and_then(|v| v.as_str())
          .unwrap_or("rust");
        markdown.push_str(&format!("```{}\n{}\n```\n", lang, code));

        if let Some(output) = block.get("output") {
          if let Some(stdout) = output.get("stdout").and_then(|v| v.as_str())
            && !stdout.is_empty()
          {
            markdown.push_str(&format!("\n```text\n{}\n```\n", stdout.trim_end()));
          }
          if let Some(stderr) = output.get("stderr").and_then(|v| v.as_str())
            && !stderr.is_empty()
          {
            markdown.push_str(&format!("\n```text\n{}\n```\n", stderr.trim_end()));
          }

          if let Some(items) = output.get("items").and_then(|v| v.as_array()) {
            for item in items {
              if let Some(url) = item.get("url").and_then(|v| v.as_str()) {
                let state_hash = if let Some(state) = item.get("state") {
                  let json = serde_json::to_string(state).unwrap_or_default();
                  use base64::{Engine as _, engine::general_purpose};
                  format!("#{}", general_purpose::STANDARD.encode(json))
                } else {
                  String::new()
                };

                if url.starts_with("data:text/html;base64,") {
                  let b64 = url.trim_start_matches("data:text/html;base64,");
                  use base64::{Engine as _, engine::general_purpose};
                  if let Ok(decoded) = general_purpose::STANDARD.decode(b64) {
                    let rand_id = rand::random::<u32>();
                    let html_filename = format!("plot-{}.html", rand_id);
                    let png_filename = format!("plot-{}.png", rand_id);
                    let html_dest = bundle_assets.join(&html_filename);
                    let png_dest = bundle_assets.join(&png_filename);
                    std::fs::write(&html_dest, decoded)?;

                    let mut screenshot_taken = false;
                    let mut should_capture = false;
                    let mut browser_opts = headless_chrome::LaunchOptions::default_builder()
                      .build()
                      .unwrap();
                    browser_opts.headless = false; // Prevent old --headless
                    browser_opts.enable_gpu = true; // Prevent --disable-gpu
                    // Use new headless mode which supports WebGL properly
                    browser_opts
                      .args
                      .push(std::ffi::OsStr::new("--headless=new"));

                    match headless_chrome::browser::default_executable() {
                      Ok(path) => {
                        browser_opts.path = Some(path);
                        should_capture = true;
                      }
                      Err(_) => {
                        let download = dialoguer::Confirm::new()
                          .with_prompt("Chrome/Chromium is required to capture plots but wasn't found. Would you like to automatically download a lightweight headless Chromium?")
                          .default(true)
                          .interact().unwrap_or(false);
                        if download {
                          tracing::info!(
                            "Downloading headless Chromium (this may take a minute)..."
                          );
                          browser_opts.path = None; // Browser::new will automatically fetch it
                          should_capture = true;
                        }
                      }
                    }

                    if should_capture
                      && let Ok(browser) = headless_chrome::Browser::new(browser_opts)
                      && let Ok(tab) = browser.new_tab()
                    {
                      let _ = tab.set_bounds(headless_chrome::types::Bounds::Normal {
                        left: Some(0),
                        top: Some(0),
                        width: Some(800.0),
                        height: Some(600.0),
                      });
                      let mut file_url = format!(
                        "file://{}",
                        html_dest
                          .canonicalize()
                          .unwrap_or(html_dest.clone())
                          .display()
                      );
                      file_url.push_str(&state_hash);

                      tracing::info!("Taking screenshot of {}", html_filename);
                      if tab.navigate_to(&file_url).is_ok() {
                        let _ = tab.wait_until_navigated();
                        std::thread::sleep(std::time::Duration::from_millis(500));
                        if let Ok(png_data) = tab.capture_screenshot(
                          headless_chrome::protocol::cdp::Page::CaptureScreenshotFormatOption::Png,
                          None,
                          None,
                          true,
                        ) && std::fs::write(&png_dest, png_data).is_ok()
                        {
                          markdown.push_str(&format!("\n![Plot](./assets/{})\n", png_filename));
                          screenshot_taken = true;
                        }
                      }
                    }

                    if !screenshot_taken {
                      markdown.push_str(&format!("\n*(Interactive Plot: {})*\n", html_filename));
                    }
                  }
                } else if url.starts_with("data:image/") {
                  let parts: Vec<&str> = url.splitn(2, ',').collect();
                  if parts.len() == 2 {
                    let b64 = parts[1];
                    use base64::{Engine as _, engine::general_purpose};
                    if let Ok(decoded) = general_purpose::STANDARD.decode(b64) {
                      let rand_id = rand::random::<u32>();
                      let ext = if url.starts_with("data:image/png") {
                        "png"
                      } else {
                        "jpg"
                      };
                      let filename = format!("image-{}.{}", rand_id, ext);
                      let dest = bundle_assets.join(&filename);
                      std::fs::write(&dest, decoded)?;
                      markdown.push_str(&format!("\n![Image](./assets/{})\n", filename));
                    }
                  }
                } else {
                  markdown.push_str(&format!("\n![Media]({})\n", url));
                }
              }
            }
          }
        }
        markdown.push('\n');
      } else if block_type == "heading" || block_type == "title" {
        let text = if let Some(children) = block.get("children").and_then(|v| v.as_array()) {
          extract_markdown_text(children)
        } else {
          String::new()
        };
        markdown.push_str(&format!("## {}\n\n", text));
      }
    }
  }

  std::fs::write(bundle_dir.join("paper.md"), markdown)?;
  std::fs::create_dir_all(bundle_dir.join("assets"))?;
  std::fs::copy(&source_file, bundle_dir.join("assets/source.smn"))?;

  tracing::info!("Extracting embedded React App...");

  for file in crate::studio::UiAssets::iter() {
    let path_str = file.as_ref();
    if let Some(content) = crate::studio::UiAssets::get(path_str) {
      if path_str == "index.html" {
        let mut index_html = String::from_utf8_lossy(&content.data).into_owned();
        let ast_json = serde_json::to_string(&ast)?;
        let mut meta = metadata_json.clone();
        if dry {
          meta["approvers"] = serde_json::json!([1024025, 810438, 6304496]);
          meta["mockVersions"] = serde_json::json!([
            {
              "sha": "mock-sha-2",
              "commit": {
                "message": format!("Publish paper: {}", title_text),
                "author": { "date": "2026-06-17T12:00:00Z" }
              }
            },
            {
              "sha": "mock-sha-1",
              "commit": {
                "message": "Initial publication",
                "author": { "date": "2026-06-16T12:00:00Z" }
              }
            }
          ]);
        }
        let metadata_str = serde_json::to_string(&meta)?;
        let injection = format!(
          "window.__SIMIAN_PAPER_DATA__ = {};\nwindow.__SIMIAN_PAPER_METADATA__ = {};",
          ast_json, metadata_str
        );
        index_html = index_html.replace("// __SIMIAN_INJECT__", &injection);
        std::fs::write(bundle_dir.join("index.html"), index_html)?;
      } else {
        let out_path = bundle_dir.join(path_str);
        if let Some(parent) = out_path.parent() {
          let _ = std::fs::create_dir_all(parent);
        }
        std::fs::write(&out_path, content.data.as_ref())?;
      }
    }
  }

  tracing::info!("Bundle is ready at: {:?}", bundle_dir);

  let wants_preview = dry
    || dialoguer::Confirm::with_theme(&theme)
      .with_prompt("Do you want to preview the paper locally before submitting?")
      .default(true)
      .interact()?;

  if wants_preview {
    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 0));
    let bundle_dir_clone = bundle_dir.clone();

    let router =
      axum::Router::new().fallback_service(tower_http::services::ServeDir::new(bundle_dir_clone));
    let listener = tokio::net::TcpListener::bind(addr).await?;
    let actual_addr = listener.local_addr()?;
    let url = format!("http://{}", actual_addr);

    tracing::info!("Starting preview server at {}", url);
    let _ = open::that(&url);

    let server_handle = tokio::spawn(async move {
      axum::serve(listener, router).await.unwrap();
    });

    if dry {
      tracing::info!("Dry run complete. The preview server is running.");
      tracing::info!("Press Ctrl+C to exit.");
      std::future::pending::<()>().await;
    } else {
      let proceed = dialoguer::Confirm::with_theme(&theme)
        .with_prompt("Does the preview look good? Proceed with submission?")
        .default(true)
        .interact()?;

      if !proceed {
        anyhow::bail!("Submission aborted by user.");
      }

      server_handle.abort();
    }
  } else if dry {
    return Ok(());
  }

  tracing::info!("Authenticating with GitHub API...");
  let auth_client = reqwest::Client::builder()
    .user_agent("Simian-CLI")
    .default_headers({
      let mut headers = reqwest::header::HeaderMap::new();
      headers.insert(
        "Authorization",
        format!("Bearer {}", token).parse().unwrap(),
      );
      headers.insert("Accept", "application/vnd.github.v3+json".parse().unwrap());
      headers
    })
    .build()?;

  // 2. Get base commit
  tracing::info!("Fetching latest commit from main branch...");
  let ref_url = "https://api.github.com/repos/nosebit/simian-papers/git/ref/heads/main";
  let ref_res: serde_json::Value = auth_client.get(ref_url).send().await?.json().await?;
  let base_sha = ref_res
    .get("object")
    .and_then(|o| o.get("sha"))
    .and_then(|s| s.as_str())
    .context("Failed to get base commit SHA from nosebit/simian-papers main branch!")?;

  // 4. Create blobs and tree
  tracing::info!("Uploading files to GitHub...");
  let mut tree_nodes = Vec::new();

  async fn upload_blob(client: &reqwest::Client, content: &[u8]) -> Result<String> {
    let b64 = {
      use base64::{Engine as _, engine::general_purpose};
      general_purpose::STANDARD.encode(content)
    };
    let res: serde_json::Value = client
      .post("https://api.github.com/repos/nosebit/simian-papers/git/blobs")
      .json(&serde_json::json!({
        "content": b64,
        "encoding": "base64"
      }))
      .send()
      .await?
      .json()
      .await?;
    res
      .get("sha")
      .and_then(|s| s.as_str())
      .map(|s| s.to_string())
      .context("Failed to upload blob")
  }

  // Iterate over bundle dir recursively
  let mut stack = vec![(bundle_dir.clone(), String::new())];
  while let Some((dir, rel_path)) = stack.pop() {
    for entry in std::fs::read_dir(dir)? {
      let entry = entry?;
      let path = entry.path();
      let file_name = entry.file_name().to_string_lossy().to_string();
      let entry_rel = if rel_path.is_empty() {
        file_name
      } else {
        format!("{}/{}", rel_path, file_name)
      };

      if path.is_dir() {
        stack.push((path, entry_rel));
      } else {
        let content = std::fs::read(&path)?;
        let sha = upload_blob(&auth_client, &content).await?;
        let tree_path = format!("published/{}-v{}/{}", slug, version, entry_rel);

        tree_nodes.push(serde_json::json!({
          "path": tree_path,
          "mode": "100644",
          "type": "blob",
          "sha": sha
        }));
      }
    }
  }

  // Add the HTML redirect blob for the unversioned URL
  let redirect_html = format!(
    r#"<!DOCTYPE html>
<meta charset="utf-8">
<title>Redirecting...</title>
<meta http-equiv="refresh" content="0; URL=../{}-v{}">
"#,
    slug, version
  );
  let redirect_sha = upload_blob(&auth_client, redirect_html.as_bytes()).await?;
  tree_nodes.push(serde_json::json!({
    "path": format!("published/{}/index.html", slug),
    "mode": "100644",
    "type": "blob",
    "sha": redirect_sha
  }));

  // 5. Create Tree
  tracing::info!("Creating git tree...");
  let tree_res: serde_json::Value = auth_client
    .post("https://api.github.com/repos/nosebit/simian-papers/git/trees")
    .json(&serde_json::json!({
      "base_tree": base_sha,
      "tree": tree_nodes
    }))
    .send()
    .await?
    .json()
    .await?;
  let tree_sha = tree_res
    .get("sha")
    .and_then(|s| s.as_str())
    .context("Failed to create tree")?;

  // 5. Create Commit
  tracing::info!("Creating commit...");
  let commit_res: serde_json::Value = auth_client
    .post("https://api.github.com/repos/nosebit/simian-papers/git/commits")
    .json(&serde_json::json!({
      "message": format!("Publish paper: {}", title_text),
      "tree": tree_sha,
      "parents": [base_sha]
    }))
    .send()
    .await?
    .json()
    .await?;
  let commit_sha = commit_res
    .get("sha")
    .and_then(|s| s.as_str())
    .context("Failed to create commit")?;

  // 7. Update or Create Branch
  // 6. Update or Create Branch
  let branch_name = format!("paper/{}", slug);
  tracing::info!("Updating branch {}...", branch_name);

  let ref_url = format!(
    "https://api.github.com/repos/nosebit/simian-papers/git/refs/heads/{}",
    branch_name
  );
  let ref_check = auth_client.get(&ref_url).send().await?;

  if ref_check.status().is_success() {
    let patch_res = auth_client
      .patch(&ref_url)
      .json(&serde_json::json!({
        "sha": commit_sha,
        "force": true
      }))
      .send()
      .await?;
    if !patch_res.status().is_success() {
      anyhow::bail!("Failed to update branch: {:?}", patch_res.text().await?);
    }
  } else {
    let branch_res = auth_client
      .post("https://api.github.com/repos/nosebit/simian-papers/git/refs")
      .json(&serde_json::json!({
        "ref": format!("refs/heads/{}", branch_name),
        "sha": commit_sha
      }))
      .send()
      .await?;
    if !branch_res.status().is_success() {
      anyhow::bail!("Failed to create branch: {:?}", branch_res.text().await?);
    }
  }

  // 7. Create Pull Request
  tracing::info!("Opening Pull Request on nosebit/simian-papers...");
  let pr_res = auth_client
    .post("https://api.github.com/repos/nosebit/simian-papers/pulls")
    .json(&serde_json::json!({
      "title": format!("Publish Paper: {}", title_text),
      "head": branch_name,
      "base": "main",
      "body": format!(
        "Automatic submission of paper `{slug}` via Simian CLI.\n\n### 📄 Preview\n[Click here to preview the rendered paper](https://raw.githack.com/nosebit/simian-papers/{branch_name}/published/{slug}/index.html)",
        slug = slug,
        branch_name = branch_name
      )
    }))
    .send()
    .await?;

  if pr_res.status().is_success() {
    let pr_json: serde_json::Value = pr_res.json().await?;
    if let Some(url) = pr_json.get("html_url").and_then(|u| u.as_str()) {
      tracing::info!("Successfully opened Pull Request: {}", url);
      let _ = open::that(url);
    }
  } else if pr_res.status() == reqwest::StatusCode::UNPROCESSABLE_ENTITY {
    let text = pr_res.text().await?;
    if text.contains("A pull request already exists") {
      tracing::info!("✅ Successfully updated your existing Pull Request!");
    } else {
      anyhow::bail!("Failed to open PR: {:?}", text);
    }
  } else {
    anyhow::bail!("Failed to open PR: {:?}", pr_res.text().await?);
  }

  if id != slug {
    tracing::info!(
      "Note: You can open this paper locally using either `{}` or `{}`.",
      id,
      slug
    );
  }

  Ok(())
}