Skip to main content

shunt/
cli.rs

1use anyhow::{bail, Context as _, Result};
2use clap::{Parser, Subcommand};
3use std::path::PathBuf;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use crate::config::{config_path, config_template, credentials_path, log_path, pid_path, CredentialsStore};
7use crate::credential::Credential;
8use crate::oauth::{read_claude_credentials, refresh_token, revoke_token, run_oauth_flow};
9use crate::term::{self, bold, bold_white, brand_green, cyan, dark_green, dim, green, green_bold, red, yellow, CHECK, CROSS, DIAMOND, DOT, EMPTY};
10
11#[derive(Parser)]
12#[command(name = "shunt", about = "Local Claude Code account-pooling proxy", version)]
13struct Cli {
14    #[command(subcommand)]
15    command: Command,
16}
17
18#[derive(Subcommand)]
19enum Command {
20    /// Interactive setup — auto-imports your existing Claude Code session
21    Setup {
22        #[arg(long)]
23        config: Option<PathBuf>,
24    },
25    /// Start the proxy (runs setup first if not configured)
26    Start {
27        #[arg(long)]
28        config: Option<PathBuf>,
29        #[arg(long)]
30        host: Option<String>,
31        #[arg(long)]
32        port: Option<u16>,
33        /// Keep the process in the foreground instead of daemonizing
34        #[arg(long)]
35        foreground: bool,
36        /// Enable debug-level logging (shows routing decisions and token refresh details)
37        #[arg(long)]
38        verbose: bool,
39        /// Internal: running as background daemon (do not use directly)
40        #[arg(long, hide = true)]
41        daemon: bool,
42    },
43    /// Stop the running proxy daemon
44    Stop,
45    /// Restart the proxy daemon (stop then start)
46    Restart {
47        #[arg(long)]
48        config: Option<PathBuf>,
49    },
50    /// Print current config and proxy status
51    Status {
52        #[arg(long)]
53        config: Option<PathBuf>,
54    },
55    /// Tail the proxy log file
56    ///
57    /// Examples:
58    ///   shunt logs           — last 50 lines (pretty-printed)
59    ///   shunt logs -f        — follow in real time
60    ///   shunt logs -n 100    — last 100 lines
61    ///   shunt logs --json    — raw JSON output
62    Logs {
63        #[arg(long)]
64        config: Option<PathBuf>,
65        /// Follow log output in real time (like tail -f)
66        #[arg(short, long)]
67        follow: bool,
68        /// Number of lines to show
69        #[arg(short = 'n', long, default_value = "50")]
70        lines: usize,
71        /// Raw JSON output instead of pretty-printed
72        #[arg(long)]
73        json: bool,
74    },
75    /// Manage accounts — add, remove, or log out (interactive menu)
76    Config {
77        #[arg(long)]
78        config: Option<PathBuf>,
79    },
80    /// Import the current Claude Code session as an additional account
81    #[command(hide = true)]
82    AddAccount {
83        #[arg(long)]
84        config: Option<PathBuf>,
85        /// Name for this account (e.g. "secondary", "work"). Prompted if omitted.
86        name: Option<String>,
87        /// Provider: "anthropic" or "openai". Prompted interactively if omitted.
88        #[arg(long)]
89        provider: Option<String>,
90    },
91    /// Remove an account from the pool
92    #[command(hide = true)]
93    RemoveAccount {
94        #[arg(long)]
95        config: Option<PathBuf>,
96        /// Name of the account to remove (omit to pick interactively)
97        name: Option<String>,
98    },
99    /// Enable remote access — expose the proxy to other devices
100    ///
101    /// With no arguments: interactive menu to choose sharing mode (LAN, tunnel, custom domain).
102    /// With a share code: connect this device to a remote shunt instance.
103    ///
104    /// Examples:
105    ///   shunt share                    — host: choose sharing mode
106    ///   shunt share SC-a3f2b1c4d5e6f7a8b9  — guest: connect with a share code
107    Share {
108        #[arg(long)]
109        config: Option<PathBuf>,
110        /// Create a public tunnel via Cloudflare (works over any network, not just LAN)
111        #[arg(long)]
112        tunnel: bool,
113        /// Disable remote access and revert to localhost-only
114        #[arg(long)]
115        stop: bool,
116        /// Share code from `shunt share` on the host — connects this device to a remote shunt
117        code: Option<String>,
118    },
119    /// Log out of an account — clears stored credentials (keeps account in config)
120    #[command(hide = true)]
121    Logout {
122        #[arg(long)]
123        config: Option<PathBuf>,
124        /// Account name to log out. Omit to pick interactively.
125        name: Option<String>,
126        /// Log out all accounts at once
127        #[arg(long)]
128        all: bool,
129    },
130    /// Live fullscreen TUI dashboard — shows account utilization and request log
131    Monitor {
132        #[arg(long)]
133        config: Option<PathBuf>,
134    },
135    /// Connect this device to a remote shunt instance (alias: shunt share <code>)
136    #[command(hide = true)]
137    Connect {
138        /// Share code printed by `shunt share` on the host
139        code: String,
140    },
141    /// Disconnect from a remote shunt instance
142    ///
143    /// Removes ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY written by `shunt connect`
144    /// from your shell profile and ~/.claude/settings.json.
145    ///
146    /// Examples:
147    ///   shunt disconnect
148    Disconnect,
149    /// Update shunt to the latest release
150    Update,
151    /// Completely remove shunt — stops service, deletes config, removes binary
152    Uninstall,
153    /// Manage shunt as a system service (auto-start on login)
154    ///
155    /// Examples:
156    ///   shunt service install    — register + start (called by install.sh)
157    ///   shunt service uninstall  — stop + remove
158    ///   shunt service status     — is service registered/running?
159    Service {
160        #[command(subcommand)]
161        action: ServiceAction,
162    },
163    /// Pin routing to a specific account, or restore automatic routing
164    ///
165    /// Examples:
166    ///   shunt use            — interactive picker
167    ///   shunt use work       — force all requests through 'work'
168    ///   shunt use auto       — restore automatic least-utilization routing
169    Use {
170        #[arg(long)]
171        config: Option<PathBuf>,
172        /// Account name to pin to, or "auto". Omit to pick interactively.
173        account: Option<String>,
174    },
175    /// Print a sanitized debug report for sharing when reporting issues
176    Report {
177        #[arg(long)]
178        config: Option<PathBuf>,
179    },
180    /// Override the model for all requests, or clear the override
181    ///
182    /// Examples:
183    ///   shunt model                           — show current model override
184    ///   shunt model set claude-opus-4-6       — force all requests to use this model
185    ///   shunt model clear                     — restore client-supplied model
186    Model {
187        #[arg(long)]
188        config: Option<PathBuf>,
189        #[command(subcommand)]
190        action: Option<ModelAction>,
191    },
192    /// Override the routing strategy at runtime, or clear the override
193    ///
194    /// Examples:
195    ///   shunt strategy                — show current strategy + source
196    ///   shunt strategy set reaper     — drain expiring accounts first
197    ///   shunt strategy set maximus    — time-weighted dual-window scorer (default)
198    ///   shunt strategy clear          — restore config-file strategy
199    Strategy {
200        #[arg(long)]
201        config: Option<PathBuf>,
202        #[command(subcommand)]
203        action: Option<StrategyAction>,
204    },
205    /// Set the per-account burst rate limit, or clear the override
206    ///
207    /// Examples:
208    ///   shunt burst-limit              — show current limit
209    ///   shunt burst-limit set 12       — max 12 requests/min per account
210    ///   shunt burst-limit set 0        — disable burst pacing
211    ///   shunt burst-limit clear        — restore default (10/min)
212    BurstLimit {
213        #[arg(long)]
214        config: Option<PathBuf>,
215        #[command(subcommand)]
216        action: Option<BurstLimitAction>,
217    },
218    /// Set the fallback model for when all accounts are on cooldown
219    ///
220    /// Examples:
221    ///   shunt fallback                 — show current fallback (auto by default)
222    ///   shunt fallback set sonnet      — always fall back to sonnet
223    ///   shunt fallback off             — disable fallback entirely
224    ///   shunt fallback clear           — restore auto-detection
225    Fallback {
226        #[arg(long)]
227        config: Option<PathBuf>,
228        #[command(subcommand)]
229        action: Option<FallbackAction>,
230    },
231    /// Set the effort level for all proxied requests
232    ///
233    /// Controls reasoning depth via output_config.effort.
234    /// Default is passthrough (don't modify client requests).
235    ///
236    /// Examples:
237    ///   shunt effort              — show current effort override
238    ///   shunt effort set xhigh    — enable multi-agent / ultracode mode
239    ///   shunt effort set max      — override to maximum reasoning
240    ///   shunt effort set low      — override to fast & cheap
241    ///   shunt effort clear        — restore passthrough (don't modify)
242    Effort {
243        #[arg(long)]
244        config: Option<PathBuf>,
245        #[command(subcommand)]
246        action: Option<EffortAction>,
247    },
248    /// Set the thinking mode for all proxied requests
249    ///
250    /// Controls extended thinking via the thinking parameter.
251    /// Default is passthrough (don't modify client requests).
252    ///
253    /// Examples:
254    ///   shunt thinking               — show current thinking override
255    ///   shunt thinking set adaptive  — force adaptive thinking on all requests
256    ///   shunt thinking set off       — disable thinking on all requests
257    ///   shunt thinking clear         — restore passthrough (don't modify)
258    Thinking {
259        #[arg(long)]
260        config: Option<PathBuf>,
261        #[command(subcommand)]
262        action: Option<ThinkingAction>,
263    },
264    /// Mute or unmute daemon alert notifications
265    ///
266    /// Examples:
267    ///   shunt alerts           — show current mute state
268    ///   shunt alerts mute      — suppress rate-limit / auth-failure notifications
269    ///   shunt alerts unmute    — re-enable notifications
270    Alerts {
271        #[arg(long)]
272        config: Option<PathBuf>,
273        #[command(subcommand)]
274        action: Option<AlertsAction>,
275    },
276    /// Show how much you've saved vs paying for the Claude API
277    ///
278    /// Tracks cumulative token usage and computes what it would have cost
279    /// at public Claude API list prices.
280    ///
281    /// Examples:
282    ///   shunt savings        — show today / this week / all-time savings
283    Savings {
284        #[arg(long)]
285        config: Option<PathBuf>,
286    },
287    /// Open a persistent tunnel to the relay (your proxy becomes reachable at subdomain.domain)
288    ///
289    /// Examples:
290    ///   shunt live                       — tunnel using config defaults
291    ///   shunt live --subdomain shunt     — register as shunt.ramcharan.shop
292    Live {
293        #[arg(long)]
294        config: Option<PathBuf>,
295        /// Subdomain to register (e.g. "shunt" → shunt.ramcharan.shop)
296        #[arg(long)]
297        subdomain: Option<String>,
298        /// Override relay WebSocket URL
299        #[arg(long)]
300        relay: Option<String>,
301    },
302    /// Run the tunnel relay server (deploy on your VPS)
303    ///
304    /// Examples:
305    ///   shunt relay serve                — start on default port 8085
306    ///   shunt relay serve --port 9000    — custom port
307    Relay {
308        #[command(subcommand)]
309        action: RelayAction,
310    },
311}
312
313#[derive(Subcommand)]
314enum ServiceAction {
315    /// Register shunt as a login service and start it immediately
316    Install,
317    /// Stop and unregister the shunt login service
318    Uninstall,
319    /// Show whether the service is registered and running
320    Status,
321}
322
323#[derive(Subcommand)]
324enum ModelAction {
325    /// Force all requests through a specific model
326    Set {
327        /// Model name, e.g. claude-opus-4-6
328        model: String,
329    },
330    /// Clear the model override and let clients choose the model
331    Clear,
332}
333
334#[derive(Subcommand)]
335enum StrategyAction {
336    /// Override the routing strategy
337    Set {
338        /// Strategy name: maximus, reaper, carousel, cushion
339        strategy: String,
340    },
341    /// Clear the strategy override and fall back to config-file value
342    Clear,
343}
344
345#[derive(Subcommand)]
346enum BurstLimitAction {
347    /// Set per-account burst rate limit (requests per minute)
348    Set {
349        /// Limit value (0 = disable pacing)
350        limit: u32,
351    },
352    /// Clear the override and restore default (10/min)
353    Clear,
354}
355
356#[derive(Subcommand)]
357enum FallbackAction {
358    /// Set an explicit fallback model
359    Set {
360        /// Model name, e.g. claude-sonnet-4-6
361        model: String,
362    },
363    /// Disable fallback entirely (wait for cooldown instead)
364    Off,
365    /// Clear the override and restore auto-detection
366    Clear,
367}
368
369#[derive(Subcommand)]
370enum EffortAction {
371    /// Set effort level (low, medium, high, xhigh, max)
372    Set {
373        /// Effort level: low, medium, high, xhigh (multi-agent/ultracode), or max
374        level: String,
375    },
376    /// Clear the override and restore passthrough
377    Clear,
378}
379
380#[derive(Subcommand)]
381enum ThinkingAction {
382    /// Set thinking mode (adaptive or off)
383    Set {
384        /// Thinking mode: adaptive or off
385        mode: String,
386    },
387    /// Clear the override and restore passthrough
388    Clear,
389}
390
391#[derive(Subcommand)]
392enum AlertsAction {
393    /// Suppress all daemon alert notifications
394    Mute,
395    /// Re-enable daemon alert notifications
396    Unmute,
397}
398
399#[derive(Subcommand)]
400enum RelayAction {
401    /// Start the relay server
402    Serve {
403        /// Port to listen on
404        #[arg(long, default_value = "8085")]
405        port: u16,
406    },
407}
408
409pub async fn run() -> Result<()> {
410    // Intercept --version / -V before clap to show branded banner
411    let args: Vec<String> = std::env::args().collect();
412    if args.len() == 2 && (args[1] == "--version" || args[1] == "-V") {
413        print_splash(&[
414            format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
415            String::new(),
416            String::new(),
417        ]);
418        return Ok(());
419    }
420
421    let cli = Cli::parse();
422    match cli.command {
423        Command::Setup { config } => cmd_setup(config).await,
424        Command::Start { config, host, port, foreground, verbose, daemon } => cmd_start(config, host, port, foreground, verbose, daemon).await,
425        Command::Stop => cmd_stop().await,
426        Command::Restart { config } => cmd_restart(config).await,
427        Command::Status { config } => cmd_status(config).await,
428        Command::Logs { config, follow, lines, json } => cmd_logs(config, follow, lines, json).await,
429        Command::Config { config } => cmd_config(config).await,
430        Command::AddAccount { config, name, provider } => cmd_add_account(config, name, provider.as_deref()).await,
431        Command::RemoveAccount { config, name } => cmd_remove_account(config, name).await,
432        Command::Logout { config, name, all } => cmd_logout(config, name, all).await,
433        Command::Monitor { config } => cmd_monitor(config).await,
434        Command::Connect { code } => cmd_connect(code).await,
435        Command::Disconnect => cmd_disconnect().await,
436        Command::Update => cmd_update().await,
437        Command::Share { config, tunnel, stop, code } => {
438            if let Some(code) = code {
439                cmd_connect(code).await
440            } else {
441                cmd_share(config, tunnel, stop).await
442            }
443        }
444        Command::Uninstall => cmd_uninstall().await,
445        Command::Use { config, account } => cmd_use(config, account).await,
446        Command::Report { config } => cmd_report(config).await,
447        Command::Model { config, action } => cmd_model(config, action).await,
448        Command::Strategy { config, action } => cmd_strategy(config, action).await,
449        Command::BurstLimit { config, action } => cmd_burst_limit(config, action).await,
450        Command::Fallback { config, action } => cmd_fallback(config, action).await,
451        Command::Effort { config, action } => cmd_effort(config, action).await,
452        Command::Thinking { config, action } => cmd_thinking(config, action).await,
453        Command::Alerts { config, action } => cmd_alerts(config, action).await,
454        Command::Savings { config } => cmd_savings(config).await,
455        Command::Live { config, subdomain, relay } => cmd_live(config, subdomain, relay).await,
456        Command::Relay { action } => match action {
457            RelayAction::Serve { port } => cmd_relay_serve(port).await,
458        },
459        Command::Service { action } => match action {
460            ServiceAction::Install   => cmd_service_install().await,
461            ServiceAction::Uninstall => cmd_service_uninstall().await,
462            ServiceAction::Status    => cmd_service_status().await,
463        },
464    }
465}
466
467// ---------------------------------------------------------------------------
468// setup
469// ---------------------------------------------------------------------------
470
471pub async fn cmd_setup(config_override: Option<PathBuf>) -> Result<()> {
472    let config_p = config_override.clone().unwrap_or_else(config_path);
473
474    print_splash(&[
475        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
476        dim("Setup"),
477        String::new(),
478    ]);
479
480    if config_p.exists() {
481        println!("  {} Already configured.", green(CHECK));
482        println!("  {} Use {} to add more accounts.", dim("·"), cyan("shunt add-account"));
483        // Ensure settings.json is pointing at the local proxy even if setup ran
484        // before this feature was added (e.g. after an update).
485        let port = crate::config::load_config(config_override.as_deref())
486            .map(|c| c.server.port)
487            .unwrap_or(8082);
488        write_local_claude_settings(port);          // verbose: prints what it wrote
489        apply_local_routing_silent(port);           // also writes managed_settings (silent, skips if correct)
490        println!();
491        return Ok(());
492    }
493
494    // Auto-detect existing Claude Code session — no user action needed
495    let cred = match read_claude_credentials() {
496        Some(mut c) => {
497            if c.needs_refresh() {
498                print!("  {} Token expired, refreshing… ", yellow("↻"));
499                use std::io::Write;
500                std::io::stdout().flush().ok();
501                match refresh_token(&c).await {
502                    Ok(fresh) => { println!("{}", green("done")); c = fresh; }
503                    Err(_) => {
504                        // Refresh token is also invalid — run a fresh OAuth flow
505                        // so setup completes with a working credential.
506                        println!("{}", yellow("failed"));
507                        println!("  {} Session fully expired — opening browser for fresh login…", dim("·"));
508                        println!();
509                        c = run_oauth_flow().await?;
510                    }
511                }
512            } else {
513                println!("  {} Claude Code session found", green(CHECK));
514            }
515            c
516        }
517        None => {
518            // No local Claude Code session — run OAuth directly so setup is self-contained.
519            println!("  {} No existing Claude Code session found — opening browser for login…", dim("·"));
520            println!();
521            run_oauth_flow().await?
522        }
523    };
524
525    let plan = crate::oauth::read_claude_session_info()
526        .map(|s| s.plan)
527        .unwrap_or_else(|| "pro".to_string());
528    println!("  {} Plan: {}", green(CHECK), bold(&plan));
529
530    // Fetch account email (non-fatal)
531    let email = crate::oauth::fetch_account_email(&cred.access_token).await;
532    if let Some(ref e) = email {
533        println!("  {} Account: {}", green(CHECK), bold(e));
534    }
535    let mut cred = cred;
536    cred.email = email;
537
538    // Write config
539    if let Some(parent) = config_p.parent() {
540        std::fs::create_dir_all(parent)?;
541    }
542    std::fs::write(&config_p, config_template(&[("main", &plan)]))?;
543    #[cfg(unix)]
544    {
545        use std::os::unix::fs::PermissionsExt;
546        std::fs::set_permissions(&config_p, std::fs::Permissions::from_mode(0o600))?;
547    }
548
549    // Store credential
550    let mut store = CredentialsStore::default();
551    store.accounts.insert("main".into(), Credential::Oauth(cred));
552    store.save()?;
553
554    // Derive port from the config we just wrote (always 8082 from template, but be explicit).
555    let setup_port = crate::config::load_config(config_override.as_deref())
556        .map(|c| c.server.port)
557        .unwrap_or(8082);
558
559    println!();
560    println!("  {} Config      {}", green("→"), dim(&config_p.display().to_string()));
561    println!("  {} Credentials {}", green("→"), dim(&credentials_path().display().to_string()));
562
563    // Write ANTHROPIC_BASE_URL to ~/.claude/settings.json so Claude Code picks up
564    // the proxy immediately — no shell restart required.
565    write_local_claude_settings(setup_port);
566
567    // For non-Claude-Code tools (curl, Python SDK, etc.) that read the env var.
568    offer_shell_export(setup_port)?;
569
570    println!();
571    println!("  {} Run {} to start.", green(CHECK), cyan("shunt start"));
572    println!("  {} Then restart any open Claude Code windows.", dim("·"));
573
574    Ok(())
575}
576
577// ---------------------------------------------------------------------------
578// config  (unified account management)
579// ---------------------------------------------------------------------------
580
581async fn cmd_config(config_override: Option<PathBuf>) -> Result<()> {
582    let config_p = config_override.clone().unwrap_or_else(config_path);
583    if !config_p.exists() {
584        bail!("No config found. Run `shunt setup` first.");
585    }
586
587    let items = vec![
588        term::SelectItem { label: format!("{}  {}", bold("Add account"),     dim("connect a new account to the pool")),        value: "add".into() },
589        term::SelectItem { label: format!("{}  {}", bold("Manage accounts"), dim("reauth, update config, or fix issues")),     value: "manage".into() },
590        term::SelectItem { label: format!("{}  {}", bold("Remove account"),  dim("delete an account from the pool")),          value: "remove".into() },
591        term::SelectItem { label: format!("{}  {}", bold("Log out"),         dim("clear credentials for an account")),         value: "logout".into() },
592    ];
593
594    println!();
595    match term::select("Account management", &items, 0) {
596        Some(v) if v == "add"    => cmd_add_account(config_override, None, None).await,
597        Some(v) if v == "manage" => cmd_manage_account(config_override).await,
598        Some(v) if v == "remove" => cmd_remove_account(config_override, None).await,
599        Some(v) if v == "logout" => cmd_logout(config_override, None, false).await,
600        _ => Ok(()),
601    }
602}
603
604// ---------------------------------------------------------------------------
605// manage-account  (per-account edit / reauth)
606// ---------------------------------------------------------------------------
607
608async fn cmd_manage_account(config_override: Option<PathBuf>) -> Result<()> {
609    use crate::provider::AuthKind;
610
611    let config = crate::config::load_config(config_override.as_deref())?;
612    if config.accounts.is_empty() {
613        bail!("No accounts configured. Run `shunt config` → Add account.");
614    }
615
616    // ── Step 1: pick account ─────────────────────────────────────────────────
617    let items: Vec<term::SelectItem> = config.accounts.iter().map(|a| {
618        let tag = match a.provider.auth_kind() {
619            AuthKind::OAuth  => {
620                let ok = a.credential.as_ref().map(|c| !c.needs_refresh()).unwrap_or(false);
621                if ok { dim("  oauth  ✓") } else { yellow("  oauth  !") }
622            }
623            AuthKind::ApiKey => dim("  api-key"),
624            AuthKind::None   => dim("  local"),
625        };
626        term::SelectItem {
627            label: format!("{}  {}{}", bold(&pad(&a.name, 14)), dim(&pad(a.credential.as_ref().and_then(|c| c.email()).unwrap_or(""), 32)), tag),
628            value: a.name.clone(),
629        }
630    }).collect();
631
632    println!();
633    let name = match term::select("Which account?", &items, 0) {
634        Some(v) => v,
635        None => return Ok(()),
636    };
637
638    let account = config.accounts.iter().find(|a| a.name == name).unwrap();
639    let provider = account.provider.clone();
640
641    // ── Step 2: pick action ──────────────────────────────────────────────────
642    let mut actions: Vec<term::SelectItem> = Vec::new();
643    match provider.auth_kind() {
644        AuthKind::OAuth => {
645            actions.push(term::SelectItem { label: format!("{}  {}", bold("Re-authenticate"), dim("start a new OAuth session")),          value: "reauth".into() });
646            actions.push(term::SelectItem { label: format!("{}  {}", bold("Log out"),         dim("clear stored credentials")),            value: "logout".into() });
647        }
648        AuthKind::ApiKey => {
649            actions.push(term::SelectItem { label: format!("{}  {}", bold("Update API key"),  dim("replace stored key")),                  value: "apikey".into() });
650        }
651        AuthKind::None => {
652            actions.push(term::SelectItem { label: format!("{}  {}", bold("Update upstream URL"), dim("change the local endpoint")),       value: "upstream".into() });
653            actions.push(term::SelectItem { label: format!("{}  {}", bold("Update model"),        dim("set default model for this account")), value: "model".into() });
654        }
655    }
656    actions.push(term::SelectItem { label: format!("{}  {}", bold("Remove account"), dim("delete from pool permanently")),                value: "remove".into() });
657
658    println!();
659    let action = match term::select(&format!("Manage  '{name}'"), &actions, 0) {
660        Some(v) => v,
661        None => return Ok(()),
662    };
663
664    println!();
665
666    match action.as_str() {
667        // ── Re-authenticate (OAuth) ──────────────────────────────────────────
668        "reauth" => {
669            print_splash(&[
670                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
671                format!("Re-authenticating  '{name}'"),
672                String::new(),
673            ]);
674            use crate::oauth::{run_oauth_flow, run_openai_oauth_flow, fetch_account_email, fetch_openai_account_email};
675            use crate::provider::Provider;
676            let mut cred = match provider {
677                Provider::Anthropic => run_oauth_flow().await?,
678                Provider::OpenAI    => run_openai_oauth_flow().await?,
679                _ => unreachable!(),
680            };
681            let email = match provider {
682                Provider::Anthropic => fetch_account_email(&cred.access_token).await,
683                Provider::OpenAI    => fetch_openai_account_email(&cred.access_token).await,
684                _ => None,
685            };
686            if let Some(ref e) = email { println!("  {} Signed in as {}", green(CHECK), bold(e)); }
687            cred.email = email;
688            if cred.id_token.is_some() { crate::oauth::write_codex_auth_file(&cred); }
689            // Clear auth_failed state
690            let state_p = crate::config::state_path();
691            let state = crate::state::StateStore::load(&state_p);
692            state.clear_auth_failed(&name);
693            // Save credential
694            let mut store = CredentialsStore::load();
695            store.accounts.insert(name.clone(), Credential::Oauth(cred));
696            store.save()?;
697            println!();
698            println!("  {} Account '{}' re-authenticated.", green(CHECK), bold(&name));
699            offer_restart(config_override).await;
700        }
701
702        // ── Update API key ───────────────────────────────────────────────────
703        "apikey" => {
704            let env_hint = provider.api_key_env_var()
705                .map(|v| format!(" (or set {} in your environment)", v))
706                .unwrap_or_default();
707            print!("  {} New API key{}: ", dim("·"), dim(&env_hint));
708            use std::io::Write; std::io::stdout().flush().ok();
709            let key = read_secret_line()?;
710            if key.is_empty() { bail!("API key cannot be empty."); }
711            let mut store = CredentialsStore::load();
712            store.accounts.insert(name.clone(), Credential::Apikey { key });
713            store.save()?;
714            // Clear any auth_failed state
715            let state_p = crate::config::state_path();
716            let state = crate::state::StateStore::load(&state_p);
717            state.clear_auth_failed(&name);
718            println!("  {} API key updated for '{}'.", green(CHECK), bold(&name));
719            offer_restart(config_override).await;
720        }
721
722        // ── Update upstream URL (Local) ──────────────────────────────────────
723        "upstream" => {
724            let current = account.upstream_url.as_deref().unwrap_or("(not set)");
725            print!("  {} Upstream URL [{}]: ", dim("·"), dim(current));
726            use std::io::{BufRead, Write}; std::io::stdout().flush().ok();
727            let mut input = String::new();
728            std::io::stdin().lock().read_line(&mut input)?;
729            let url = input.trim().to_string();
730            if url.is_empty() { bail!("URL cannot be empty."); }
731            update_account_toml_field(config_override.as_deref(), &name, "upstream_url", &url)?;
732            println!("  {} Upstream URL updated for '{}'.", green(CHECK), bold(&name));
733            offer_restart(config_override).await;
734        }
735
736        // ── Update model (Local / any) ───────────────────────────────────────
737        "model" => {
738            let current = account.model.as_deref().unwrap_or("(not set)");
739            print!("  {} Model [{}]: ", dim("·"), dim(current));
740            use std::io::{BufRead, Write}; std::io::stdout().flush().ok();
741            let mut input = String::new();
742            std::io::stdin().lock().read_line(&mut input)?;
743            let model = input.trim().to_string();
744            if model.is_empty() { bail!("Model cannot be empty."); }
745            update_account_toml_field(config_override.as_deref(), &name, "model", &model)?;
746            println!("  {} Model updated for '{}'.", green(CHECK), bold(&name));
747            offer_restart(config_override).await;
748        }
749
750        // ── Log out (OAuth) ──────────────────────────────────────────────────
751        "logout" => {
752            return cmd_logout(config_override, Some(name), false).await;
753        }
754
755        // ── Remove account ───────────────────────────────────────────────────
756        "remove" => {
757            return cmd_remove_account(config_override, Some(name)).await;
758        }
759
760        _ => {}
761    }
762
763    println!();
764    Ok(())
765}
766
767/// Update a single string field inside the `[[accounts]]` block for `account_name`
768/// in the TOML config file (using toml_edit for safe structured editing).
769fn update_account_toml_field(config_override: Option<&std::path::Path>, account_name: &str, field: &str, value: &str) -> Result<()> {
770    let config_p = config_override.map(|p| p.to_path_buf()).unwrap_or_else(config_path);
771    let text = std::fs::read_to_string(&config_p)?;
772    let mut doc = text.parse::<toml_edit::DocumentMut>()
773        .context("Failed to parse config TOML")?;
774    if let Some(item) = doc.get_mut("accounts") {
775        if let Some(arr) = item.as_array_of_tables_mut() {
776            for table in arr.iter_mut() {
777                if table.get("name").and_then(|v| v.as_str()) == Some(account_name) {
778                    table.insert(field, toml_edit::value(value));
779                }
780            }
781        }
782    }
783    std::fs::write(&config_p, doc.to_string())?;
784    Ok(())
785}
786
787// ---------------------------------------------------------------------------
788// add-account
789// ---------------------------------------------------------------------------
790
791async fn cmd_add_account(
792    config_override: Option<PathBuf>,
793    name_arg: Option<String>,
794    provider_arg: Option<&str>,
795) -> Result<()> {
796    use crate::provider::Provider;
797
798    let config_p = config_override.clone().unwrap_or_else(config_path);
799    if !config_p.exists() {
800        bail!("No config found. Run `shunt setup` first.");
801    }
802
803    print_splash(&[
804        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
805        "Add account".to_string(),
806        String::new(),
807    ]);
808
809    // ── Step 1: choose provider ──────────────────────────────────────────────
810    let provider = if let Some(p) = provider_arg {
811        Provider::from_str(p)
812    } else {
813        let items = vec![
814            term::SelectItem { label: format!("{}  {}", bold("Claude Code"), dim("(claude.ai — Anthropic)")), value: "anthropic".into() },
815            term::SelectItem { label: format!("{}  {}  {}", bold("Codex"), yellow("[beta]"), dim("(chatgpt.com — OpenAI)")), value: "openai".into() },
816            term::SelectItem { label: format!("{}  {}", bold("Groq"),        dim("(api.groq.com — API key)")),               value: "groq".into() },
817            term::SelectItem { label: format!("{}  {}", bold("Mistral"),     dim("(api.mistral.ai — API key)")),             value: "mistral".into() },
818            term::SelectItem { label: format!("{}  {}", bold("Together AI"), dim("(api.together.xyz — API key)")),           value: "together".into() },
819            term::SelectItem { label: format!("{}  {}", bold("OpenRouter"),  dim("(openrouter.ai — API key)")),              value: "openrouter".into() },
820            term::SelectItem { label: format!("{}  {}", bold("DeepSeek"),    dim("(api.deepseek.com — API key)")),           value: "deepseek".into() },
821            term::SelectItem { label: format!("{}  {}", bold("Fireworks"),   dim("(api.fireworks.ai — API key)")),           value: "fireworks".into() },
822            term::SelectItem { label: format!("{}  {}", bold("Gemini"),      dim("(generativelanguage.googleapis.com — API key)")), value: "gemini".into() },
823            term::SelectItem { label: format!("{}  {}", bold("OpenAI API"),  dim("(api.openai.com — API key)")),             value: "openai-api".into() },
824            term::SelectItem { label: format!("{}  {}", bold("Local"),       dim("(Ollama, LM Studio, etc. — no auth)")),   value: "local".into() },
825        ];
826        match term::select("Which provider?", &items, 0) {
827            Some(v) => Provider::from_str(&v),
828            None => return Ok(()),
829        }
830    };
831
832    println!();
833
834    // ── Step 2: choose name ──────────────────────────────────────────────────
835    let existing_config = std::fs::read_to_string(&config_p)?;
836    let store = CredentialsStore::load();
837
838    let (name, already_in_config) = if let Some(n) = name_arg {
839        let in_config = existing_config.contains(&format!("name = \"{n}\""));
840        let has_cred  = store.accounts.contains_key(&n);
841        let is_expired = store.accounts.get(&n).map(|c| c.needs_refresh()).unwrap_or(false);
842        let is_auth_failed = crate::state::StateStore::load(&crate::config::state_path())
843            .account_states().get(&n).map(|s| s.auth_failed).unwrap_or(false);
844        if in_config && has_cred && !is_expired && !is_auth_failed {
845            bail!("Account '{}' already has a valid credential.", n);
846        }
847        (n, in_config)
848    } else {
849        use crate::provider::AuthKind;
850        // For OAuth providers: offer to re-auth existing uncredentialed accounts.
851        // For API-key / Local: always prompt for a new name (credentials don't expire the same way).
852        let missing_oauth: Vec<_> = if provider.auth_kind() == AuthKind::OAuth {
853            let config = crate::config::load_config(config_override.as_deref())?;
854            config.accounts.iter()
855                .filter(|a| a.provider == provider && a.credential.is_none())
856                .map(|a| a.name.clone())
857                .collect()
858        } else {
859            vec![]
860        };
861
862        match missing_oauth.len() {
863            1 => {
864                println!("  {} Authorizing account {}", yellow("↻"), bold(&format!("'{}'", missing_oauth[0])));
865                println!();
866                (missing_oauth[0].clone(), true)
867            }
868            n if n > 1 => {
869                let items: Vec<term::SelectItem> = missing_oauth.iter().map(|a| term::SelectItem {
870                    label: bold(a).to_string(),
871                    value: a.clone(),
872                }).collect();
873                match term::select("Which account to authorize?", &items, 0) {
874                    Some(v) => (v, true),
875                    None => return Ok(()),
876                }
877            }
878            _ => {
879                // Prompt for a new name
880                let hint = format!("({} account name, e.g. \"{}\")", provider, provider.to_string().to_lowercase().replace(' ', "-"));
881                print!("  {} Account name {}: ", dim("·"), dim(&hint));
882                use std::io::Write;
883                std::io::stdout().flush().ok();
884                let mut input = String::new();
885                std::io::stdin().read_line(&mut input)?;
886                let n = input.trim().to_string();
887                if n.is_empty() { bail!("Account name cannot be empty."); }
888                (n, false)
889            }
890        }
891    };
892
893    // ── Step 3: authenticate ─────────────────────────────────────────────────
894    use crate::provider::AuthKind;
895    let credential: Option<Credential> = match provider.auth_kind() {
896        AuthKind::OAuth => {
897            let mut cred = match provider {
898                Provider::Anthropic => run_oauth_flow().await?,
899                Provider::OpenAI    => crate::oauth::run_openai_oauth_flow().await?,
900                _ => unreachable!(),
901            };
902            // Fetch email (non-fatal)
903            let email = match provider {
904                Provider::Anthropic => crate::oauth::fetch_account_email(&cred.access_token).await,
905                Provider::OpenAI    => crate::oauth::fetch_openai_account_email(&cred.access_token).await,
906                _ => None,
907            };
908            if let Some(ref e) = email {
909                println!("  {} Signed in as {}", green(CHECK), bold(e));
910            }
911            cred.email = email;
912            // Keep ~/.codex/auth.json in sync so the Codex CLI works without re-login.
913            if cred.id_token.is_some() {
914                crate::oauth::write_codex_auth_file(&cred);
915            }
916            Some(Credential::Oauth(cred))
917        }
918        AuthKind::ApiKey => {
919            // Show env-var hint if available
920            let env_hint = provider.api_key_env_var()
921                .map(|v| format!(" (or set {} in your environment)", v))
922                .unwrap_or_default();
923            print!("  {} API key{}: ", dim("·"), dim(&env_hint));
924            use std::io::Write;
925            std::io::stdout().flush().ok();
926            // Read key — use rpassword for masked input if available, otherwise plain readline
927            let key = read_secret_line()?;
928            if key.is_empty() { bail!("API key cannot be empty."); }
929            println!("  {} API key saved.", green(CHECK));
930            Some(Credential::Apikey { key })
931        }
932        AuthKind::None => {
933            // Local provider — no credential needed, but we may need upstream_url
934            None
935        }
936    };
937
938    // For Local provider, prompt for upstream URL
939    let upstream_url: Option<String> = if matches!(provider, Provider::Local) {
940        print!("  {} Upstream URL (e.g. http://localhost:11434): ", dim("·"));
941        use std::io::Write;
942        std::io::stdout().flush().ok();
943        let mut input = String::new();
944        std::io::stdin().read_line(&mut input)?;
945        let u = input.trim().to_string();
946        if u.is_empty() { bail!("Upstream URL cannot be empty for local provider."); }
947        Some(u)
948    } else {
949        None
950    };
951
952    // ── Step 4: persist ──────────────────────────────────────────────────────
953    if !already_in_config {
954        let mut config_text = existing_config;
955        let mut block = format!("\n[[accounts]]\nname = \"{name}\"\n");
956        if !matches!(provider, Provider::Anthropic) {
957            block.push_str(&format!("provider = \"{provider}\"\n"));
958        }
959        if let Some(ref url) = upstream_url {
960            block.push_str(&format!("upstream_url = \"{url}\"\n"));
961        }
962        config_text.push_str(&block);
963        std::fs::write(&config_p, &config_text)?;
964    }
965
966    if let Some(cred) = credential {
967        let mut store = CredentialsStore::load();
968        store.accounts.insert(name.clone(), cred);
969        store.save()?;
970    }
971
972    // Clear any persisted auth_failed / disabled flags so the proxy treats
973    // the fresh credential as healthy on next start (or hot-reload).
974    {
975        let state = crate::state::StateStore::load(&crate::config::state_path());
976        state.clear_auth_failed(&name);
977        // Give the background writer thread time to flush (~100 ms poll interval).
978        std::thread::sleep(std::time::Duration::from_millis(250));
979    }
980
981    println!();
982    println!("  {} Account {} added.", green(CHECK), bold(&format!("'{name}'")));
983    offer_restart(config_override).await;
984    println!();
985    Ok(())
986}
987
988/// Read a line from stdin without echoing (for API keys). Falls back to
989/// plain readline if the terminal doesn't support it.
990fn read_secret_line() -> Result<String> {
991    // Try rpassword-style: disable echo via termios, then restore.
992    #[cfg(unix)]
993    {
994        use std::io::{BufRead, Write};
995        // Disable echo
996        let _ = std::process::Command::new("stty").arg("-echo").status();
997        let mut out = std::io::stdout();
998        let _ = out.flush();
999        let stdin = std::io::stdin();
1000        let mut line = String::new();
1001        stdin.lock().read_line(&mut line)?;
1002        // Re-enable echo and print newline
1003        let _ = std::process::Command::new("stty").arg("echo").status();
1004        println!();
1005        return Ok(line.trim().to_string());
1006    }
1007    #[cfg(not(unix))]
1008    {
1009        use std::io::{BufRead, Write};
1010        let mut out = std::io::stdout();
1011        let _ = out.flush();
1012        let stdin = std::io::stdin();
1013        let mut line = String::new();
1014        stdin.lock().read_line(&mut line)?;
1015        return Ok(line.trim().to_string());
1016    }
1017}
1018
1019// ---------------------------------------------------------------------------
1020// remove-account
1021// ---------------------------------------------------------------------------
1022
1023async fn cmd_remove_account(config_override: Option<PathBuf>, name: Option<String>) -> Result<()> {
1024    let config_p = config_override.clone().unwrap_or_else(config_path);
1025    if !config_p.exists() {
1026        bail!("No config found. Run `shunt setup` first.");
1027    }
1028
1029    // Resolve name — pick interactively if not given
1030    let name = if let Some(n) = name {
1031        n
1032    } else {
1033        let config = crate::config::load_config(config_override.as_deref())?;
1034        let removable: Vec<_> = config.accounts.iter().collect();
1035        if removable.is_empty() {
1036            bail!("No accounts to remove.");
1037        }
1038        let items: Vec<term::SelectItem> = removable.iter().map(|a| {
1039            let email = a.credential.as_ref().and_then(|c| c.email()).unwrap_or("");
1040            term::SelectItem {
1041                label: format!("{}  {}", bold(&pad(&a.name, 12)), dim(&pad(email, 32))),
1042                value: a.name.clone(),
1043            }
1044        }).collect();
1045        match term::select("Remove account:", &items, 0) {
1046            Some(v) => v,
1047            None => return Ok(()),
1048        }
1049    };
1050
1051    let config_text = std::fs::read_to_string(&config_p)?;
1052    if !config_text.contains(&format!("name = \"{name}\"")) {
1053        bail!("Account '{name}' not found.");
1054    }
1055
1056    if !term::confirm(&format!("Remove account '{name}'? This cannot be undone.")) {
1057        println!("  {} Cancelled.", dim("·"));
1058        println!();
1059        return Ok(());
1060    }
1061
1062    print_splash(&[
1063        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
1064        format!("Removing account {}", bold(&format!("'{name}'"))),
1065        String::new(),
1066    ]);
1067
1068    // Strip the [[accounts]] block for this name from config
1069    let new_config = remove_account_block(&config_text, &name);
1070    std::fs::write(&config_p, &new_config)?;
1071    println!("  {} Removed from config", green(CHECK));
1072
1073    // Remove credential from store
1074    let mut store = CredentialsStore::load();
1075    if store.accounts.remove(&name).is_some() {
1076        store.save()?;
1077        println!("  {} Credential removed", green(CHECK));
1078    }
1079
1080    println!();
1081    println!("  {} Account {} removed.", green(CHECK), bold(&format!("'{name}'")));
1082    offer_restart(config_override).await;
1083    println!();
1084    Ok(())
1085}
1086
1087// ---------------------------------------------------------------------------
1088// logout
1089// ---------------------------------------------------------------------------
1090
1091async fn cmd_logout(config_override: Option<PathBuf>, name: Option<String>, all: bool) -> Result<()> {
1092    let config_p = config_override.clone().unwrap_or_else(config_path);
1093    if !config_p.exists() {
1094        bail!("No config found. Run `shunt setup` first.");
1095    }
1096
1097    let config = crate::config::load_config(config_override.as_deref())?;
1098
1099    // Collect account names to log out
1100    let names: Vec<String> = if all {
1101        config.accounts.iter()
1102            .filter(|a| a.credential.is_some())
1103            .map(|a| a.name.clone())
1104            .collect()
1105    } else if let Some(n) = name {
1106        if !config.accounts.iter().any(|a| a.name == n) {
1107            bail!("Account '{n}' not found.");
1108        }
1109        vec![n]
1110    } else {
1111        // Interactive picker — show only accounts that have credentials
1112        let with_cred: Vec<_> = config.accounts.iter()
1113            .filter(|a| a.credential.is_some())
1114            .collect();
1115        if with_cred.is_empty() {
1116            println!("  {} No logged-in accounts.", dim("·"));
1117            println!();
1118            return Ok(());
1119        }
1120        let items: Vec<term::SelectItem> = with_cred.iter().map(|a| {
1121            let email = a.credential.as_ref().and_then(|c| c.email()).unwrap_or("");
1122            term::SelectItem {
1123                label: format!("{}  {}", bold(&pad(&a.name, 12)), dim(&pad(email, 32))),
1124                value: a.name.clone(),
1125            }
1126        }).collect();
1127        match term::select("Log out account:", &items, 0) {
1128            Some(v) => vec![v],
1129            None => return Ok(()),
1130        }
1131    };
1132
1133    if names.is_empty() {
1134        println!("  {} No logged-in accounts.", dim("·"));
1135        println!();
1136        return Ok(());
1137    }
1138
1139    let label = if names.len() == 1 {
1140        format!("account {}", bold(&format!("'{}'", names[0])))
1141    } else {
1142        format!("{} accounts", bold(&names.len().to_string()))
1143    };
1144
1145    // Reconfirm for --all or multi-account logout
1146    if names.len() > 1 {
1147        if !term::confirm(&format!("Log out all {} accounts? You will need to re-authorize each one.", names.len())) {
1148            println!("  {} Cancelled.", dim("·"));
1149            println!();
1150            return Ok(());
1151        }
1152    }
1153
1154    print_splash(&[
1155        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
1156        format!("Logging out {label}"),
1157        String::new(),
1158    ]);
1159
1160    let mut store = CredentialsStore::load();
1161
1162    for name in &names {
1163        // Revoke token on the server (best-effort)
1164        if let Some(cred) = store.accounts.get(name) {
1165            print!("  {} Revoking '{}' token… ", dim("↻"), name);
1166            use std::io::Write;
1167            std::io::stdout().flush().ok();
1168            if revoke_token(cred.access_token()).await {
1169                println!("{}", green("done"));
1170            } else {
1171                println!("{}", dim("(server did not confirm — cleared locally)"));
1172            }
1173        }
1174
1175        // Remove credential from local store
1176        store.accounts.remove(name);
1177        println!("  {} Credential for '{}' removed", green(CHECK), name);
1178    }
1179
1180    store.save()?;
1181
1182    println!();
1183    println!("  {} Logged out {}.", green(CHECK), label);
1184    println!("  {} To re-authorize: {}", dim("·"), cyan("shunt add-account"));
1185    println!();
1186    Ok(())
1187}
1188
1189/// Remove a `[[accounts]]` TOML block with the given name from config text.
1190/// Uses toml_edit for correct structured editing that handles comments and edge cases.
1191fn remove_account_block(config: &str, name: &str) -> String {
1192    let mut doc = match config.parse::<toml_edit::DocumentMut>() {
1193        Ok(d) => d,
1194        Err(_) => return config.to_owned(), // unparseable — leave unchanged
1195    };
1196
1197    if let Some(item) = doc.get_mut("accounts") {
1198        if let Some(arr) = item.as_array_of_tables_mut() {
1199            // Collect indices to remove in reverse order so removal doesn't shift indices
1200            let to_remove: Vec<usize> = arr.iter()
1201                .enumerate()
1202                .filter(|(_, t)| t.get("name").and_then(|v| v.as_str()) == Some(name))
1203                .map(|(i, _)| i)
1204                .collect();
1205            for i in to_remove.into_iter().rev() {
1206                arr.remove(i);
1207            }
1208        }
1209    }
1210
1211    doc.to_string()
1212}
1213
1214#[cfg(test)]
1215mod tests {
1216    use super::*;
1217
1218    const SAMPLE_CONFIG: &str = r#"
1219[server]
1220port = 8082
1221
1222[[accounts]]
1223name = "alice"
1224plan_type = "pro"
1225
1226[[accounts]]
1227name = "bob"
1228plan_type = "max"
1229
1230[[accounts]]
1231name = "charlie"
1232plan_type = "pro"
1233"#;
1234
1235    #[test]
1236    fn test_remove_account_block_removes_target() {
1237        let result = remove_account_block(SAMPLE_CONFIG, "bob");
1238        // bob must be gone
1239        assert!(!result.contains("\"bob\"") && !result.contains("'bob'") && !result.contains("bob"),
1240            "removed account must not appear: {result}");
1241        // others must remain
1242        assert!(result.contains("alice"));
1243        assert!(result.contains("charlie"));
1244    }
1245
1246    #[test]
1247    fn test_remove_account_block_preserves_others() {
1248        let result = remove_account_block(SAMPLE_CONFIG, "alice");
1249        assert!(!result.contains("alice"), "alice must be removed");
1250        assert!(result.contains("bob"),     "bob must remain");
1251        assert!(result.contains("charlie"), "charlie must remain");
1252    }
1253
1254    #[test]
1255    fn test_remove_account_block_noop_when_not_found() {
1256        let result = remove_account_block(SAMPLE_CONFIG, "dave");
1257        // All three must still be present
1258        assert!(result.contains("alice"));
1259        assert!(result.contains("bob"));
1260        assert!(result.contains("charlie"));
1261    }
1262
1263    #[test]
1264    fn test_remove_account_block_last_account() {
1265        let cfg = "[[accounts]]\nname = \"only\"\nplan_type = \"pro\"\n";
1266        let result = remove_account_block(cfg, "only");
1267        assert!(!result.contains("only"), "sole account must be removed");
1268    }
1269
1270    #[test]
1271    fn test_remove_account_block_handles_unparseable_input() {
1272        let bad = "not valid [[toml{{ garbage";
1273        let result = remove_account_block(bad, "anything");
1274        // Must return input unchanged, not panic
1275        assert_eq!(result, bad);
1276    }
1277
1278    #[test]
1279    fn test_remove_account_block_with_inline_comment() {
1280        let cfg = "[[accounts]]\nname = \"alice\" # main account\nplan_type = \"pro\"\n\n[[accounts]]\nname = \"bob\"\nplan_type = \"max\"\n";
1281        let result = remove_account_block(cfg, "alice");
1282        assert!(!result.contains("alice"));
1283        assert!(result.contains("bob"));
1284    }
1285}
1286
1287// ---------------------------------------------------------------------------
1288// start
1289// ---------------------------------------------------------------------------
1290
1291async fn cmd_start(
1292    config_override: Option<PathBuf>,
1293    host_override: Option<String>,
1294    port_override: Option<u16>,
1295    foreground: bool,
1296    verbose: bool,
1297    daemon: bool,
1298) -> Result<()> {
1299    let config_p = config_override.clone().unwrap_or_else(config_path);
1300
1301    // ── Daemon mode: internal re-exec, no user output ────────────────────────
1302    if daemon {
1303        if !config_p.exists() { return Ok(()); }
1304        let mut config = crate::config::load_config(config_override.as_deref())?;
1305        let host = host_override.unwrap_or_else(|| config.server.host.clone());
1306        let port = port_override.unwrap_or(config.server.port);
1307
1308        // #5: Warn once if sensitive values are found in config as plaintext.
1309        if let Ok(raw) = std::fs::read_to_string(&config_p) {
1310            if raw.lines().any(|l| l.trim_start().starts_with("cloudflare_api_token") || l.trim_start().starts_with("remote_key")) {
1311                eprintln!("  [shunt] Warning: plaintext sensitive values detected in config.toml.");
1312                eprintln!("  [shunt] Consider migrating to env vars: CLOUDFLARE_API_TOKEN, SHUNT_REMOTE_KEY");
1313            }
1314        }
1315
1316        for account in &mut config.accounts {
1317            if let Some(cred) = &account.credential {
1318                if cred.needs_refresh() {
1319                    if let Some(oauth) = cred.as_oauth() {
1320                        if let Ok(Ok(fresh)) = tokio::time::timeout(
1321                            std::time::Duration::from_secs(10),
1322                            account.provider.refresh_token(oauth),
1323                        ).await {
1324                            let mut store = CredentialsStore::load();
1325                            store.accounts.insert(account.name.clone(), Credential::Oauth(fresh.clone()));
1326                            store.save().ok();
1327                            account.credential = Some(Credential::Oauth(fresh));
1328                        }
1329                    }
1330                }
1331            }
1332        }
1333
1334        let lp = log_path();
1335        let log_level = if verbose { "debug" } else { config.server.log_level.as_str() };
1336        crate::logging::prune_old_logs(&lp, 7);
1337        let _log_guard = crate::logging::setup(&lp, log_level)?;
1338        let state = crate::state::StateStore::load(&crate::config::state_path());
1339        write_pid();
1340        // Apply routing on every daemon start — silently re-injects ANTHROPIC_BASE_URL
1341        // into both settings files so Claude Code routes through shunt immediately.
1342        apply_local_routing_silent(port);
1343        serve_all_providers(config, state, &host, port).await?;
1344        return Ok(());
1345    }
1346
1347    // ── Auto-setup on first run ───────────────────────────────────────────────
1348    // Skip interactive setup when stdin is not a TTY (e.g. curl | sh) to
1349    // avoid blocking on macOS Keychain or OAuth prompts.
1350    let stdin_is_tty = unsafe { libc::isatty(libc::STDIN_FILENO) != 0 };
1351    if !config_p.exists() && stdin_is_tty {
1352        cmd_setup_auto(config_override.clone()).await?;
1353    }
1354
1355    let config = crate::config::load_config(config_override.as_deref())?;
1356    let host = host_override.clone().unwrap_or_else(|| config.server.host.clone());
1357    let port = port_override.unwrap_or(config.server.port);
1358
1359    // Kill any previous instance on this port
1360    for pid in port_pids(port) {
1361        let _ = std::process::Command::new("kill").arg(pid.to_string()).status();
1362    }
1363    if !port_pids(port).is_empty() {
1364        std::thread::sleep(std::time::Duration::from_millis(400));
1365    }
1366
1367    // ── Foreground mode (debugging) ───────────────────────────────────────────
1368    if foreground {
1369        use std::io::Write as _;
1370        let mut config = config;
1371        let account_names: Vec<&str> = config.accounts.iter().map(|a| a.name.as_str()).collect();
1372        print_routing_header(&account_names, &[
1373            format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
1374            dim("foreground").to_string(),
1375        ]);
1376        for account in &mut config.accounts {
1377            if let Some(cred) = &account.credential {
1378                if cred.needs_refresh() {
1379                    if let Some(oauth) = cred.as_oauth() {
1380                        print!("  {} Refreshing '{}'… ", yellow("↻"), account.name);
1381                        std::io::stdout().flush().ok();
1382                        match tokio::time::timeout(
1383                            std::time::Duration::from_secs(10),
1384                            account.provider.refresh_token(oauth),
1385                        ).await {
1386                            Ok(Ok(fresh)) => {
1387                                println!("{}", green("done"));
1388                                let mut store = CredentialsStore::load();
1389                                store.accounts.insert(account.name.clone(), Credential::Oauth(fresh.clone()));
1390                                store.save().ok();
1391                                account.credential = Some(Credential::Oauth(fresh));
1392                            }
1393                            Ok(Err(e)) => println!("{}", yellow(&format!("failed ({})", e))),
1394                            Err(_)    => println!("{}", yellow("timed out")),
1395                        }
1396                    }
1397                }
1398            }
1399        }
1400        let lp = log_path();
1401        let log_level = if verbose { "debug" } else { config.server.log_level.as_str() };
1402        crate::logging::prune_old_logs(&lp, 7);
1403        let _log_guard = crate::logging::setup(&lp, log_level)?;
1404        let col = 13usize;
1405        println!("  {}  {} {}", dim(&pad("listening", col)), dim("[control]"),
1406            green_bold(&format!("http://{host}:{}", config.server.control_port)));
1407        for (p, addr) in listener_addrs(&config.accounts, &host, port) {
1408            println!("  {}  {} {}", dim(&pad("listening", col)), dim(&format!("[{p}]")), green_bold(&addr));
1409        }
1410        println!("  {}  {}", dim(&pad("logs", col)), dim(&lp.display().to_string()));
1411        println!();
1412        let state = crate::state::StateStore::load(&crate::config::state_path());
1413        write_pid();
1414        apply_local_routing_silent(port);
1415        serve_all_providers(config, state, &host, port).await?;
1416        return Ok(());
1417    }
1418
1419    // ── Background mode (default) ─────────────────────────────────────────────
1420    let exe = std::env::current_exe().context("cannot locate current executable")?;
1421    let mut cmd = std::process::Command::new(&exe);
1422    cmd.arg("start").arg("--daemon");
1423    if let Some(ref p) = config_override { cmd.args(["--config", &p.display().to_string()]); }
1424    if let Some(ref h) = host_override   { cmd.args(["--host", h]); }
1425    if let Some(p) = port_override       { cmd.args(["--port", &p.to_string()]); }
1426    if verbose                           { cmd.arg("--verbose"); }
1427    cmd.stdin(std::process::Stdio::null())
1428       .stdout(std::process::Stdio::null())
1429       .stderr(std::process::Stdio::null())
1430       .spawn()
1431       .context("failed to start proxy in background")?;
1432
1433    // Wait until the control plane is accepting connections (up to 8 s)
1434    let control_port = config.server.control_port;
1435    let ready = wait_for_health(&host, control_port, 8).await;
1436
1437    // Auto-write ANTHROPIC_BASE_URL to shell profile (silent if already there)
1438    auto_write_shell_export(port);
1439
1440    let account_names: Vec<&str> = config.accounts.iter().map(|a| a.name.as_str()).collect();
1441    let status_line = if ready {
1442        format!("{}  {}  {}", green(DOT), green_bold("running"), cyan(&format!("http://{host}:{port}")))
1443    } else {
1444        format!("{}  {}  {}", yellow(DOT), yellow("starting"), dim(&format!("http://{host}:{port}")))
1445    };
1446    print_routing_header(&account_names, &[
1447        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
1448        status_line,
1449    ]);
1450
1451    Ok(())
1452}
1453
1454// ---------------------------------------------------------------------------
1455// stop
1456// ---------------------------------------------------------------------------
1457
1458async fn cmd_stop() -> Result<()> {
1459    cmd_stop_impl(false).await
1460}
1461
1462async fn cmd_stop_quiet() -> Result<()> {
1463    cmd_stop_impl(true).await
1464}
1465
1466async fn cmd_stop_impl(quiet: bool) -> Result<()> {
1467    let pid_p = pid_path();
1468    let content = match std::fs::read_to_string(&pid_p) {
1469        Ok(c) => c,
1470        Err(_) => {
1471            if !quiet { println!("  {} Proxy is not running.", dim("·")); println!(); }
1472            return Ok(());
1473        }
1474    };
1475    let pid = match content.trim().parse::<u32>() {
1476        Ok(p) => p,
1477        Err(_) => {
1478            let _ = std::fs::remove_file(&pid_p);
1479            if !quiet { println!("  {} Proxy is not running.", dim("·")); println!(); }
1480            return Ok(());
1481        }
1482    };
1483    if !is_shunt_pid(pid) {
1484        let _ = std::fs::remove_file(&pid_p);
1485        if !quiet { println!("  {} Proxy is not running.", dim("·")); }
1486        // Daemon died without cleanup — remove stale routing so Claude Code doesn't
1487        // keep hitting a dead localhost port.
1488        if let Some(home) = dirs::home_dir() {
1489            remove_from_settings_file_quiet(&home.join(".claude").join("settings.json"));
1490            remove_from_settings_file_quiet(&managed_claude_settings_path(&home));
1491        }
1492        if !quiet { println!(); }
1493        return Ok(());
1494    }
1495
1496    // SIGTERM — let axum drain connections cleanly
1497    unsafe { libc::kill(pid as i32, libc::SIGTERM) };
1498
1499    // Wait up to 3 s for clean exit, then SIGKILL
1500    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
1501    while std::time::Instant::now() < deadline {
1502        std::thread::sleep(std::time::Duration::from_millis(100));
1503        if !is_shunt_pid(pid) { break; }
1504    }
1505    if is_shunt_pid(pid) {
1506        unsafe { libc::kill(pid as i32, libc::SIGKILL) };
1507        std::thread::sleep(std::time::Duration::from_millis(200));
1508    }
1509
1510    let _ = std::fs::remove_file(&pid_p);
1511    if !quiet { println!("  {} Proxy stopped.", green(CHECK)); }
1512
1513    // Remove routing from both settings files so Claude Code hits the API directly
1514    // while the daemon is down (avoids "connection refused" errors).
1515    // Routing is re-applied automatically when the daemon starts again.
1516    if let Some(home) = dirs::home_dir() {
1517        remove_from_settings_file_quiet(&home.join(".claude").join("settings.json"));
1518        remove_from_settings_file_quiet(&managed_claude_settings_path(&home));
1519    }
1520
1521    if !quiet { println!(); }
1522    Ok(())
1523}
1524
1525fn is_shunt_pid(pid: u32) -> bool {
1526    let Ok(out) = std::process::Command::new("ps")
1527        .args(["-p", &pid.to_string(), "-o", "comm="])
1528        .output()
1529    else { return false };
1530    String::from_utf8_lossy(&out.stdout).trim().contains("shunt")
1531}
1532
1533// ---------------------------------------------------------------------------
1534// restart
1535// ---------------------------------------------------------------------------
1536
1537async fn cmd_restart(config_override: Option<PathBuf>) -> Result<()> {
1538    print!("  {} Restarting…  ", dim("↻"));
1539    use std::io::Write as _;
1540    std::io::stdout().flush().ok();
1541    cmd_stop_quiet().await?;
1542    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1543    cmd_start(config_override, None, None, false, false, false).await
1544}
1545
1546// ---------------------------------------------------------------------------
1547// logs
1548// ---------------------------------------------------------------------------
1549
1550async fn cmd_logs(_config_override: Option<PathBuf>, follow: bool, lines: usize, raw_json: bool) -> Result<()> {
1551    use std::io::{BufRead, BufReader, Write};
1552
1553    let log = log_path();
1554    if !log.exists() {
1555        println!("  {} No log file found.", dim("·"));
1556        println!("  {} Start the proxy first: {}", dim("·"), cyan("shunt start"));
1557        println!();
1558        return Ok(());
1559    }
1560
1561    let file = std::fs::File::open(&log)?;
1562    let mut reader = BufReader::new(file);
1563
1564    let render = |l: &str| -> String {
1565        if raw_json { l.trim_end().to_string() } else { pretty_log_line(l) }
1566    };
1567
1568    // Ring buffer — keep last N lines regardless of file size.
1569    let mut ring: std::collections::VecDeque<String> = std::collections::VecDeque::with_capacity(lines + 1);
1570    let mut line = String::new();
1571    while reader.read_line(&mut line)? > 0 {
1572        if ring.len() >= lines { ring.pop_front(); }
1573        ring.push_back(std::mem::take(&mut line));
1574    }
1575    for l in &ring { println!("{}", render(l)); }
1576    std::io::stdout().flush().ok();
1577
1578    if !follow { return Ok(()); }
1579
1580    eprintln!("{}", dim("--- following (Ctrl+C to stop) ---"));
1581    loop {
1582        line.clear();
1583        if reader.read_line(&mut line)? > 0 {
1584            println!("{}", render(&line));
1585            std::io::stdout().flush().ok();
1586        } else {
1587            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1588        }
1589    }
1590}
1591
1592/// Format a log line into a human-readable string.
1593/// Handles both JSON (rotating file appender) and ANSI tracing text
1594/// (daemon stderr redirected into proxy.log). Strips ANSI when not JSON.
1595fn pretty_log_line(line: &str) -> String {
1596    let line = line.trim_end();
1597    let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
1598        // Not JSON (ANSI-formatted tracing stderr) — strip escape codes.
1599        return strip_ansi(line);
1600    };
1601
1602    // Timestamp: keep only HH:MM:SS from "2026-05-28T16:28:19.208352Z"
1603    let time = v["timestamp"].as_str()
1604        .and_then(|t| t.get(11..19))
1605        .unwrap_or("??:??:??");
1606
1607    let level = v["level"].as_str().unwrap_or("????");
1608    let level_str = match level {
1609        "ERROR" => red("ERROR"),
1610        "WARN"  => yellow("WARN "),
1611        "INFO"  => dim("INFO "),
1612        "DEBUG" => dim("DEBUG"),
1613        other   => dim(other),
1614    };
1615
1616    let fields = v["fields"].as_object();
1617    let message = fields
1618        .and_then(|f| f["message"].as_str())
1619        .unwrap_or(line);
1620
1621    // Message color by level
1622    let message_str = match level {
1623        "ERROR" => red(message),
1624        "WARN"  => yellow(message),
1625        _       => message.to_string(),
1626    };
1627
1628    // Build key=value pairs — skip "message", format latency nicely
1629    let mut kvs = String::new();
1630    if let Some(fields) = fields {
1631        // Preferred key order for readability
1632        const ORDER: &[&str] = &["account", "model", "status", "latency_ms", "path", "request_id"];
1633        let mut seen = std::collections::HashSet::new();
1634
1635        for &k in ORDER {
1636            if let Some(val) = fields.get(k) {
1637                seen.insert(k);
1638                let v_str = val_to_str(val);
1639                if v_str.is_empty() { continue; }
1640                let (display_k, display_v) = if k == "latency_ms" {
1641                    ("latency", format!("{}ms", v_str))
1642                } else {
1643                    (k, v_str)
1644                };
1645                kvs.push_str(&format!("  {}={}", dim(display_k), display_v));
1646            }
1647        }
1648        // Any remaining fields not in ORDER
1649        for (k, val) in fields {
1650            if k == "message" || seen.contains(k.as_str()) { continue; }
1651            let v_str = val_to_str(val);
1652            if v_str.is_empty() { continue; }
1653            kvs.push_str(&format!("  {}={}", dim(k), v_str));
1654        }
1655    }
1656
1657    format!("{}  {}  {}{}", dim(time), level_str, message_str, kvs)
1658}
1659
1660fn val_to_str(v: &serde_json::Value) -> String {
1661    match v {
1662        serde_json::Value::String(s) => s.clone(),
1663        serde_json::Value::Null      => String::new(),
1664        other                        => other.to_string(),
1665    }
1666}
1667
1668
1669/// Non-interactive setup called from `cmd_start`.
1670/// Imports the existing Claude Code session silently.
1671/// The only user interaction is the OAuth code paste if no session exists.
1672async fn cmd_setup_auto(config_override: Option<PathBuf>) -> Result<()> {
1673    let config_p = config_override.clone().unwrap_or_else(config_path);
1674
1675    let mut cred = match crate::oauth::read_claude_credentials() {
1676        Some(mut c) => {
1677            if c.needs_refresh() {
1678                if let Ok(fresh) = refresh_token(&c).await { c = fresh; }
1679            }
1680            c
1681        }
1682        None => {
1683            // No session on disk — run the full OAuth flow (user pastes code)
1684            println!("  {} No Claude Code session found — opening browser for login…", yellow("·"));
1685            crate::oauth::run_oauth_flow().await?
1686        }
1687    };
1688
1689    let plan = crate::oauth::read_claude_session_info()
1690        .map(|s| s.plan)
1691        .unwrap_or_else(|| "pro".to_string());
1692
1693    cred.email = crate::oauth::fetch_account_email(&cred.access_token).await;
1694
1695    if let Some(parent) = config_p.parent() { std::fs::create_dir_all(parent)?; }
1696    std::fs::write(&config_p, crate::config::config_template(&[("main", &plan)]))?;
1697    #[cfg(unix)] {
1698        use std::os::unix::fs::PermissionsExt;
1699        std::fs::set_permissions(&config_p, std::fs::Permissions::from_mode(0o600))?;
1700    }
1701
1702    let mut store = CredentialsStore::default();
1703    store.accounts.insert("main".into(), Credential::Oauth(cred));
1704    store.save()?;
1705
1706    Ok(())
1707}
1708
1709async fn wait_for_health(host: &str, port: u16, timeout_secs: u64) -> bool {
1710    let url = format!("http://{host}:{port}/health");
1711    let client = reqwest::Client::builder()
1712        .timeout(std::time::Duration::from_secs(2))
1713        .build()
1714        .unwrap_or_default();
1715    let deadline = tokio::time::Instant::now()
1716        + std::time::Duration::from_secs(timeout_secs);
1717    while tokio::time::Instant::now() < deadline {
1718        if client.get(&url).send().await
1719            .map(|r| r.status().is_success())
1720            .unwrap_or(false)
1721        {
1722            return true;
1723        }
1724        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1725    }
1726    false
1727}
1728
1729fn auto_write_shell_export(port: u16) {
1730    use std::io::Write;
1731    let line = format!("export ANTHROPIC_BASE_URL=http://127.0.0.1:{port}");
1732    let Some(profile) = detect_shell_profile() else { return };
1733
1734    if profile.exists() {
1735        if let Ok(contents) = std::fs::read_to_string(&profile) {
1736            if contents.contains(&line) {
1737                // Already exactly correct — nothing to do.
1738                return;
1739            }
1740            if contents.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:") {
1741                // Has the variable but with a different port — update it in-place.
1742                let updated: String = contents
1743                    .lines()
1744                    .map(|l| {
1745                        if l.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:") {
1746                            line.as_str()
1747                        } else {
1748                            l
1749                        }
1750                    })
1751                    .collect::<Vec<_>>()
1752                    .join("\n")
1753                    + "\n";
1754                if std::fs::write(&profile, updated).is_ok() {
1755                    println!("  {} {} updated to port {}  → {}",
1756                        green(CHECK), cyan("ANTHROPIC_BASE_URL"), port,
1757                        dim(&profile.display().to_string()));
1758                }
1759                return;
1760            }
1761            if contents.contains("ANTHROPIC_BASE_URL") {
1762                // Set to something else (e.g. remote URL) — leave it alone.
1763                return;
1764            }
1765        }
1766    }
1767
1768    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&profile) {
1769        writeln!(f, "\n# Added by shunt").ok();
1770        writeln!(f, "{line}").ok();
1771        println!("  {} {} → {}",
1772            green(CHECK), cyan("ANTHROPIC_BASE_URL"),
1773            dim(&profile.display().to_string()));
1774    }
1775}
1776
1777// ---------------------------------------------------------------------------
1778// status
1779// ---------------------------------------------------------------------------
1780
1781/// Renders status by fetching from a remote shunt URL (set by `shunt connect`).
1782/// Accounts are sourced directly from the remote /status JSON, not local config.
1783async fn cmd_status_remote(remote_url: &str) -> Result<()> {
1784    let status_url = format!("{remote_url}/status");
1785    let resp = reqwest::Client::new()
1786        .get(&status_url)
1787        .timeout(std::time::Duration::from_secs(10))
1788        .send()
1789        .await;
1790
1791    let live: Option<serde_json::Value> = match resp {
1792        Ok(r) => futures_executor_hack(r),
1793        Err(e) => {
1794            println!();
1795            println!("  {} Cannot connect to remote shunt at {}", red(CROSS), cyan(remote_url));
1796            if e.is_connect() || e.is_timeout() {
1797                println!("  {} Host unreachable — is the tunnel/domain still active?", dim("·"));
1798            } else {
1799                println!("  {} Error: {e}", dim("·"));
1800            }
1801            println!("  {} Run {} on the host machine to create a new share code.", dim("·"), cyan("shunt share"));
1802            println!();
1803            return Ok(());
1804        }
1805    };
1806
1807    let Some(data) = live else {
1808        println!();
1809        println!("  {} Connected to {} but got an unexpected response.", red(CROSS), cyan(remote_url));
1810        println!("  {} The URL may not point to a shunt instance.", dim("·"));
1811        println!();
1812        return Ok(());
1813    };
1814
1815    let accounts = data["accounts"].as_array().map(|v| v.as_slice()).unwrap_or(&[]);
1816    let version = data["version"].as_str().unwrap_or("?");
1817
1818    let provider_lines = {
1819        let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
1820        for a in accounts {
1821            let label = a["provider"].as_str().unwrap_or("unknown");
1822            *counts.entry(label).or_default() += 1;
1823        }
1824        let mut lines = vec!["accounts connected".to_string(), String::new()];
1825        lines.extend(counts.iter().map(|(label, n)| {
1826            let provider_display = match *label {
1827                "anthropic" => "Claude Code",
1828                "openai"    => "Codex",
1829                l           => l,
1830            };
1831            format!("{n} {provider_display} {}", if *n == 1 { "account" } else { "accounts" })
1832        }));
1833        lines
1834    };
1835
1836    let title = format!("shunt  v{}", env!("CARGO_PKG_VERSION"));
1837    print_status_splash(&title, provider_lines);
1838    println!();
1839
1840    let now_secs = SystemTime::now().duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs()).unwrap_or(0);
1841    let pinned = data["pinned_account"].as_str().map(|s| s.to_owned());
1842    let last_used = data["last_used_account"].as_str().map(|s| s.to_owned());
1843
1844    // Pinned notice
1845    if let Some(ref p) = pinned {
1846        println!("  {}  pinned to {}", yellow(DIAMOND), bold(p));
1847        println!("  {}  run {} to restore auto routing", dim("·"), cyan("shunt use auto"));
1848        println!();
1849    }
1850
1851    for acc in accounts {
1852        let name      = acc["name"].as_str().unwrap_or("?");
1853        let status    = acc["status"].as_str().unwrap_or("offline");
1854        let email     = acc["email"].as_str().unwrap_or("");
1855        let plan_type = acc["plan_type"].as_str().unwrap_or("pro");
1856        let provider  = acc["provider"].as_str().unwrap_or("anthropic");
1857
1858        let (status_icon, status_text): (String, String) = match status {
1859            "available"       => (green(CHECK),   green("available")),
1860            "cooling"         => (yellow("↻"),    yellow("cooling")),
1861            "disabled"        => (red(CROSS),     red("disabled")),
1862            "reauth_required" => (red(CROSS),     red("session expired")),
1863            _                 => (dim(EMPTY),     dim("offline")),
1864        };
1865
1866        let plan_label = match provider {
1867            "anthropic" => match plan_type.to_lowercase().as_str() {
1868                "max" | "claude_max" => "Claude Max",
1869                "team"               => "Claude Team",
1870                _                    => "Claude Pro",
1871            },
1872            _ => "",
1873        };
1874
1875        let is_pinned  = pinned.as_deref() == Some(name);
1876        let is_last    = !is_pinned && last_used.as_deref() == Some(name);
1877        let (routing_tag, tag_vis_len): (String, usize) = if is_pinned {
1878            (format!("  {}", yellow("pinned")), 8)
1879        } else if is_last {
1880            (format!("  {}", green("active")), 8)
1881        } else {
1882            (String::new(), 0)
1883        };
1884
1885        println!("{}", card_header(name, &green_bold(name), &routing_tag, tag_vis_len, plan_label));
1886        if !email.is_empty() {
1887            println!("{}", card_row(&dim(email)));
1888        }
1889        println!();
1890        println!("{}", card_row(&format!("{}  {}", status_icon, status_text)));
1891
1892        // Rate-limit bars
1893        if let Some(rl) = acc["rate_limit"].as_object() {
1894            let util_5h   = rl.get("utilization_5h").and_then(|v| v.as_f64());
1895            let reset_5h  = rl.get("reset_5h").and_then(|v| v.as_u64());
1896            let status_5h = rl.get("status_5h").and_then(|v| v.as_str()).unwrap_or("allowed");
1897            let util_7d   = rl.get("utilization_7d").and_then(|v| v.as_f64());
1898            let reset_7d  = rl.get("reset_7d").and_then(|v| v.as_u64());
1899            let status_7d = rl.get("status_7d").and_then(|v| v.as_str()).unwrap_or("allowed");
1900
1901            let window_row = |label: &str, util: Option<f64>, reset: Option<u64>, wstatus: &str| {
1902                if reset.map(|t| t <= now_secs).unwrap_or(false) {
1903                    let ago = reset.map(|t| format!(
1904                        "  {} ago", term::fmt_duration_ms(now_secs.saturating_sub(t) * 1000)
1905                    )).unwrap_or_default();
1906                    println!("{}", card_row(&format!(
1907                        "{}  {}  {}{}",
1908                        dim(label), green(&"─".repeat(20)), green("fresh"), dim(&ago)
1909                    )));
1910                } else if let Some(u) = util {
1911                    let rem = 100u64.saturating_sub((u * 100.0) as u64);
1912                    let bar = util_bar(u, 20);
1913                    let reset_str = reset.and_then(|t| secs_until(t))
1914                        .map(|s| format!("  ·  resets in {}", term::fmt_duration_ms(s * 1000)))
1915                        .unwrap_or_default();
1916                    let pct = if wstatus == "exhausted" {
1917                        red("exhausted")
1918                    } else {
1919                        format!("{}% left", bold(&rem.to_string()))
1920                    };
1921                    println!("{}", card_row(&format!(
1922                        "{}  {}  {}{}",
1923                        dim(label), bar, pct, dim(&reset_str)
1924                    )));
1925                }
1926            };
1927
1928            if util_5h.is_some() || reset_5h.is_some() { window_row("5h", util_5h, reset_5h, status_5h); }
1929            if util_7d.is_some() || reset_7d.is_some() { window_row("7d", util_7d, reset_7d, status_7d); }
1930        }
1931
1932        println!();
1933        println!("{}", card_sep());
1934        println!();
1935    }
1936
1937    // Remote host info footer
1938    println!("  {}  remote shunt v{}  {}  {}", dim("·"), dim(version), dim("·"), dim(remote_url));
1939    println!();
1940    Ok(())
1941}
1942
1943async fn cmd_status(config_override: Option<PathBuf>) -> Result<()> {
1944    // Remote mode: ANTHROPIC_BASE_URL is a non-local shunt (written by `shunt connect`).
1945    // Render accounts directly from the remote /status JSON — local config is irrelevant.
1946    if let Some(remote) = std::env::var("ANTHROPIC_BASE_URL").ok()
1947        .filter(|u| !u.contains("127.0.0.1") && !u.contains("localhost"))
1948        .map(|u| u.trim_end_matches('/').to_owned())
1949    {
1950        return cmd_status_remote(&remote).await;
1951    }
1952
1953    let mut config = crate::config::load_config(config_override.as_deref())?;
1954
1955    // Fetch live status from local control port.
1956    let live: Option<serde_json::Value> = reqwest::get(
1957        format!("http://{}:{}/status", config.server.host, config.server.control_port)
1958    ).await.ok().and_then(|r| futures_executor_hack(r));
1959
1960    // Back-fill missing emails (existing accounts set up before email support).
1961    // Fetch in parallel, persist any that are new.
1962    let mut store_dirty = false;
1963    let mut store = CredentialsStore::load();
1964    for acc in &mut config.accounts {
1965        if acc.credential.as_ref().map(|c| c.email().is_none()).unwrap_or(false) {
1966            let token = acc.credential.as_ref().map(|c| c.access_token().to_owned()).unwrap_or_default();
1967            if let Some(email) = crate::oauth::fetch_account_email(&token).await {
1968                if let Some(oauth) = acc.credential.as_mut().and_then(|c| c.as_oauth_mut()) {
1969                    oauth.email = Some(email.clone());
1970                }
1971                if let Some(stored) = store.accounts.get_mut(&acc.name) {
1972                    if let Some(oauth) = stored.as_oauth_mut() {
1973                        oauth.email = Some(email);
1974                        store_dirty = true;
1975                    }
1976                }
1977            }
1978        }
1979    }
1980    if store_dirty {
1981        store.save().ok();
1982    }
1983
1984    // Build per-provider account counts for the splash right panel.
1985    let provider_lines: Vec<String> = {
1986        let mut counts: Vec<(String, usize)> = vec![];
1987        for acc in &config.accounts {
1988            let label = match &acc.provider {
1989                crate::provider::Provider::Anthropic   => "Claude Code",
1990                crate::provider::Provider::OpenAI      => "Codex",
1991                crate::provider::Provider::OpenAIApi   => "OpenAI",
1992                crate::provider::Provider::OllamaCloud => "Ollama",
1993                crate::provider::Provider::Groq        => "Groq",
1994                crate::provider::Provider::Mistral     => "Mistral",
1995                crate::provider::Provider::Together    => "Together",
1996                crate::provider::Provider::OpenRouter  => "OpenRouter",
1997                crate::provider::Provider::DeepSeek    => "DeepSeek",
1998                crate::provider::Provider::Fireworks   => "Fireworks",
1999                crate::provider::Provider::Gemini      => "Gemini",
2000                crate::provider::Provider::Local       => "Local",
2001            };
2002            if let Some(entry) = counts.iter_mut().find(|(l, _)| l == label) {
2003                entry.1 += 1;
2004            } else {
2005                counts.push((label.to_string(), 1));
2006            }
2007        }
2008        let mut lines = vec![
2009            "accounts connected".to_string(),
2010            String::new(),
2011        ];
2012        lines.extend(counts.iter().map(|(label, n)| {
2013            let noun = if *n == 1 { "account" } else { "accounts" };
2014            format!("{n} {label} {noun}")
2015        }));
2016        lines
2017    };
2018
2019    let title = format!("shunt  v{}", env!("CARGO_PKG_VERSION"));
2020    print_status_splash(&title, provider_lines);
2021    println!();
2022
2023    let pinned_account = live.as_ref().and_then(|v| v["pinned"].as_str()).map(|s| s.to_owned());
2024    let last_used_account = live.as_ref().and_then(|v| v["last_used"].as_str()).map(|s| s.to_owned());
2025
2026    // Pinned notice
2027    if let Some(ref pinned) = pinned_account {
2028        println!("  {}  pinned to {}",
2029            yellow(DIAMOND), bold(pinned));
2030        println!("  {}  run {} to restore auto routing",
2031            dim("·"), cyan("shunt use auto"));
2032        println!();
2033    }
2034
2035    let now_secs = SystemTime::now().duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs()).unwrap_or(0);
2036
2037    for acc in &config.accounts {
2038        let live_acc = live.as_ref()
2039            .and_then(|v| v["accounts"].as_array())
2040            .and_then(|arr| arr.iter().find(|a| a["name"] == acc.name));
2041
2042        let status = live_acc.and_then(|a| a["status"].as_str()).unwrap_or("offline");
2043
2044        let (status_icon, status_text): (String, String) = match status {
2045            "available"       => (green(CHECK), green("available")),
2046            "cooling"         => (yellow("↻"),  yellow("cooling")),
2047            "disabled"        => (red(CROSS),   red("disabled")),
2048            "reauth_required" => (red(CROSS),   red("session expired")),
2049            _ => {
2050                use crate::provider::AuthKind;
2051                match &acc.credential {
2052                    // Local/None-auth providers don't need a credential — show offline, not error.
2053                    None if acc.provider.auth_kind() == AuthKind::None
2054                                                  => (dim(EMPTY),   dim("offline")),
2055                    None                          => (red(CROSS),   red("no credential")),
2056                    Some(c) if c.needs_refresh()  => (yellow(CROSS), yellow("token expired")),
2057                    _                             => (dim(EMPTY),   dim("offline")),
2058                }
2059            }
2060        };
2061
2062        let plan_label: &str = match &acc.provider {
2063            crate::provider::Provider::OpenAI => match acc.plan_type.to_lowercase().as_str() {
2064                "plus"  => "ChatGPT Plus [beta]",
2065                "pro"   => "ChatGPT Pro [beta]",
2066                "team"  => "ChatGPT Team [beta]",
2067                _       => "ChatGPT [beta]",
2068            },
2069            crate::provider::Provider::Anthropic => match acc.plan_type.to_lowercase().as_str() {
2070                "max" | "claude_max" => "Claude Max",
2071                "team"               => "Claude Team",
2072                _                    => "Claude Pro",
2073            },
2074            // API-key and Local providers don't have Claude plan tiers.
2075            _ => "",
2076        };
2077        let email_str = acc.credential.as_ref().and_then(|c| c.email()).unwrap_or("");
2078
2079        // ── routing tag ─────────────────────────────────────
2080        let is_pinned  = pinned_account.as_deref() == Some(&acc.name);
2081        let is_last    = !is_pinned && last_used_account.as_deref() == Some(&acc.name);
2082        let (routing_tag, tag_vis_len): (String, usize) = if is_pinned {
2083            (format!("  {}", yellow("pinned")), 8)
2084        } else if is_last {
2085            (format!("  {}", green("active")), 8)
2086        } else {
2087            (String::new(), 0)
2088        };
2089
2090        // ── account header (name + tag + plan) ──────────────
2091        println!("{}", card_header(&acc.name, &green_bold(&acc.name), &routing_tag, tag_vis_len, plan_label));
2092
2093        // ── email + provider badge row ───────────────────────
2094        let provider_label = match &acc.provider {
2095            crate::provider::Provider::Anthropic => String::new(),
2096            crate::provider::Provider::OpenAI    => "chatgpt".to_string(),
2097            p                                    => p.to_string(),
2098        };
2099        let provider_badge = if provider_label.is_empty() {
2100            String::new()
2101        } else {
2102            format!("  {}  {}", dim("·"), dim(&format!("[{provider_label}]")))
2103        };
2104        if !email_str.is_empty() {
2105            println!("{}", card_row(&format!("{}{}", dim(email_str), provider_badge)));
2106        } else if !provider_badge.is_empty() {
2107            println!("{}", card_row(&dim(&format!("[{provider_label}]"))));
2108        }
2109
2110        println!();
2111
2112        // ── status ───────────────────────────────────────────
2113        println!("{}", card_row(&format!("{}  {}", status_icon, status_text)));
2114
2115        // ── rate limit bars ──────────────────────────────────
2116        if let Some(rl) = live_acc.and_then(|a| a["rate_limit"].as_object()) {
2117            let util_5h   = rl.get("utilization_5h").and_then(|v| v.as_f64());
2118            let reset_5h  = rl.get("reset_5h").and_then(|v| v.as_u64());
2119            let status_5h = rl.get("status_5h").and_then(|v| v.as_str()).unwrap_or("allowed");
2120            let util_7d   = rl.get("utilization_7d").and_then(|v| v.as_f64());
2121            let reset_7d  = rl.get("reset_7d").and_then(|v| v.as_u64());
2122            let status_7d = rl.get("status_7d").and_then(|v| v.as_str()).unwrap_or("allowed");
2123
2124            let window_row = |label: &str, util: Option<f64>, reset: Option<u64>, wstatus: &str| {
2125                if reset.map(|t| t <= now_secs).unwrap_or(false) {
2126                    let ago = reset.map(|t| format!(
2127                        "  {} ago", term::fmt_duration_ms(now_secs.saturating_sub(t) * 1000)
2128                    )).unwrap_or_default();
2129                    println!("{}", card_row(&format!(
2130                        "{}  {}  {}{}",
2131                        dim(label), green(&"─".repeat(20)), green("fresh"), dim(&ago)
2132                    )));
2133                } else if let Some(u) = util {
2134                    let rem = 100u64.saturating_sub((u * 100.0) as u64);
2135                    let bar = util_bar(u, 20);
2136                    let reset_str = reset.and_then(|t| secs_until(t))
2137                        .map(|s| format!("  ·  resets in {}", term::fmt_duration_ms(s * 1000)))
2138                        .unwrap_or_default();
2139                    let pct = if wstatus == "exhausted" {
2140                        red("exhausted")
2141                    } else {
2142                        format!("{}% left", bold(&rem.to_string()))
2143                    };
2144                    println!("{}", card_row(&format!(
2145                        "{}  {}  {}{}",
2146                        dim(label), bar, pct, dim(&reset_str)
2147                    )));
2148                }
2149            };
2150
2151            if util_5h.is_some() || reset_5h.is_some() {
2152                window_row("5h", util_5h, reset_5h, status_5h);
2153            }
2154            if util_7d.is_some() || reset_7d.is_some() {
2155                window_row("7d", util_7d, reset_7d, status_7d);
2156            }
2157        } else if acc.credential.is_none() && acc.provider.auth_kind() != crate::provider::AuthKind::None {
2158            println!("{}", card_row(&format!("{}  run {}",
2159                dim("·"), cyan(&format!("shunt add-account {}", acc.name)))));
2160        } else if status == "reauth_required" {
2161            println!("{}", card_row(&format!("{}  run {}",
2162                dim("·"), cyan(&format!("shunt add-account {}", acc.name)))));
2163        } else if live.is_some() && live_acc.is_some() {
2164            match &acc.provider {
2165                crate::provider::Provider::Anthropic =>
2166                    println!("{}", card_row(&dim("· quota data will appear after first request"))),
2167                crate::provider::Provider::Local => {
2168                    if acc.model.is_none() {
2169                        println!("{}", card_row(&dim(&format!(
2170                            "· tip: set model = \"your-model\" in config for this account"
2171                        ))));
2172                    }
2173                }
2174                _ =>
2175                    println!("{}", card_row(&dim("· quota tracking unavailable (provider doesn't report utilization)"))),
2176            }
2177        }
2178
2179        // ── separator ────────────────────────────────────────
2180        println!();
2181        println!("{}", card_sep());
2182        println!();
2183    }
2184
2185    Ok(())
2186}
2187
2188// ---------------------------------------------------------------------------
2189// use (pin account)
2190// ---------------------------------------------------------------------------
2191
2192async fn cmd_use(config_override: Option<PathBuf>, account: Option<String>) -> Result<()> {
2193    let config = crate::config::load_config(config_override.as_deref())?;
2194    let use_url = format!("http://{}:{}/use", config.server.host, config.server.control_port);
2195
2196    // Fetch live state for utilization info
2197    let live: Option<serde_json::Value> = reqwest::get(
2198        &format!("http://{}:{}/status", config.server.host, config.server.control_port)
2199    ).await.ok().and_then(|r| futures_executor_hack(r));
2200
2201    let current_pinned = live.as_ref()
2202        .and_then(|v| v["pinned"].as_str())
2203        .map(|s| s.to_owned());
2204
2205    // Build menu items
2206    let mut items: Vec<term::SelectItem> = config.accounts.iter().map(|a| {
2207        let live_acc = live.as_ref()
2208            .and_then(|v| v["accounts"].as_array())
2209            .and_then(|arr| arr.iter().find(|x| x["name"] == a.name));
2210
2211        let status = live_acc.and_then(|x| x["status"].as_str()).unwrap_or("offline");
2212        let util = live_acc.and_then(|x| x["rate_limit"]["utilization_5h"].as_f64());
2213        let is_pinned = current_pinned.as_deref() == Some(&a.name);
2214
2215        let status_str = match status {
2216            "reauth_required" => red("session expired"),
2217            "disabled"        => red("disabled"),
2218            "cooling"         => yellow("cooling"),
2219            "available"       => {
2220                match util {
2221                    Some(u) => {
2222                        let rem = 100u64.saturating_sub((u * 100.0) as u64);
2223                        green(&format!("{}% remaining", rem))
2224                    }
2225                    None => dim("fresh").to_string(),
2226                }
2227            }
2228            _ => dim("offline").to_string(),
2229        };
2230
2231        let email = a.credential.as_ref().and_then(|c| c.email()).unwrap_or("");
2232        let pin = if is_pinned { format!("  {}", yellow("pinned")) } else { String::new() };
2233
2234        term::SelectItem {
2235            label: format!("{}  {}  {}{}", bold(&pad(&a.name, 12)), dim(&pad(email, 32)), status_str, pin),
2236            value: a.name.clone(),
2237        }
2238    }).collect();
2239
2240    let auto_marker = if current_pinned.is_none() { format!("  {}", yellow("active")) } else { String::new() };
2241    items.push(term::SelectItem {
2242        label: format!("{}  {}{}", bold(&pad("auto", 12)), dim("least-utilization routing"), auto_marker),
2243        value: "auto".to_owned(),
2244    });
2245
2246    // Determine initial cursor position (current pinned account or auto)
2247    let initial = current_pinned.as_ref()
2248        .and_then(|p| items.iter().position(|it| &it.value == p))
2249        .unwrap_or(items.len() - 1);
2250
2251    // If account name was given directly, skip the picker
2252    let chosen = if let Some(name) = account {
2253        name
2254    } else {
2255        match term::select("Route traffic to:", &items, initial) {
2256            Some(v) => v,
2257            None => return Ok(()), // cancelled
2258        }
2259    };
2260
2261    // Validate
2262    let is_auto = chosen == "auto";
2263    if !is_auto && !config.accounts.iter().any(|a| a.name == chosen) {
2264        let names: Vec<_> = config.accounts.iter().map(|a| a.name.as_str()).collect();
2265        anyhow::bail!("Unknown account '{}'. Available: {}", chosen, names.join(", "));
2266    }
2267
2268    let client = reqwest::Client::new();
2269    let resp = client
2270        .post(&use_url)
2271        .json(&serde_json::json!({ "account": chosen }))
2272        .send()
2273        .await;
2274
2275    match resp {
2276        Ok(r) if r.status().is_success() => {
2277            if is_auto {
2278                println!("  {} Automatic routing restored", green(CHECK));
2279            } else {
2280                println!("  {} Pinned to {}  ·  {}", green(CHECK), bold(&chosen), dim("shunt use auto to restore"));
2281            }
2282            println!();
2283        }
2284        Ok(r) => {
2285            let body = r.text().await.unwrap_or_default();
2286            anyhow::bail!("Proxy returned error: {body}");
2287        }
2288        Err(_) => {
2289            // Proxy not running — persist directly to the state file so it
2290            // takes effect when the proxy next starts.
2291            write_pinned_to_state(if is_auto { None } else { Some(chosen.clone()) });
2292            if is_auto {
2293                println!("  {} Automatic routing saved  ·  {}", green(CHECK),
2294                    dim("applies on next shunt start"));
2295            } else {
2296                println!("  {} Pinned to {}  ·  {}", green(CHECK), bold(&chosen),
2297                    dim("applies on next shunt start"));
2298            }
2299            println!();
2300        }
2301    }
2302    Ok(())
2303}
2304
2305/// Write a pinned account directly into the state file (used when proxy is not running).
2306fn write_pinned_to_state(account: Option<String>) {
2307    let path = crate::config::state_path();
2308    let mut data: serde_json::Value = path.exists()
2309        .then(|| std::fs::read_to_string(&path).ok())
2310        .flatten()
2311        .and_then(|t| serde_json::from_str(&t).ok())
2312        .unwrap_or_else(|| serde_json::json!({}));
2313    data["pinned_account"] = match account {
2314        Some(a) => serde_json::Value::String(a),
2315        None => serde_json::Value::Null,
2316    };
2317    if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); }
2318    let tmp = path.with_extension("tmp");
2319    if let Ok(text) = serde_json::to_string_pretty(&data) {
2320        let _ = std::fs::write(&tmp, text);
2321        let _ = std::fs::rename(&tmp, &path);
2322    }
2323}
2324
2325async fn cmd_model(config_override: Option<PathBuf>, action: Option<ModelAction>) -> Result<()> {
2326    let config = crate::config::load_config(config_override.as_deref())?;
2327    let model_url = format!("http://{}:{}/model", config.server.host, config.server.control_port);
2328    let client = reqwest::Client::new();
2329
2330    match action {
2331        None => {
2332            // Show current override
2333            let resp = client.get(&model_url).send().await;
2334            match resp {
2335                Ok(r) if r.status().is_success() => {
2336                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2337                    match v["model"].as_str() {
2338                        Some(m) => println!("  {} Model override: {}  ·  {}", green(CHECK), bold(m), dim("shunt model clear to restore")),
2339                        None => println!("  {} No model override  ·  {}", dim(DOT), dim("clients choose their own model")),
2340                    }
2341                }
2342                _ => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2343            }
2344        }
2345        Some(ModelAction::Set { model }) => {
2346            let resp = client
2347                .post(&model_url)
2348                .json(&serde_json::json!({ "model": model }))
2349                .send()
2350                .await;
2351            match resp {
2352                Ok(r) if r.status().is_success() => {
2353                    println!("  {} Model override set: {}  ·  {}", green(CHECK), bold(&model), dim("shunt model clear to restore"));
2354                }
2355                Ok(r) => {
2356                    let body = r.text().await.unwrap_or_default();
2357                    anyhow::bail!("Proxy returned error: {body}");
2358                }
2359                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2360            }
2361        }
2362        Some(ModelAction::Clear) => {
2363            let resp = client.delete(&model_url).send().await;
2364            match resp {
2365                Ok(r) if r.status().is_success() => {
2366                    println!("  {} Model override cleared  ·  {}", green(CHECK), dim("clients now choose their own model"));
2367                }
2368                Ok(r) => {
2369                    let body = r.text().await.unwrap_or_default();
2370                    anyhow::bail!("Proxy returned error: {body}");
2371                }
2372                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2373            }
2374        }
2375    }
2376    println!();
2377    Ok(())
2378}
2379
2380async fn cmd_strategy(config_override: Option<PathBuf>, action: Option<StrategyAction>) -> Result<()> {
2381    let config = crate::config::load_config(config_override.as_deref())?;
2382    let strategy_url = format!("http://{}:{}/strategy", config.server.host, config.server.control_port);
2383    let client = reqwest::Client::new();
2384
2385    match action {
2386        None => {
2387            // Show current strategy + source
2388            let resp = client.get(&strategy_url).send().await;
2389            match resp {
2390                Ok(r) if r.status().is_success() => {
2391                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2392                    let strategy = v["strategy"].as_str().unwrap_or("unknown");
2393                    let source = v["source"].as_str().unwrap_or("unknown");
2394                    if source == "override" {
2395                        println!("  {} Routing strategy: {}  ·  {}  ·  {}", green(CHECK), bold(strategy), dim("runtime override"), dim("shunt strategy clear to restore"));
2396                    } else {
2397                        println!("  {} Routing strategy: {}  ·  {}", dim(DOT), bold(strategy), dim("from config"));
2398                    }
2399                }
2400                _ => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2401            }
2402        }
2403        Some(StrategyAction::Set { strategy }) => {
2404            let resp = client
2405                .post(&strategy_url)
2406                .json(&serde_json::json!({ "strategy": strategy }))
2407                .send()
2408                .await;
2409            match resp {
2410                Ok(r) if r.status().is_success() => {
2411                    println!("  {} Routing strategy set: {}  ·  {}", green(CHECK), bold(&strategy), dim("shunt strategy clear to restore"));
2412                }
2413                Ok(r) => {
2414                    let body = r.text().await.unwrap_or_default();
2415                    anyhow::bail!("Proxy returned error: {body}");
2416                }
2417                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2418            }
2419        }
2420        Some(StrategyAction::Clear) => {
2421            let resp = client.delete(&strategy_url).send().await;
2422            match resp {
2423                Ok(r) if r.status().is_success() => {
2424                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2425                    let strategy = v["strategy"].as_str().unwrap_or("unknown");
2426                    println!("  {} Strategy override cleared  ·  {}  ·  {}", green(CHECK), bold(strategy), dim("from config"));
2427                }
2428                Ok(r) => {
2429                    let body = r.text().await.unwrap_or_default();
2430                    anyhow::bail!("Proxy returned error: {body}");
2431                }
2432                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2433            }
2434        }
2435    }
2436    println!();
2437    Ok(())
2438}
2439
2440async fn cmd_burst_limit(config_override: Option<PathBuf>, action: Option<BurstLimitAction>) -> Result<()> {
2441    let config = crate::config::load_config(config_override.as_deref())?;
2442    let url = format!("http://{}:{}/burst-limit", config.server.host, config.server.control_port);
2443    let client = reqwest::Client::new();
2444
2445    match action {
2446        None => {
2447            let resp = client.get(&url).send().await;
2448            match resp {
2449                Ok(r) if r.status().is_success() => {
2450                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2451                    let limit = v["burst_rpm_limit"].as_u64().unwrap_or(0);
2452                    let source = v["source"].as_str().unwrap_or("unknown");
2453                    let display = if limit == 0 { "off".to_owned() } else { format!("{limit}/min") };
2454                    if source == "override" {
2455                        println!("  {} Burst limit: {}  ·  {}  ·  {}", green(CHECK), bold(&display), dim("runtime override"), dim("shunt burst-limit clear to restore"));
2456                    } else {
2457                        println!("  {} Burst limit: {}  ·  {}", dim(DOT), bold(&display), dim(&format!("from {source}")));
2458                    }
2459                }
2460                _ => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2461            }
2462        }
2463        Some(BurstLimitAction::Set { limit }) => {
2464            let resp = client.post(&url).json(&serde_json::json!({ "burst_rpm_limit": limit })).send().await;
2465            match resp {
2466                Ok(r) if r.status().is_success() => {
2467                    let display = if limit == 0 { "off".to_owned() } else { format!("{limit}/min") };
2468                    println!("  {} Burst limit set: {}  ·  {}", green(CHECK), bold(&display), dim("shunt burst-limit clear to restore"));
2469                }
2470                Ok(r) => { let body = r.text().await.unwrap_or_default(); anyhow::bail!("Proxy returned error: {body}"); }
2471                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2472            }
2473        }
2474        Some(BurstLimitAction::Clear) => {
2475            let resp = client.delete(&url).send().await;
2476            match resp {
2477                Ok(r) if r.status().is_success() => {
2478                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2479                    let limit = v["burst_rpm_limit"].as_u64().unwrap_or(0);
2480                    let display = if limit == 0 { "off".to_owned() } else { format!("{limit}/min") };
2481                    println!("  {} Burst limit override cleared  ·  {}  ·  {}", green(CHECK), bold(&display), dim("from default"));
2482                }
2483                Ok(r) => { let body = r.text().await.unwrap_or_default(); anyhow::bail!("Proxy returned error: {body}"); }
2484                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2485            }
2486        }
2487    }
2488    println!();
2489    Ok(())
2490}
2491
2492async fn cmd_fallback(config_override: Option<PathBuf>, action: Option<FallbackAction>) -> Result<()> {
2493    let config = crate::config::load_config(config_override.as_deref())?;
2494    let url = format!("http://{}:{}/fallback", config.server.host, config.server.control_port);
2495    let client = reqwest::Client::new();
2496
2497    match action {
2498        None => {
2499            let resp = client.get(&url).send().await;
2500            match resp {
2501                Ok(r) if r.status().is_success() => {
2502                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2503                    let source = v["source"].as_str().unwrap_or("unknown");
2504                    let disabled = v.get("disabled").and_then(|d| d.as_bool()).unwrap_or(false);
2505                    if disabled {
2506                        println!("  {} Fallback: {}  ·  {}", dim(DOT), bold("disabled"), dim("shunt fallback clear to restore"));
2507                    } else {
2508                        let model = v["fallback_model"].as_str().unwrap_or("none");
2509                        if source == "override" {
2510                            println!("  {} Fallback: {}  ·  {}  ·  {}", green(CHECK), bold(model), dim("runtime override"), dim("shunt fallback clear to restore"));
2511                        } else {
2512                            println!("  {} Fallback: {}  ·  {}", dim(DOT), bold(model), dim(&format!("from {source}")));
2513                        }
2514                    }
2515                }
2516                _ => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2517            }
2518        }
2519        Some(FallbackAction::Set { model }) => {
2520            let resp = client.post(&url).json(&serde_json::json!({ "fallback_model": model })).send().await;
2521            match resp {
2522                Ok(r) if r.status().is_success() => {
2523                    println!("  {} Fallback model set: {}  ·  {}", green(CHECK), bold(&model), dim("shunt fallback clear to restore"));
2524                }
2525                Ok(r) => { let body = r.text().await.unwrap_or_default(); anyhow::bail!("Proxy returned error: {body}"); }
2526                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2527            }
2528        }
2529        Some(FallbackAction::Off) => {
2530            let resp = client.post(&url).json(&serde_json::json!({ "fallback_model": null })).send().await;
2531            match resp {
2532                Ok(r) if r.status().is_success() => {
2533                    println!("  {} Fallback disabled  ·  {}", green(CHECK), dim("shunt fallback clear to restore"));
2534                }
2535                Ok(r) => { let body = r.text().await.unwrap_or_default(); anyhow::bail!("Proxy returned error: {body}"); }
2536                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2537            }
2538        }
2539        Some(FallbackAction::Clear) => {
2540            let resp = client.delete(&url).send().await;
2541            match resp {
2542                Ok(r) if r.status().is_success() => {
2543                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2544                    let source = v["source"].as_str().unwrap_or("auto");
2545                    let model = v["fallback_model"].as_str().unwrap_or("auto");
2546                    println!("  {} Fallback override cleared  ·  {}  ·  {}", green(CHECK), bold(model), dim(&format!("from {source}")));
2547                }
2548                Ok(r) => { let body = r.text().await.unwrap_or_default(); anyhow::bail!("Proxy returned error: {body}"); }
2549                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2550            }
2551        }
2552    }
2553    println!();
2554    Ok(())
2555}
2556
2557async fn cmd_effort(config_override: Option<PathBuf>, action: Option<EffortAction>) -> Result<()> {
2558    let config = crate::config::load_config(config_override.as_deref())?;
2559    let url = format!("http://{}:{}/effort", config.server.host, config.server.control_port);
2560    let client = reqwest::Client::new();
2561
2562    match action {
2563        None => {
2564            let resp = client.get(&url).send().await;
2565            match resp {
2566                Ok(r) if r.status().is_success() => {
2567                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2568                    let source = v["source"].as_str().unwrap_or("unknown");
2569                    if source == "override" {
2570                        let effort = v["effort"].as_str().unwrap_or("high");
2571                        println!("  {} Effort: {}  ·  {}  ·  {}", green(CHECK), bold(effort), dim("runtime override"), dim("shunt effort clear to restore"));
2572                    } else {
2573                        println!("  {} Effort: {}  ·  {}", dim(DOT), bold("passthrough"), dim("client requests unmodified"));
2574                    }
2575                }
2576                _ => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2577            }
2578        }
2579        Some(EffortAction::Set { level }) => {
2580            let resp = client.post(&url).json(&serde_json::json!({ "effort": level })).send().await;
2581            match resp {
2582                Ok(r) if r.status().is_success() => {
2583                    println!("  {} Effort set: {}  ·  {}", green(CHECK), bold(&level), dim("shunt effort clear to restore"));
2584                }
2585                Ok(r) => { let body = r.text().await.unwrap_or_default(); anyhow::bail!("Proxy returned error: {body}"); }
2586                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2587            }
2588        }
2589        Some(EffortAction::Clear) => {
2590            let resp = client.delete(&url).send().await;
2591            match resp {
2592                Ok(r) if r.status().is_success() => {
2593                    println!("  {} Effort override cleared  ·  {}", green(CHECK), dim("passthrough restored"));
2594                }
2595                Ok(r) => { let body = r.text().await.unwrap_or_default(); anyhow::bail!("Proxy returned error: {body}"); }
2596                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2597            }
2598        }
2599    }
2600    println!();
2601    Ok(())
2602}
2603
2604async fn cmd_thinking(config_override: Option<PathBuf>, action: Option<ThinkingAction>) -> Result<()> {
2605    let config = crate::config::load_config(config_override.as_deref())?;
2606    let url = format!("http://{}:{}/thinking", config.server.host, config.server.control_port);
2607    let client = reqwest::Client::new();
2608
2609    match action {
2610        None => {
2611            let resp = client.get(&url).send().await;
2612            match resp {
2613                Ok(r) if r.status().is_success() => {
2614                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2615                    let source = v["source"].as_str().unwrap_or("unknown");
2616                    if source == "override" {
2617                        let mode = v["thinking"].as_str().unwrap_or("adaptive");
2618                        let display = if mode == "disabled" { "off" } else { mode };
2619                        println!("  {} Thinking: {}  ·  {}  ·  {}", green(CHECK), bold(display), dim("runtime override"), dim("shunt thinking clear to restore"));
2620                    } else {
2621                        println!("  {} Thinking: {}  ·  {}", dim(DOT), bold("passthrough"), dim("client requests unmodified"));
2622                    }
2623                }
2624                _ => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2625            }
2626        }
2627        Some(ThinkingAction::Set { mode }) => {
2628            let api_mode = if mode == "off" { "disabled" } else { &mode };
2629            let resp = client.post(&url).json(&serde_json::json!({ "thinking": api_mode })).send().await;
2630            match resp {
2631                Ok(r) if r.status().is_success() => {
2632                    println!("  {} Thinking set: {}  ·  {}", green(CHECK), bold(&mode), dim("shunt thinking clear to restore"));
2633                }
2634                Ok(r) => { let body = r.text().await.unwrap_or_default(); anyhow::bail!("Proxy returned error: {body}"); }
2635                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2636            }
2637        }
2638        Some(ThinkingAction::Clear) => {
2639            let resp = client.delete(&url).send().await;
2640            match resp {
2641                Ok(r) if r.status().is_success() => {
2642                    println!("  {} Thinking override cleared  ·  {}", green(CHECK), dim("passthrough restored"));
2643                }
2644                Ok(r) => { let body = r.text().await.unwrap_or_default(); anyhow::bail!("Proxy returned error: {body}"); }
2645                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2646            }
2647        }
2648    }
2649    println!();
2650    Ok(())
2651}
2652
2653async fn cmd_alerts(config_override: Option<PathBuf>, action: Option<AlertsAction>) -> Result<()> {
2654    let config = crate::config::load_config(config_override.as_deref())?;
2655    let alerts_url = format!("http://{}:{}/alerts", config.server.host, config.server.control_port);
2656    let client = reqwest::Client::new();
2657
2658    match action {
2659        None => {
2660            let resp = client.get(&alerts_url).send().await;
2661            match resp {
2662                Ok(r) if r.status().is_success() => {
2663                    let v: serde_json::Value = r.json().await.unwrap_or_default();
2664                    if v["muted"].as_bool().unwrap_or(false) {
2665                        println!("  {} Alerts muted  ·  {}", yellow("!"), dim("shunt alerts unmute to re-enable"));
2666                    } else {
2667                        println!("  {} Alerts active  ·  {}", green(CHECK), dim("shunt alerts mute to suppress"));
2668                    }
2669                }
2670                _ => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2671            }
2672        }
2673        Some(AlertsAction::Mute) => {
2674            let resp = client
2675                .post(&alerts_url)
2676                .json(&serde_json::json!({ "muted": true }))
2677                .send()
2678                .await;
2679            match resp {
2680                Ok(r) if r.status().is_success() => {
2681                    println!("  {} Alerts muted  ·  {}", yellow("!"), dim("shunt alerts unmute to re-enable"));
2682                }
2683                Ok(r) => {
2684                    let body = r.text().await.unwrap_or_default();
2685                    anyhow::bail!("Proxy returned error: {body}");
2686                }
2687                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2688            }
2689        }
2690        Some(AlertsAction::Unmute) => {
2691            let resp = client
2692                .post(&alerts_url)
2693                .json(&serde_json::json!({ "muted": false }))
2694                .send()
2695                .await;
2696            match resp {
2697                Ok(r) if r.status().is_success() => {
2698                    println!("  {} Alerts active  ·  {}", green(CHECK), dim("notifications re-enabled"));
2699                }
2700                Ok(r) => {
2701                    let body = r.text().await.unwrap_or_default();
2702                    anyhow::bail!("Proxy returned error: {body}");
2703                }
2704                Err(_) => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2705            }
2706        }
2707    }
2708    println!();
2709    Ok(())
2710}
2711
2712async fn cmd_savings(config_override: Option<PathBuf>) -> Result<()> {
2713    let config = crate::config::load_config(config_override.as_deref())?;
2714    let url = format!("http://{}:{}/status", config.server.host, config.server.control_port);
2715
2716    let v: serde_json::Value = match reqwest::Client::new()
2717        .get(&url)
2718        .timeout(std::time::Duration::from_secs(2))
2719        .send()
2720        .await
2721    {
2722        Ok(r) if r.status().is_success() => r.json().await.unwrap_or_default(),
2723        _ => anyhow::bail!("Proxy is not running. Start with `shunt start`."),
2724    };
2725
2726    let s = &v["savings"];
2727    let today_usd   = s["today_cost_usd"].as_f64().unwrap_or(0.0);
2728    let week_usd    = s["week_cost_usd"].as_f64().unwrap_or(0.0);
2729    let alltime_usd = s["all_time_cost_usd"].as_f64().unwrap_or(0.0);
2730    let today_in    = s["today_input"].as_u64().unwrap_or(0);
2731    let today_out   = s["today_output"].as_u64().unwrap_or(0);
2732    let week_in     = s["week_input"].as_u64().unwrap_or(0);
2733    let week_out    = s["week_output"].as_u64().unwrap_or(0);
2734    let all_in      = s["all_time_input"].as_u64().unwrap_or(0);
2735    let all_out     = s["all_time_output"].as_u64().unwrap_or(0);
2736
2737    fn fmt_tok(n: u64) -> String {
2738        if n >= 1_000_000 { format!("{:.1}M", n as f64 / 1_000_000.0) }
2739        else if n >= 1_000 { format!("{:.1}K", n as f64 / 1_000.0) }
2740        else { n.to_string() }
2741    }
2742
2743    println!();
2744    if alltime_usd > 0.001 {
2745        println!("  {} shunt has saved you {}  ·  {}", green(CHECK), bold(&crate::pricing::fmt_cost(alltime_usd)), dim("vs public Claude API at list prices"));
2746    } else {
2747        println!("  {} {}  ·  {}", dim(DOT), bold("no savings tracked yet"), dim("make some requests and come back"));
2748    }
2749    println!();
2750    println!("  {:<18} {}  {}", dim("today"), crate::pricing::fmt_cost(today_usd), dim(&format!("{}in · {}out", fmt_tok(today_in), fmt_tok(today_out))));
2751    println!("  {:<18} {}  {}", dim("this week"), crate::pricing::fmt_cost(week_usd), dim(&format!("{}in · {}out", fmt_tok(week_in), fmt_tok(week_out))));
2752    println!("  {:<18} {}  {}", dim("all time"), bold(&crate::pricing::fmt_cost(alltime_usd)), dim(&format!("{}in · {}out", fmt_tok(all_in), fmt_tok(all_out))));
2753    println!();
2754    Ok(())
2755}
2756
2757/// Synchronously awaits a reqwest response to get its JSON.
2758fn futures_executor_hack(resp: reqwest::Response) -> Option<serde_json::Value> {
2759    tokio::task::block_in_place(|| {
2760        tokio::runtime::Handle::current().block_on(async {
2761            resp.json::<serde_json::Value>().await.ok()
2762        })
2763    })
2764}
2765
2766// ---------------------------------------------------------------------------
2767// Helpers
2768// ---------------------------------------------------------------------------
2769
2770/// Circuit shunt symbol: rectangle with wires extending left/right from the mid row,
2771/// and two legs going down from the bottom.
2772///
2773///   ·  ██████  ·
2774///   ███      ███   ← wire row (middle of box)
2775///   ·  ██████  ·
2776///   ·    █ █   ·   ← legs
2777fn build_logo_lines(h: usize, w: usize) -> Vec<String> {
2778    if h == 0 || w < 5 { return vec![]; }
2779
2780    let box_l = w / 4;
2781    let box_r = w - w / 4;  // exclusive
2782    let leg_h = (h / 4).max(1);
2783    let box_h = h.saturating_sub(leg_h).max(2); // at least top + bottom row
2784    let wire_row = box_h / 2; // wire connects at vertical mid of box
2785
2786    // Mirror from each side so legs are symmetric around centre.
2787    let leg1 = w / 3;
2788    let leg2 = w - w / 3 - 1;
2789
2790    let mut out = Vec::new();
2791    for row in 0..h {
2792        let mut r = vec![' '; w];
2793        if row < box_h {
2794            let is_top = row == 0;
2795            let is_bot = row == box_h - 1;
2796            if is_top || is_bot {
2797                for j in box_l..box_r { r[j] = '█'; }
2798            } else {
2799                r[box_l]     = '█';
2800                r[box_r - 1] = '█';
2801            }
2802            if row == wire_row {
2803                for j in 0..box_l  { r[j] = '█'; }
2804                for j in box_r..w  { r[j] = '█'; }
2805            }
2806        } else {
2807            if leg1 < w { r[leg1] = '█'; }
2808            if leg2 < w { r[leg2] = '█'; }
2809        }
2810        out.push(r.into_iter().collect());
2811    }
2812    out
2813}
2814
2815fn render_splash_frame(
2816    f: &mut ratatui::Frame,
2817    title_raw: &str,
2818    subtitle_raw: &str,
2819    right_lines: &[String],
2820) {
2821    use ratatui::{
2822        layout::{Constraint, Direction, Layout},
2823        style::{Color, Style},
2824        text::Line,
2825        widgets::{Block, Borders, Paragraph},
2826    };
2827
2828    let brand    = Color::Indexed(154); // #afd700 bright lime-green
2829    let dim_col  = Color::Indexed(240); // #585858 gray
2830    let dk_green = Color::Indexed(28);  // #008700 dark green
2831
2832    // Fixed-width box — does not stretch to fill the terminal.
2833    const BOX_W: u16 = 70;
2834    let full = f.area();
2835    let area = Layout::new(Direction::Horizontal, [
2836        Constraint::Length(BOX_W.min(full.width)),
2837        Constraint::Fill(1),
2838    ]).split(full)[0];
2839
2840    // Outer bordered box.
2841    let outer = Block::default()
2842        .borders(Borders::ALL)
2843        .border_style(Style::default().fg(dk_green))
2844        .title(Line::styled(format!(" {title_raw} "), Style::default().fg(brand)));
2845    let inner = outer.inner(area);
2846    f.render_widget(outer, area);
2847
2848    const CONTENT_H: u16 = 4;
2849    const LOGO_W:    u16 = 10;
2850
2851    // Main horizontal split: left half | separator | right half
2852    let cols = Layout::new(Direction::Horizontal, [
2853        Constraint::Fill(1),
2854        Constraint::Length(1),
2855        Constraint::Fill(1),
2856    ]).split(inner);
2857    let (left_area, sep_area, right_area) = (cols[0], cols[1], cols[2]);
2858
2859    // Left: vertical centering around the content row.
2860    let has_sub = !subtitle_raw.is_empty();
2861    let left_v_constraints: Vec<Constraint> = if has_sub {
2862        vec![Constraint::Fill(1), Constraint::Length(CONTENT_H), Constraint::Fill(1), Constraint::Length(1)]
2863    } else {
2864        vec![Constraint::Fill(1), Constraint::Length(CONTENT_H), Constraint::Fill(1)]
2865    };
2866    let left_v = Layout::new(Direction::Vertical, left_v_constraints).split(left_area);
2867    let content_row = left_v[1];
2868
2869    // Left content: logo centered horizontally within the left half
2870    let h = Layout::new(Direction::Horizontal, [
2871        Constraint::Fill(1),
2872        Constraint::Length(LOGO_W),
2873        Constraint::Fill(1),
2874    ]).split(content_row);
2875
2876    let logo = build_logo_lines(CONTENT_H as usize, LOGO_W as usize);
2877    f.render_widget(
2878        Paragraph::new(logo.into_iter()
2879            .map(|l| Line::styled(l, Style::default().fg(brand)))
2880            .collect::<Vec<_>>()),
2881        h[1],
2882    );
2883
2884    if has_sub {
2885        f.render_widget(
2886            Paragraph::new(subtitle_raw).style(Style::default().fg(dim_col)),
2887            left_v[3],
2888        );
2889    }
2890
2891    // Vertical separator spanning full inner height.
2892    let sep_lines: Vec<Line> = (0..sep_area.height)
2893        .map(|_| Line::styled("│", Style::default().fg(dk_green)))
2894        .collect();
2895    f.render_widget(Paragraph::new(sep_lines), sep_area);
2896
2897    // Right: custom lines (center-aligned) or static description (right-aligned).
2898    let static_desc: Vec<String> = vec![
2899        "Pool multiple AI coding agent".into(),
2900        "accounts behind a single endpoint.".into(),
2901        "Maximise rate limits across".into(),
2902        "all accounts automatically.".into(),
2903    ];
2904    let (desc_lines, alignment) = if right_lines.is_empty() {
2905        (static_desc.as_slice(), ratatui::layout::Alignment::Center)
2906    } else {
2907        (right_lines, ratatui::layout::Alignment::Center)
2908    };
2909    let desc: Vec<Line> = desc_lines.iter()
2910        .map(|s| Line::styled(s.clone(), Style::default().fg(dim_col)))
2911        .collect();
2912    let desc_h = desc.len() as u16;
2913    // 1-col left spacer so text doesn't touch the separator.
2914    let right_inner = Layout::new(Direction::Horizontal, [
2915        Constraint::Length(1),
2916        Constraint::Fill(1),
2917    ]).split(right_area)[1];
2918    let right_v = Layout::new(Direction::Vertical, [
2919        Constraint::Fill(1),
2920        Constraint::Length(desc_h),
2921        Constraint::Fill(1),
2922    ]).split(right_inner);
2923    f.render_widget(
2924        Paragraph::new(desc).alignment(alignment),
2925        right_v[1],
2926    );
2927}
2928
2929
2930/// Print the splash using ratatui inline viewport — redraws live on resize.
2931fn print_splash(info: &[String]) {
2932    use ratatui::{backend::CrosstermBackend, Terminal, TerminalOptions, Viewport};
2933    use crossterm::{event::{self, Event}, terminal as cterm};
2934    use std::io::stdout;
2935
2936    let title_raw    = info.get(0).map(|s| strip_ansi(s)).unwrap_or_default();
2937    let subtitle_raw = info.get(1).map(|s| strip_ansi(s)).unwrap_or_default();
2938
2939    // Logo = 4 rows content + 2 border + 2 vertical padding + optional subtitle
2940    let splash_h: u16 = 4 + 2 + 2 + if subtitle_raw.is_empty() { 0 } else { 1 };
2941
2942    let mut terminal = match Terminal::with_options(
2943        CrosstermBackend::new(stdout()),
2944        TerminalOptions { viewport: Viewport::Inline(splash_h) },
2945    ) {
2946        Ok(t) => t,
2947        Err(_) => {
2948            // Fallback: plain text header if ratatui fails (e.g. non-TTY).
2949            println!("\n  ◆  {}  {}\n", title_raw.trim(), subtitle_raw);
2950            return;
2951        }
2952    };
2953
2954    let draw = |t: &mut Terminal<CrosstermBackend<std::io::Stdout>>| {
2955        t.draw(|f| render_splash_frame(f, &title_raw, &subtitle_raw, &[])).ok();
2956    };
2957
2958    draw(&mut terminal);
2959
2960    // Redraw on resize for up to 500 ms.
2961    let _ = cterm::enable_raw_mode();
2962    let dl = std::time::Instant::now() + std::time::Duration::from_millis(500);
2963    loop {
2964        let rem = dl.saturating_duration_since(std::time::Instant::now());
2965        if rem.is_zero() { break; }
2966        if event::poll(rem).unwrap_or(false) {
2967            match event::read() {
2968                Ok(Event::Resize(_, _)) => draw(&mut terminal),
2969                _ => break,
2970            }
2971        } else { break; }
2972    }
2973    let _ = cterm::disable_raw_mode();
2974    let _ = terminal.show_cursor();
2975    // Ratatui leaves the cursor at the end of the inline viewport's last line.
2976    // \r resets to column 0 before \n moves down, so subsequent output is left-aligned.
2977    print!("\r\n");
2978}
2979
2980/// Like print_splash but with custom right-side lines (used by cmd_status).
2981///
2982/// Plain println-based box drawing — no ratatui/crossterm terminal state so
2983/// subsequent output is always left-aligned.
2984fn print_status_splash(title: &str, right_lines: Vec<String>) {
2985    use crate::term::{brand_green, dark_green, dim};
2986
2987    const BOX_W:     usize = 70; // visible width of the box (excluding indent)
2988    const LOGO_W:    usize = 10;
2989    const CONTENT_H: usize = 4;
2990
2991    let splash_h = (right_lines.len() + 4).max(8);
2992    let inner_h  = splash_h - 2;             // rows inside (between borders)
2993    let left_w   = (BOX_W - 3) / 2;          // left panel visible width  (33)
2994    let right_w  = BOX_W - 3 - left_w;       // right panel visible width (34)
2995
2996    // ── top border ──────────────────────────────────────────────────────
2997    let title_part = format!(" {title} ");
2998    let fill = BOX_W.saturating_sub(4 + title_part.len());
2999    print!("  {}", dark_green("┌─"));
3000    print!("{}", brand_green(&title_part));
3001    println!("{}", dark_green(&format!("{}─┐", "─".repeat(fill))));
3002
3003    // ── content rows ────────────────────────────────────────────────────
3004    let logo      = build_logo_lines(CONTENT_H, LOGO_W);
3005    let logo_top  = inner_h.saturating_sub(CONTENT_H) / 2;
3006    let right_top = inner_h.saturating_sub(right_lines.len()) / 2;
3007    let logo_lpad = left_w.saturating_sub(LOGO_W) / 2;
3008
3009    for row in 0..inner_h {
3010        // Left panel: logo centered vertically and horizontally
3011        let left_content: String = if row >= logo_top && row < logo_top + CONTENT_H {
3012            let lrow = logo.get(row - logo_top).map(|s| s.as_str()).unwrap_or("");
3013            let right_pad = left_w.saturating_sub(logo_lpad + LOGO_W);
3014            format!("{}{}{}", " ".repeat(logo_lpad), brand_green(lrow), " ".repeat(right_pad))
3015        } else {
3016            " ".repeat(left_w)
3017        };
3018
3019        // Right panel: lines centered vertically, left-aligned with padding
3020        let right_content: String = if row >= right_top && row < right_top + right_lines.len() {
3021            let rline = &right_lines[row - right_top];
3022            let lpad = right_w.saturating_sub(rline.len()) / 2;
3023            let rpad = right_w.saturating_sub(lpad.saturating_add(rline.len()));
3024            format!("{}{}{}", " ".repeat(lpad), dim(rline), " ".repeat(rpad))
3025        } else {
3026            " ".repeat(right_w)
3027        };
3028
3029        print!("  {}", dark_green("│"));
3030        print!("{left_content}");
3031        print!("{}", dark_green("│"));
3032        print!("{right_content}");
3033        println!("{}", dark_green("│"));
3034    }
3035
3036    // ── bottom border ───────────────────────────────────────────────────
3037    println!("  {}", dark_green(&format!("└{}┘", "─".repeat(BOX_W - 2))));
3038}
3039
3040// ---------------------------------------------------------------------------
3041// Account card helpers  (used by cmd_status)
3042// ---------------------------------------------------------------------------
3043
3044/// Target visible width for account header lines and separators.
3045const CARD_W: usize = 58;
3046
3047/// Account header: "  ◆  name  tag                     Plan"
3048fn card_header(name: &str, name_c: &str, routing_tag: &str, tag_vis: usize, plan: &str) -> String {
3049    // Visible prefix: "  ◆  " = 5, then name (name.len()), then tag (tag_vis)
3050    let left_vis = 5 + name.len() + tag_vis;
3051    let gap = CARD_W.saturating_sub(left_vis + plan.len());
3052    format!("  {}  {}{}{}{}", brand_green(DIAMOND), name_c, routing_tag, " ".repeat(gap), dim(plan))
3053}
3054
3055/// An indented content row: "    content"
3056fn card_row(content: &str) -> String {
3057    format!("    {content}")
3058}
3059
3060/// Thin separator line between accounts.
3061fn card_sep() -> String {
3062    format!("  {}", dim(&"─".repeat(CARD_W - 2)))
3063}
3064
3065/// Routing diagram — account names in bold green, connectors in dark green.
3066///
3067/// 1 account:           2 accounts:          3+ accounts:
3068///   main  ─→  [info]    main ─┐ →  [info]    main ─┐
3069///             [info1]   work ─┘     [info1]   work ─┼─→  [info]
3070///                                             sec  ─┘     [info1]
3071fn print_routing_header(account_names: &[&str], info: &[String]) {
3072    println!();
3073    let n = account_names.len();
3074    let name_w = account_names.iter().map(|s| s.len()).max().unwrap_or(4);
3075    let info0 = info.get(0).map(|s| s.as_str()).unwrap_or("");
3076    let info1 = info.get(1).map(|s| s.as_str()).unwrap_or("");
3077
3078    match n {
3079        0 => {
3080            // No accounts yet — clean two-line header
3081            println!("  {}  {}", brand_green(DIAMOND), info0);
3082            if !info1.is_empty() {
3083                println!("       {}", info1);
3084            }
3085        }
3086        1 => {
3087            // "  name  ─→  info0"  (info1 indented to same column)
3088            let indent = name_w + 8; // 2 + name + 2 + "─→" + 2
3089            println!("  {}  {}  {}", green_bold(account_names[0]), dark_green("─→"), info0);
3090            if !info1.is_empty() {
3091                println!("  {}{}", " ".repeat(indent), info1);
3092            }
3093        }
3094        2 => {
3095            // "  name0 ─┐ →  info0"
3096            // "  name1 ─┘     info1"
3097            println!("  {}  {} {}  {}",
3098                green_bold(&pad(account_names[0], name_w)),
3099                dark_green("─┐"), dark_green("→"), info0);
3100            println!("  {}  {}    {}",
3101                green_bold(&pad(account_names[1], name_w)),
3102                dark_green("─┘"), info1);
3103        }
3104        3 => {
3105            // "  name0 ─┐"
3106            // "  name1 ─┼─→  info0"
3107            // "  name2 ─┘     info1"
3108            println!("  {}  {}", green_bold(&pad(account_names[0], name_w)), dark_green("─┐"));
3109            println!("  {}  {}  {}",
3110                green_bold(&pad(account_names[1], name_w)),
3111                dark_green("─┼─→"), info0);
3112            println!("  {}  {}    {}",
3113                green_bold(&pad(account_names[2], name_w)),
3114                dark_green("─┘"), info1);
3115        }
3116        _ => {
3117            // "  name0      ─┐"
3118            // "  + N more   ─┼─→  info0"
3119            // "  nameN      ─┘     info1"
3120            let more = dim(&pad(&format!("+ {} more", n - 2), name_w));
3121            println!("  {}  {}", green_bold(&pad(account_names[0], name_w)), dark_green("─┐"));
3122            println!("  {}  {}  {}", more, dark_green("─┼─→"), info0);
3123            println!("  {}  {}    {}",
3124                green_bold(&pad(account_names[n - 1], name_w)),
3125                dark_green("─┘"), info1);
3126        }
3127    }
3128
3129    println!();
3130}
3131
3132/// Capacity bar — `util` is 0.0–1.0; filled blocks show REMAINING capacity.
3133/// Green = plenty left, yellow = getting low, red = nearly exhausted.
3134fn util_bar(util: f64, width: usize) -> String {
3135    let used = (util.clamp(0.0, 1.0) * width as f64).round() as usize;
3136    let free = width.saturating_sub(used);
3137    // filled = remaining, empty = used — so a full bar means lots of quota left
3138    let bar = format!("{}{}", "█".repeat(free), "░".repeat(used));
3139    let pct = (util * 100.0) as u64;
3140    if pct < 50 { green(&bar) } else if pct < 80 { yellow(&bar) } else { red(&bar) }
3141}
3142
3143/// Seconds until a Unix-epoch reset timestamp. Returns None if past or zero.
3144fn secs_until(epoch_secs: u64) -> Option<u64> {
3145    let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
3146    epoch_secs.checked_sub(now).filter(|&s| s > 0)
3147}
3148
3149// ---------------------------------------------------------------------------
3150// Multi-provider listener helpers
3151// ---------------------------------------------------------------------------
3152
3153/// Returns `(provider_label, url)` pairs for every provider present in accounts,
3154/// using `primary_port` for Anthropic and each provider's default port for others.
3155fn listener_addrs(
3156    accounts: &[crate::config::AccountConfig],
3157    host: &str,
3158    primary_port: u16,
3159) -> Vec<(String, String)> {
3160    use crate::provider::Provider;
3161    use std::collections::BTreeSet;
3162
3163    let providers: BTreeSet<String> = accounts.iter()
3164        .map(|a| a.provider.to_string())
3165        .collect();
3166
3167    providers.into_iter().map(|p| {
3168        let port = match Provider::from_str(&p) {
3169            Provider::Anthropic => primary_port,
3170            other => other.default_port(),
3171        };
3172        (p.clone(), format!("http://{host}:{port}"))
3173    }).collect()
3174}
3175
3176/// Bind a listener and spawn an axum server for each provider group found in
3177/// `config.accounts`. All servers run concurrently; the function returns when
3178/// the first one stops (error or clean shutdown).
3179async fn serve_all_providers(
3180    config: crate::config::Config,
3181    state: crate::state::StateStore,
3182    host: &str,
3183    primary_port: u16,
3184) -> anyhow::Result<()> {
3185    use crate::config::{Config, ServerConfig};
3186    use crate::provider::Provider;
3187    use std::collections::HashMap;
3188
3189    // Save all accounts for the control plane before the provider loop consumes them.
3190    let all_accounts = config.accounts.clone();
3191    let control_port = config.server.control_port;
3192
3193    tracing::info!(
3194        version = env!("CARGO_PKG_VERSION"),
3195        accounts = all_accounts.len(),
3196        port = primary_port,
3197        control_port,
3198        "shunt proxy started"
3199    );
3200
3201    // Group accounts by provider.
3202    let mut by_provider: HashMap<String, Vec<crate::config::AccountConfig>> = HashMap::new();
3203    for account in config.accounts {
3204        by_provider.entry(account.provider.to_string()).or_default().push(account);
3205    }
3206
3207    // Shared shutdown signal — fired on SIGTERM so every axum server drains
3208    // in-flight connections, state is flushed, then the process exits cleanly.
3209    let shutdown = std::sync::Arc::new(tokio::sync::Notify::new());
3210
3211    // SIGTERM handler: flush state then wake all servers.
3212    {
3213        let state_s = state.clone();
3214        let notify  = shutdown.clone();
3215        tokio::spawn(async move {
3216            #[cfg(unix)]
3217            {
3218                if let Ok(mut sig) = tokio::signal::unix::signal(
3219                    tokio::signal::unix::SignalKind::terminate(),
3220                ) {
3221                    sig.recv().await;
3222                    tracing::info!("SIGTERM received — flushing state before shutdown");
3223                    state_s.flush_sync();
3224                    notify.notify_waiters();
3225                }
3226            }
3227            #[cfg(not(unix))]
3228            std::future::pending::<()>().await
3229        });
3230    }
3231
3232    let mut handles = Vec::new();
3233
3234    for (provider_str, accounts) in by_provider {
3235        let provider = Provider::from_str(&provider_str);
3236        let port = match provider {
3237            Provider::Anthropic => primary_port,
3238            ref other => other.default_port(),
3239        };
3240
3241        // The Anthropic proxy gets ALL accounts so non-Anthropic accounts (e.g. codex/chatgpt.com)
3242        // act as fallback when Anthropic accounts are exhausted. Each non-Anthropic account already
3243        // has upstream_url pre-populated (e.g. "https://chatgpt.com") by the config loader.
3244        let proxy_accounts = if provider == Provider::Anthropic {
3245            all_accounts.clone()
3246        } else {
3247            accounts
3248        };
3249
3250        let provider_config = Config {
3251            accounts: proxy_accounts,
3252            server: ServerConfig {
3253                host: host.to_owned(),
3254                port,
3255                upstream_url: provider.default_upstream_url().to_owned(),
3256                ..config.server.clone()
3257            },
3258            config_file: config.config_file.clone(),
3259            model_mapping: config.model_mapping.clone(),
3260        };
3261
3262        let anthropic_url = if provider == Provider::OpenAI {
3263            Some(format!("http://{}:{}", host, primary_port))
3264        } else {
3265            None
3266        };
3267        let (app, live_creds) = crate::proxy::create_proxy_app(provider_config.clone(), state.clone(), anthropic_url)?;
3268        let listener = tokio::net::TcpListener::bind(format!("{host}:{port}"))
3269            .await
3270            .with_context(|| format!("cannot bind {host}:{port} for {provider_str} proxy"))?;
3271
3272        let cfg_arc = std::sync::Arc::new(provider_config);
3273        tokio::spawn(crate::proxy::prefetch_rate_limits(cfg_arc.clone(), state.clone(), live_creds.clone()));
3274        tokio::spawn(crate::proxy::openai_token_refresh_loop(cfg_arc.clone(), state.clone(), live_creds.clone()));
3275        tokio::spawn(crate::proxy::cooldown_watcher(cfg_arc.clone(), state.clone(), live_creds.clone()));
3276        tokio::spawn(crate::proxy::recovery_watcher(cfg_arc.clone(), state.clone(), live_creds.clone()));
3277        tokio::spawn(crate::proxy::health_check_loop(cfg_arc, state.clone(), live_creds));
3278        let sd = shutdown.clone();
3279        handles.push(tokio::spawn(async move {
3280            axum::serve(listener, app)
3281                .with_graceful_shutdown(async move { sd.notified().await })
3282                .await
3283        }));
3284    }
3285
3286    // Spawn the control plane — management endpoints with visibility into ALL accounts.
3287    let control_config = Config {
3288        accounts: all_accounts,
3289        server: ServerConfig {
3290            host: host.to_owned(),
3291            port: control_port,
3292            upstream_url: "https://api.anthropic.com".to_owned(),
3293            ..config.server.clone()
3294        },
3295        config_file: config.config_file.clone(),
3296        model_mapping: config.model_mapping.clone(),
3297    };
3298    let control_app = crate::proxy::create_control_app(control_config.clone(), state.clone())?;
3299    let control_listener = tokio::net::TcpListener::bind(format!("{host}:{control_port}"))
3300        .await
3301        .with_context(|| format!("cannot bind {host}:{control_port} for control plane"))?;
3302    let sd = shutdown.clone();
3303    handles.push(tokio::spawn(async move {
3304        axum::serve(control_listener, control_app)
3305            .with_graceful_shutdown(async move { sd.notified().await })
3306            .await
3307    }));
3308
3309    // Spawn settings guardian — re-injects ANTHROPIC_BASE_URL into ~/.claude/settings.json
3310    // if a Claude Code re-login overwrites it while the daemon is running.
3311    tokio::spawn(settings_guardian_loop(primary_port));
3312
3313    // Spawn heartbeat loop if telemetry is configured.
3314    if let Some(telemetry_url) = config.server.telemetry_url.clone() {
3315        let telem = crate::telemetry::TelemetryClient::new(
3316            &telemetry_url,
3317            config.server.telemetry_token.clone(),
3318            config.server.instance_name.clone(),
3319        );
3320        let state_hb  = state.clone();
3321        let config_hb = std::sync::Arc::new(control_config);
3322        let started   = std::time::SystemTime::now()
3323            .duration_since(std::time::UNIX_EPOCH)
3324            .unwrap_or_default()
3325            .as_millis() as u64;
3326        tokio::spawn(async move {
3327            let mut interval = tokio::time::interval(std::time::Duration::from_secs(30));
3328            loop {
3329                interval.tick().await;
3330                let snapshot = crate::proxy::build_status_snapshot(&config_hb, &state_hb, started);
3331                telem.push_heartbeat(snapshot).await;
3332            }
3333        });
3334    }
3335
3336    if handles.is_empty() {
3337        return Ok(());
3338    }
3339
3340    // Wait until the first listener stops, then exit (whole daemon restarts on error).
3341    let (result, _idx, _rest) = futures_util::future::select_all(handles).await;
3342    result??;
3343    Ok(())
3344}
3345
3346fn write_pid() {
3347    let p = pid_path();
3348    if let Some(dir) = p.parent() { let _ = std::fs::create_dir_all(dir); }
3349    let _ = std::fs::write(&p, std::process::id().to_string());
3350}
3351
3352/// PIDs of processes listening on the given port.
3353fn port_pids(port: u16) -> Vec<u32> {
3354    let out = std::process::Command::new("lsof")
3355        .args(["-ti", &format!(":{port}")])
3356        .output();
3357    let Ok(out) = out else { return vec![] };
3358    String::from_utf8_lossy(&out.stdout)
3359        .split_whitespace()
3360        .filter_map(|s| s.parse().ok())
3361        .collect()
3362}
3363
3364#[allow(dead_code)]
3365fn kill_port(port: u16) -> bool {
3366    let pids = port_pids(port);
3367    let mut any = false;
3368    for pid in pids {
3369        if std::process::Command::new("kill").arg(pid.to_string()).status().map(|s| s.success()).unwrap_or(false) {
3370            any = true;
3371        }
3372    }
3373    any
3374}
3375
3376/// Pad a string to display width using spaces (strips ANSI codes first; handles Unicode).
3377fn pad(s: &str, width: usize) -> String {
3378    use unicode_width::UnicodeWidthStr;
3379    let visible_width = UnicodeWidthStr::width(strip_ansi(s).as_str());
3380    if visible_width >= width {
3381        s.to_owned()
3382    } else {
3383        format!("{s}{}", " ".repeat(width - visible_width))
3384    }
3385}
3386
3387fn strip_ansi(s: &str) -> String {
3388    let mut out = String::with_capacity(s.len());
3389    let mut chars = s.chars().peekable();
3390    while let Some(c) = chars.next() {
3391        if c == '\x1b' {
3392            if chars.peek() == Some(&'[') {
3393                chars.next();
3394                while let Some(&next) = chars.peek() {
3395                    chars.next();
3396                    if next.is_ascii_alphabetic() { break; }
3397                }
3398            }
3399        } else {
3400            out.push(c);
3401        }
3402    }
3403    out
3404}
3405
3406// ---------------------------------------------------------------------------
3407// monitor
3408// ---------------------------------------------------------------------------
3409
3410async fn cmd_monitor(config_override: Option<PathBuf>) -> Result<()> {
3411    let client = reqwest::Client::new();
3412
3413    // If ANTHROPIC_BASE_URL points to a remote shunt (written by `shunt connect`),
3414    // always use that — the user intends to monitor the host machine, not local.
3415    let remote_base = std::env::var("ANTHROPIC_BASE_URL").ok()
3416        .filter(|u| !u.contains("127.0.0.1") && !u.contains("localhost"))
3417        .map(|u| u.trim_end_matches('/').to_owned());
3418
3419    let base_url = if let Some(remote) = remote_base {
3420        remote
3421    } else {
3422        // Local mode: use the control port.
3423        let config = crate::config::load_config(config_override.as_deref())?;
3424        let local = format!("http://{}:{}", config.server.host, config.server.control_port);
3425        let running = client.get(format!("{local}/health"))
3426            .timeout(std::time::Duration::from_secs(3))
3427            .send().await.is_ok();
3428        if !running {
3429            println!();
3430            println!("  {} Proxy is not running.", red(CROSS));
3431            println!("  {} Start it first with {}.", dim("·"), cyan("shunt start"));
3432            println!();
3433            return Ok(());
3434        }
3435        local
3436    };
3437
3438    crate::monitor::run_monitor(&base_url).await
3439}
3440
3441// ---------------------------------------------------------------------------
3442// remote
3443// ---------------------------------------------------------------------------
3444
3445// update
3446// ---------------------------------------------------------------------------
3447
3448async fn cmd_update() -> Result<()> {
3449    const REPO: &str = "ramc10/shunt";
3450    let current = env!("CARGO_PKG_VERSION");
3451
3452    print_splash(&[
3453        format!("{}  {}", brand_green("shunt"), dim(&format!("v{current}"))),
3454    ]);
3455
3456    // Each status line is prefixed with \r so it starts at column 0 regardless
3457    // of where the cursor was left after the ratatui inline viewport.
3458    macro_rules! status {
3459        ($($arg:tt)*) => { println!("\r{}", format_args!($($arg)*)) };
3460    }
3461
3462    status!("  {} Checking for updates…", dim("·"));
3463
3464    // Fetch latest release from GitHub API
3465    let client = reqwest::Client::builder()
3466        .user_agent("shunt-updater")
3467        .connect_timeout(std::time::Duration::from_secs(10))
3468        .timeout(std::time::Duration::from_secs(120))
3469        .build()?;
3470
3471    let api_url = format!("https://api.github.com/repos/{REPO}/releases/latest");
3472    let resp = client.get(&api_url).send().await
3473        .context("Failed to reach GitHub API")?;
3474
3475    if !resp.status().is_success() {
3476        bail!("GitHub API returned {}", resp.status());
3477    }
3478
3479    let json: serde_json::Value = resp.json().await?;
3480    let latest_tag = json["tag_name"].as_str().context("Missing tag_name in release")?;
3481    let latest = latest_tag.trim_start_matches('v');
3482
3483    // Compare versions numerically to correctly handle both upgrades and the
3484    // case where the installed build is newer than the latest GitHub release.
3485    if parse_version(latest) <= parse_version(current) {
3486        status!("  {} Already up to date ({})", green(CHECK), bold(&format!("v{current}")));
3487        println!();
3488        return Ok(());
3489    }
3490
3491    status!("  {} Update available: {}  →  {}", green("↑"),
3492        dim(&format!("v{current}")), bold_white(&format!("v{latest}")));
3493    println!();
3494
3495    // Detect platform
3496    let target = detect_update_target()?;
3497    let archive_name = format!("shunt-v{latest}-{target}.tar.gz");
3498    let url = format!(
3499        "https://github.com/{REPO}/releases/download/v{latest}/{archive_name}"
3500    );
3501
3502    print!("\r  {} Downloading {}… ", dim("↓"), dim(&archive_name));
3503    use std::io::Write as _;
3504    std::io::stdout().flush().ok();
3505
3506    let resp = client.get(&url).send().await
3507        .context("Download request failed")?;
3508
3509    if !resp.status().is_success() {
3510        bail!("Download failed: HTTP {} for {url}", resp.status());
3511    }
3512
3513    let bytes = resp.bytes().await
3514        .context("Failed to read download")?;
3515
3516    // #4: Verify checksum before trusting the download.
3517    let base_url = format!("https://github.com/{REPO}/releases/download/v{latest}");
3518    let checksum_url = format!("{base_url}/checksums.txt");
3519    match client.get(&checksum_url).send().await {
3520        Ok(cr) if cr.status().is_success() => {
3521            use sha2::{Sha256, Digest};
3522            let checksums_text = cr.text().await.context("Failed to read checksums")?;
3523            let expected_hash = checksums_text.lines()
3524                .find(|l| l.contains(&archive_name))
3525                .and_then(|l| l.split_whitespace().next())
3526                .context("Checksum not found for this artifact — cannot verify download")?;
3527            let actual_hash = hex::encode(Sha256::digest(&bytes));
3528            if actual_hash != expected_hash {
3529                bail!("Checksum mismatch! Expected {expected_hash}, got {actual_hash}. Aborting update.");
3530            }
3531            status!("  {} Checksum verified", green(CHECK));
3532        }
3533        _ => {
3534            // checksums.txt not yet published — warn but continue.
3535            status!("  {} Warning: no checksums.txt found for this release — skipping integrity check", yellow("!"));
3536        }
3537    }
3538
3539    // Sanity-check: gzip magic bytes are 0x1f 0x8b
3540    if bytes.len() < 2 || bytes[0] != 0x1f || bytes[1] != 0x8b {
3541        bail!(
3542            "Downloaded file does not look like a gzip archive ({} bytes, first bytes: {:02x?})",
3543            bytes.len(), &bytes[..bytes.len().min(4)]
3544        );
3545    }
3546
3547    println!("{}", green("done"));
3548
3549    // Extract binary from tarball into a temp file next to the current exe
3550    let exe_path = std::env::current_exe().context("Cannot locate current executable")?;
3551    let tmp_path = exe_path.with_extension("tmp");
3552
3553    // #13 TOCTOU: remove any pre-existing file or symlink before writing,
3554    // so we don't follow an attacker-placed symlink to an arbitrary path.
3555    if tmp_path.symlink_metadata().is_ok() {
3556        std::fs::remove_file(&tmp_path)
3557            .context("Failed to remove stale temp file (possible symlink attack?)")?;
3558    }
3559
3560    extract_binary_from_tarball(&bytes, &tmp_path)
3561        .context("Failed to extract binary from archive")?;
3562
3563    #[cfg(unix)]
3564    {
3565        use std::os::unix::fs::PermissionsExt;
3566        std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o755))?;
3567    }
3568
3569    // macOS: clear ALL extended attributes (quarantine + provenance) then ad-hoc
3570    // sign the temp file BEFORE replacing the live binary so Gatekeeper never
3571    // sees an unsigned/quarantined binary on disk even if killed mid-update.
3572    #[cfg(target_os = "macos")]
3573    {
3574        let p = tmp_path.display().to_string();
3575        // -c clears all xattrs including com.apple.provenance (not just quarantine)
3576        std::process::Command::new("xattr").args(["-c", &p])
3577            .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().ok();
3578        std::process::Command::new("codesign").args(["--force", "--deep", "--sign", "-", &p])
3579            .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().ok();
3580    }
3581
3582    // Atomic replace — new binary is already signed, so this is safe.
3583    std::fs::rename(&tmp_path, &exe_path)
3584        .context("Failed to replace binary (try running with sudo?)")?;
3585
3586    // macOS: codesign the final path too — rename can reset Gatekeeper state on
3587    // some macOS versions (Sonoma+), so re-sign after the rename to be sure.
3588    #[cfg(target_os = "macos")]
3589    {
3590        let p = exe_path.display().to_string();
3591        std::process::Command::new("xattr").args(["-c", &p])
3592            .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().ok();
3593        std::process::Command::new("codesign").args(["--force", "--deep", "--sign", "-", &p])
3594            .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().ok();
3595    }
3596
3597    status!("  {} Updated to {}", green(CHECK), bold_white(&format!("v{latest}")));
3598    println!();
3599
3600    // If the daemon is running an older version, offer to restart it.
3601    let config = crate::config::load_config(None).ok();
3602    if let Some(cfg) = config {
3603        let health_url = format!("http://{}:{}/health", cfg.server.host, cfg.server.control_port);
3604        if let Ok(r) = reqwest::Client::new()
3605            .get(&health_url)
3606            .timeout(std::time::Duration::from_secs(2))
3607            .send().await
3608        {
3609            if let Ok(v) = r.json::<serde_json::Value>().await {
3610                let daemon_ver = v["version"].as_str().unwrap_or("");
3611                // If version field is missing, it's a pre-v0.1.137 daemon — treat as outdated.
3612                let is_outdated = daemon_ver.is_empty() || parse_version(daemon_ver) < parse_version(latest);
3613                if is_outdated {
3614                    let ver_display = if daemon_ver.is_empty() { "old version".to_owned() } else { format!("v{daemon_ver}") };
3615                    println!("  {} Daemon is still running {}. Restart now? [Y/n] ",
3616                        yellow("!"), dim(&ver_display));
3617                    let mut input = String::new();
3618                    std::io::stdin().read_line(&mut input).ok();
3619                    let input = input.trim().to_lowercase();
3620                    if input.is_empty() || input == "y" || input == "yes" {
3621                        println!();
3622                        cmd_restart(None).await?;
3623                    }
3624                }
3625            }
3626        }
3627    }
3628
3629    Ok(())
3630}
3631
3632/// Parse a "major.minor.patch" version string into a comparable tuple.
3633/// Missing components default to 0.
3634fn parse_version(s: &str) -> (u32, u32, u32) {
3635    let mut it = s.split('.');
3636    let maj = it.next().and_then(|p| p.parse().ok()).unwrap_or(0);
3637    let min = it.next().and_then(|p| p.parse().ok()).unwrap_or(0);
3638    let pat = it.next().and_then(|p| p.parse().ok()).unwrap_or(0);
3639    (maj, min, pat)
3640}
3641
3642fn detect_update_target() -> Result<&'static str> {
3643    match (std::env::consts::OS, std::env::consts::ARCH) {
3644        ("macos",  "aarch64") => Ok("aarch64-apple-darwin"),
3645        ("linux",  "x86_64")  => Ok("x86_64-unknown-linux-gnu"),
3646        ("linux",  "aarch64") => Ok("aarch64-unknown-linux-gnu"),
3647        (os, arch) => bail!("No pre-built binary for {os}/{arch}. Build from source: cargo install shunt-proxy"),
3648    }
3649}
3650
3651fn extract_binary_from_tarball(data: &[u8], dest: &std::path::Path) -> Result<()> {
3652    let gz = flate2::read::GzDecoder::new(data);
3653    let mut archive = tar::Archive::new(gz);
3654    for entry in archive.entries()? {
3655        let mut entry = entry?;
3656        let path = entry.path()?;
3657        // Reject path traversal attempts
3658        if path.components().any(|c| c == std::path::Component::ParentDir) {
3659            bail!("Unsafe path in archive: {:?}", path);
3660        }
3661        // Reject symlinks and directories — only plain files allowed
3662        let entry_type = entry.header().entry_type();
3663        if entry_type.is_symlink() || entry_type.is_hard_link() || entry_type.is_dir() {
3664            continue;
3665        }
3666        if path.file_name().and_then(|n| n.to_str()) == Some("shunt") {
3667            let mut out = std::fs::File::create(dest)?;
3668            std::io::copy(&mut entry, &mut out)?;
3669            return Ok(());
3670        }
3671    }
3672    bail!("Binary 'shunt' not found in archive")
3673}
3674
3675// ---------------------------------------------------------------------------
3676// share
3677// ---------------------------------------------------------------------------
3678
3679async fn cmd_share(config_override: Option<PathBuf>, tunnel: bool, stop: bool) -> Result<()> {
3680    let config_p = config_override.unwrap_or_else(config_path);
3681    if !config_p.exists() {
3682        bail!("No config found. Run `shunt setup` first.");
3683    }
3684
3685    let text = std::fs::read_to_string(&config_p)?;
3686
3687    // If no flags given, show interactive menu
3688    // use an enum to track the chosen mode cleanly
3689    #[derive(Debug)]
3690    enum ShareMode { Lan, Tunnel, CustomDomain, Stop }
3691
3692    let mode: ShareMode = if tunnel {
3693        ShareMode::Tunnel
3694    } else if stop {
3695        ShareMode::Stop
3696    } else {
3697        print_splash(&[
3698            format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
3699            dim("Remote sharing").to_string(),
3700            String::new(),
3701        ]);
3702        let top_items = vec![
3703            term::SelectItem {
3704                label: format!("{}  {}", bold("Local network (LAN)"),
3705                    dim("— same Wi-Fi only, no internet required")),
3706                value: "lan".into(),
3707            },
3708            term::SelectItem {
3709                label: format!("{}  {}", bold("Online"),
3710                    dim("— share over the internet")),
3711                value: "online".into(),
3712            },
3713            term::SelectItem {
3714                label: format!("{}  {}", bold("Stop sharing"),
3715                    dim("— revert to localhost-only")),
3716                value: "stop".into(),
3717            },
3718        ];
3719        match term::select("How do you want to share?", &top_items, 0).as_deref() {
3720            Some("lan")    => ShareMode::Lan,
3721            Some("stop")   => ShareMode::Stop,
3722            Some("online") => {
3723                // Sub-menu: temporary vs custom domain
3724                let existing_domain = crate::config::load_config(Some(&config_p))
3725                    .ok()
3726                    .and_then(|c| c.server.custom_domain.clone());
3727                let domain_label = match &existing_domain {
3728                    Some(d) => format!("{}  {}",
3729                        bold("Permanent (named Cloudflare tunnel)"),
3730                        dim(&format!("— {} · auto-setup DNS + tunnel", d))),
3731                    None => format!("{}  {}",
3732                        bold("Permanent (named Cloudflare tunnel)"),
3733                        dim("— your domain, auto-setup DNS + tunnel, always-on")),
3734                };
3735                let online_items = vec![
3736                    term::SelectItem {
3737                        label: format!("{}  {}",
3738                            bold("Temporary (Cloudflare tunnel)"),
3739                            dim("— free, random URL, session only")),
3740                        value: "tunnel".into(),
3741                    },
3742                    term::SelectItem {
3743                        label: domain_label,
3744                        value: "custom".into(),
3745                    },
3746                ];
3747                match term::select("Online sharing type:", &online_items, 0).as_deref() {
3748                    Some("tunnel") => ShareMode::Tunnel,
3749                    Some("custom") => ShareMode::CustomDomain,
3750                    _ => return Ok(()),
3751                }
3752            }
3753            _ => return Ok(()),
3754        }
3755    };
3756
3757    if matches!(mode, ShareMode::Stop) {
3758        // Reconfirm before disabling
3759        if !term::confirm("Stop sharing and revert to localhost-only?") {
3760            println!("  {} Cancelled.", dim("·"));
3761            println!();
3762            return Ok(());
3763        }
3764
3765        let mut doc = text.parse::<toml_edit::DocumentMut>()
3766            .context("Failed to parse config as TOML")?;
3767        if let Some(server) = doc.get_mut("server").and_then(|t| t.as_table_mut()) {
3768            server.remove("remote_key");
3769            server.insert("host", toml_edit::value("127.0.0.1"));
3770        }
3771        write_config_atomic(&config_p, &doc.to_string())?;
3772
3773        print_splash(&[
3774            format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
3775            dim("Remote sharing disabled").to_string(),
3776            String::new(),
3777        ]);
3778        println!("  {} Restart to apply: {}", dim("·"), cyan("shunt start"));
3779        println!();
3780        return Ok(());
3781    }
3782
3783    // #5: remote_key — read from env var first, then legacy config entry.
3784    // New keys are printed for the user to save; never written to config.
3785    let key = if let Ok(k) = std::env::var("SHUNT_REMOTE_KEY") {
3786        if !k.is_empty() { k } else { extract_remote_key(&text).unwrap_or_else(generate_remote_key) }
3787    } else if let Some(k) = extract_remote_key(&text) {
3788        // Existing config entry — keep using it, but nudge migration
3789        println!("  {} remote_key found in config.toml (plaintext).", yellow("!"));
3790        println!("  {} Migrate to an env var for better security:", dim("·"));
3791        println!("       export SHUNT_REMOTE_KEY='{k}'");
3792        println!();
3793        k
3794    } else {
3795        let k = generate_remote_key();
3796        println!();
3797        println!("  {} Generated remote key (save this in your env):", dim("·"));
3798        println!("       export SHUNT_REMOTE_KEY='{k}'");
3799        println!("  {} Add that line to your shell profile.", dim("·"));
3800        println!();
3801        k
3802    };
3803
3804    // Ensure host is 0.0.0.0
3805    {
3806        let mut doc = text.parse::<toml_edit::DocumentMut>()
3807            .context("Failed to parse config as TOML")?;
3808        if let Some(server) = doc.get_mut("server").and_then(|t| t.as_table_mut()) {
3809            server.insert("host", toml_edit::value("0.0.0.0"));
3810        }
3811        write_config_atomic(&config_p, &doc.to_string())?;
3812    }
3813
3814    let (port, relay_url, saved_domain) = match crate::config::load_config(Some(&config_p)) {
3815        Ok(cfg) => {
3816            let relay = std::env::var("SHUNT_RELAY_URL")
3817                .unwrap_or_else(|_| cfg.server.relay_url.clone());
3818            (cfg.server.port, relay, cfg.server.custom_domain)
3819        }
3820        Err(_) => (8082u16,
3821            std::env::var("SHUNT_RELAY_URL")
3822                .unwrap_or_else(|_| "https://relay.ramcharan.shop".to_string()),
3823            None),
3824    };
3825
3826    if !relay_url.starts_with("https://") {
3827        bail!("Relay URL must use HTTPS (got: {relay_url})");
3828    }
3829
3830    match mode {
3831        ShareMode::Tunnel => {
3832            print_splash(&[
3833                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
3834                dim("Starting Cloudflare tunnel…").to_string(),
3835                String::new(),
3836            ]);
3837            println!("  {} Make sure the proxy is running: {}", dim("·"), cyan("shunt start"));
3838            println!();
3839
3840            let url = start_cloudflare_tunnel(port)?;
3841            share_and_print(&url, &key, &relay_url, "Tunnel active", &[
3842                format!("  {} Code expires in 10 minutes — one-time use", dim("·")),
3843                format!("  {} Tunnel is active — keep this terminal open.", dim("·")),
3844                format!("  {} Press Ctrl+C to stop.", dim("·")),
3845            ]).await;
3846
3847            tokio::signal::ctrl_c().await.ok();
3848            println!("\n  {} Tunnel closed.", dim("·"));
3849        }
3850
3851        ShareMode::CustomDomain => {
3852            // Step 1: ensure cloudflared is available (downloads if needed)
3853            ensure_cloudflared()?;
3854
3855            // Step 2: resolve domain (use saved, or prompt + save)
3856            let domain = if let Some(d) = saved_domain {
3857                d
3858            } else {
3859                use std::io::Write;
3860                println!();
3861                println!("  {} Enter your domain URL (e.g. {}): ",
3862                    dim("·"), dim("https://shunt.mysite.com"));
3863                print!("    ");
3864                std::io::stdout().flush()?;
3865                let mut input = String::new();
3866                std::io::stdin().read_line(&mut input)?;
3867                let domain = input.trim().trim_end_matches('/').to_string();
3868                if domain.is_empty() { bail!("No domain entered."); }
3869                let _ = url::Url::parse(&domain).context("Invalid domain URL")?;
3870                if !domain.starts_with("https://") {
3871                    bail!("Domain must use HTTPS (got: {domain})");
3872                }
3873                let mut doc = std::fs::read_to_string(&config_p)?
3874                    .parse::<toml_edit::DocumentMut>()
3875                    .context("Failed to parse config as TOML")?;
3876                if let Some(server) = doc.get_mut("server").and_then(|t| t.as_table_mut()) {
3877                    server.insert("custom_domain", toml_edit::value(&domain));
3878                }
3879                write_config_atomic(&config_p, &doc.to_string())?;
3880                println!("  {} Saved {} to config.", green(CHECK), cyan(&domain));
3881                domain
3882            };
3883
3884            // Steps 2-6: auto-setup DNS + start named tunnel (fully CLI, no browser)
3885            start_named_cloudflare_tunnel(&domain, port, &config_p)?;
3886
3887            share_and_print(&domain, &key, &relay_url, "Permanent tunnel active", &[
3888                format!("  {} Code expires in 10 minutes — one-time use", dim("·")),
3889                format!("  {} Tunnel is active at {} — keep this terminal open.", dim("·"), cyan(&domain)),
3890                format!("  {} Press Ctrl+C to stop.", dim("·")),
3891            ]).await;
3892
3893            tokio::signal::ctrl_c().await.ok();
3894            println!("\n  {} Tunnel closed.", dim("·"));
3895        }
3896
3897        ShareMode::Lan => {
3898            let ip = local_ip().unwrap_or_else(|| "<your-ip>".to_string());
3899            let base_url = format!("http://{ip}:{port}");
3900
3901            share_and_print(&base_url, &key, &relay_url, "Remote sharing enabled (LAN)", &[
3902                format!("  {} Code expires in 10 minutes — one-time use", dim("·")),
3903                format!("  {} Both devices must be on the same network.", dim("·")),
3904                format!("  {} Restart to apply: {}", dim("·"), cyan("shunt start")),
3905                format!("  {} To stop sharing:  {}", dim("·"), cyan("shunt share --stop")),
3906            ]).await;
3907        }
3908
3909        ShareMode::Stop => unreachable!(),
3910    }
3911
3912    Ok(())
3913}
3914
3915/// Push share code to relay and print the result (code or fallback manual instructions).
3916async fn share_and_print(base_url: &str, key: &str, relay_url: &str, subtitle: &str, hints: &[String]) {
3917    let share_code = crate::sync::generate_share_code();
3918    match crate::sync::push_share(&share_code, base_url, key, relay_url).await {
3919        Ok(()) => {
3920            print_splash(&[
3921                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
3922                dim(subtitle).to_string(),
3923                String::new(),
3924            ]);
3925            println!("  {}  Share code:\n", green(CHECK));
3926            println!("      {}\n", cyan(&share_code));
3927            println!("  {} On the other device, run:", dim("·"));
3928            println!("       {}", cyan(&format!("shunt share {share_code}")));
3929            println!();
3930            for hint in hints { println!("{hint}"); }
3931            println!();
3932        }
3933        Err(e) => {
3934            // Relay unavailable — fall back to manual env var instructions
3935            print_splash(&[
3936                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
3937                dim(subtitle).to_string(),
3938                String::new(),
3939            ]);
3940            println!("  {} Relay unavailable ({e}).", dim("·"));
3941            println!("  {} Set on the remote device:", dim("·"));
3942            println!("      {}{}", dim("export ANTHROPIC_BASE_URL="), cyan(base_url));
3943            println!();
3944            for hint in hints { println!("{hint}"); }
3945            println!();
3946        }
3947    }
3948}
3949
3950/// Ensure `cloudflared` is available in PATH or a local bin dir.
3951/// Downloads the binary automatically if not found.
3952fn ensure_cloudflared() -> Result<String> {
3953    use std::process::Command;
3954
3955    // Check if it's already in PATH
3956    if Command::new("cloudflared")
3957        .arg("--version")
3958        .stdout(std::process::Stdio::null())
3959        .stderr(std::process::Stdio::null())
3960        .status().is_ok()
3961    {
3962        return Ok("cloudflared".to_string());
3963    }
3964
3965    // Not found — download to ~/.local/bin/cloudflared
3966    let local_bin = dirs::home_dir()
3967        .context("Cannot find home directory")?
3968        .join(".local").join("bin");
3969    std::fs::create_dir_all(&local_bin)?;
3970    let dest = local_bin.join("cloudflared");
3971
3972    let url = match (std::env::consts::OS, std::env::consts::ARCH) {
3973        ("macos",  "aarch64") => "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-arm64",
3974        ("macos",  "x86_64")  => "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-amd64",
3975        ("linux",  "x86_64")  => "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64",
3976        ("linux",  "aarch64") => "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64",
3977        (os, arch) => bail!("No cloudflared binary for {os}/{arch}. Install manually: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"),
3978    };
3979
3980    println!("  {} cloudflared not found — downloading…", dim("·"));
3981    let bytes = reqwest::blocking::get(url)
3982        .and_then(|r| r.bytes())
3983        .context("Failed to download cloudflared")?;
3984
3985    // #4: Attempt checksum verification from Cloudflare's published checksums.
3986    // cloudflared publishes a checksums file alongside each release binary.
3987    let checksum_url = format!("{url}.sha256sum");
3988    match reqwest::blocking::get(&checksum_url).and_then(|r| r.text()) {
3989        Ok(text) => {
3990            use sha2::{Sha256, Digest};
3991            // Format: "<sha256>  cloudflared-darwin-arm64"
3992            let expected = text.split_whitespace().next().unwrap_or("");
3993            let actual = hex::encode(Sha256::digest(&bytes));
3994            if actual != expected {
3995                bail!("cloudflared checksum mismatch! Expected {expected}, got {actual}. Aborting.");
3996            }
3997            println!("  {} cloudflared checksum verified", green(CHECK));
3998        }
3999        Err(_) => {
4000            println!("  {} Warning: no .sha256sum file found — skipping cloudflared integrity check", yellow("!"));
4001        }
4002    }
4003
4004    std::fs::write(&dest, &bytes)?;
4005    #[cfg(unix)]
4006    {
4007        use std::os::unix::fs::PermissionsExt;
4008        std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755))?;
4009    }
4010    println!("  {} Downloaded to {}", green(CHECK), dim(&dest.display().to_string()));
4011
4012    Ok(dest.to_string_lossy().to_string())
4013}
4014
4015/// Spawn `cloudflared tunnel --url http://localhost:{port}`, wait for the public URL,
4016/// and return it. The cloudflared process is left running in the background.
4017fn start_cloudflare_tunnel(port: u16) -> Result<String> {
4018    use std::io::{BufRead, BufReader};
4019    use std::process::{Command, Stdio};
4020
4021    let bin = ensure_cloudflared()?;
4022
4023    let mut child = Command::new(&bin)
4024        .args(["tunnel", "--url", &format!("http://localhost:{port}")])
4025        .stderr(Stdio::piped())
4026        .stdout(Stdio::null())
4027        .spawn()
4028        .with_context(|| format!("Failed to start cloudflared ({bin})"))?;
4029
4030    let stderr = child.stderr.take().expect("stderr was piped");
4031    let reader = BufReader::new(stderr);
4032
4033    for line in reader.lines() {
4034        let line = line?;
4035        if let Some(url) = extract_cloudflare_url(&line) {
4036            // Leave the child running — it will be killed when the process exits
4037            std::mem::forget(child);
4038            return Ok(url);
4039        }
4040    }
4041
4042    bail!("cloudflared exited before providing a tunnel URL")
4043}
4044
4045/// Set up and run a named Cloudflare tunnel via the Cloudflare API — no browser required.
4046///
4047/// Steps (all CLI, no browser dropoff):
4048///   1. Prompt for / load Cloudflare API token (saved to config for reuse).
4049///   2. Resolve account ID and zone ID via the API.
4050///   3. Find or create the "shunt" tunnel via API → write credentials JSON.
4051///   4. Create DNS CNAME record via API (idempotent).
4052///   5. Write ~/.cloudflared/config.yml.
4053///   6. Start `cloudflared tunnel run`, wait for "registered", return.
4054fn start_named_cloudflare_tunnel(domain: &str, port: u16, config_p: &std::path::Path) -> Result<()> {
4055    use std::io::{BufRead, BufReader};
4056    use std::process::{Command, Stdio};
4057
4058    let bin = ensure_cloudflared()?;
4059    let home = dirs::home_dir().context("Cannot find home directory")?;
4060    let cf_dir = home.join(".cloudflared");
4061    std::fs::create_dir_all(&cf_dir)?;
4062
4063    let hostname = domain
4064        .trim_start_matches("https://")
4065        .trim_start_matches("http://")
4066        .trim_end_matches('/');
4067
4068    // ── Step 1: get API token ────────────────────────────────────────────────
4069    let token = cf_api_get_token(config_p)?;
4070
4071    // ── Step 2: resolve account + zone ──────────────────────────────────────
4072    print!("  {} Resolving Cloudflare account…", dim("·"));
4073    let _ = std::io::Write::flush(&mut std::io::stdout());
4074    let account_id = cf_api_get_account_id(&token)?;
4075    println!(" {}", green(CHECK));
4076
4077    let root_domain = hostname.splitn(2, '.').nth(1).unwrap_or(hostname);
4078    print!("  {} Resolving zone for {}…", dim("·"), dim(root_domain));
4079    let _ = std::io::Write::flush(&mut std::io::stdout());
4080    let zone_id = cf_api_get_zone_id(&token, root_domain)?;
4081    println!(" {}", green(CHECK));
4082
4083    // ── Step 3: find or create "shunt" tunnel ───────────────────────────────
4084    let creds_path = cf_dir.join("shunt-creds.json");
4085    let tunnel_id = cf_api_find_or_create_tunnel(&token, &account_id, &creds_path)?;
4086    println!("  {} Tunnel: {}", dim("·"), dim(&tunnel_id));
4087
4088    // ── Step 4: create / update DNS CNAME ───────────────────────────────────
4089    print!("  {} Setting DNS CNAME for {}…", dim("·"), cyan(hostname));
4090    let _ = std::io::Write::flush(&mut std::io::stdout());
4091    cf_api_upsert_dns(&token, &zone_id, hostname, &tunnel_id)?;
4092    println!(" {}", green(CHECK));
4093
4094    // ── Step 5: write cloudflared config ────────────────────────────────────
4095    let config_yml = cf_dir.join("config.yml");
4096    std::fs::write(&config_yml, format!(
4097        "tunnel: shunt\ncredentials-file: {creds}\ningress:\n  - hostname: {hostname}\n    service: http://127.0.0.1:{port}\n  - service: http_status:404\n",
4098        creds = creds_path.display(),
4099    )).context("Failed to write ~/.cloudflared/config.yml")?;
4100
4101    // ── Step 6: launch tunnel and wait for "registered" ─────────────────────
4102    println!("  {} Starting tunnel…", dim("·"));
4103    let mut child = Command::new(&bin)
4104        .args(["tunnel", "run", "--config", &config_yml.to_string_lossy(), "shunt"])
4105        .stderr(Stdio::piped()).stdout(Stdio::null())
4106        .spawn().context("Failed to spawn cloudflared")?;
4107
4108    let stderr = child.stderr.take().expect("piped");
4109    for line in BufReader::new(stderr).lines() {
4110        let line = line?;
4111        let lower = line.to_lowercase();
4112        if lower.contains("registered") || lower.contains("connection established") {
4113            std::mem::forget(child);
4114            println!("  {} Tunnel connected.", green(CHECK));
4115            println!();
4116            return Ok(());
4117        }
4118        if lower.contains("error") || lower.contains("failed") {
4119            eprintln!("  {} {}", yellow("!"), dim(&line));
4120        }
4121    }
4122    bail!("cloudflared exited before the tunnel became ready")
4123}
4124
4125/// Prompt for a Cloudflare API token, or load from env var / legacy config entry.
4126///
4127/// #5: New tokens are never written to config — users are directed to store them
4128/// in the environment instead. Existing entries in config.toml continue to work
4129/// for backward compat (with a one-time migration notice).
4130fn cf_api_get_token(config_p: &std::path::Path) -> Result<String> {
4131    // env var takes priority
4132    if let Ok(t) = std::env::var("CLOUDFLARE_API_TOKEN") {
4133        if !t.is_empty() { return Ok(t); }
4134    }
4135    // backward compat: read from config (legacy), but warn once
4136    if let Ok(text) = std::fs::read_to_string(config_p) {
4137        for line in text.lines() {
4138            let line = line.trim();
4139            if line.starts_with("cloudflare_api_token") {
4140                if let Some(v) = line.splitn(2, '=').nth(1) {
4141                    let t = v.trim().trim_matches('"').to_string();
4142                    if !t.is_empty() {
4143                        println!("  {} Cloudflare API token found in config.toml (plaintext).", yellow("!"));
4144                        println!("  {} Migrate to an env var to improve security:", dim("·"));
4145                        println!("       export CLOUDFLARE_API_TOKEN='{t}'");
4146                        println!("  {} Add that line to your shell profile and remove cloudflare_api_token from config.toml.", dim("·"));
4147                        println!();
4148                        return Ok(t);
4149                    }
4150                }
4151            }
4152        }
4153    }
4154    // prompt — do NOT write to config
4155    println!();
4156    println!("  {} A Cloudflare API token is needed to create the tunnel and DNS record.", dim("·"));
4157    println!("  {} Create one at {} with permissions:", dim("·"), cyan("https://dash.cloudflare.com/profile/api-tokens"));
4158    println!("  {}   Account → Cloudflare Tunnel: Edit", dim("·"));
4159    println!("  {}   Zone → DNS: Edit  (for your domain's zone)", dim("·"));
4160    println!();
4161    let token = rpassword::prompt_password("  Token: ")
4162        .context("Failed to read token")?;
4163    if token.is_empty() { bail!("No API token entered."); }
4164
4165    // Tell user how to persist — do not write to config
4166    println!();
4167    println!("  {} To avoid entering this each time, add to your shell profile:", dim("·"));
4168    println!("       export CLOUDFLARE_API_TOKEN='<your-token>'");
4169    println!();
4170    Ok(token)
4171}
4172
4173fn cf_api<T: serde::de::DeserializeOwned>(
4174    token: &str, method: &str, path: &str,
4175    body: Option<serde_json::Value>,
4176) -> Result<T> {
4177    let url = format!("https://api.cloudflare.com/client/v4{path}");
4178    let client = reqwest::blocking::Client::new();
4179    let req = match method {
4180        "GET"    => client.get(&url),
4181        "POST"   => client.post(&url),
4182        "PUT"    => client.put(&url),
4183        "PATCH"  => client.patch(&url),
4184        "DELETE" => client.delete(&url),
4185        m => bail!("Unknown HTTP method: {m}"),
4186    };
4187    let req = req.bearer_auth(token).header("Content-Type", "application/json");
4188    let req = if let Some(b) = body { req.json(&b) } else { req };
4189    let resp: serde_json::Value = req.send()?.json()?;
4190    if !resp["success"].as_bool().unwrap_or(false) {
4191        let errs = resp["errors"].to_string();
4192        bail!("Cloudflare API error: {errs}");
4193    }
4194    serde_json::from_value(resp["result"].clone()).context("Failed to parse Cloudflare API response")
4195}
4196
4197fn cf_api_get_account_id(token: &str) -> Result<String> {
4198    let accounts: serde_json::Value = cf_api(token, "GET", "/accounts?per_page=1", None)?;
4199    accounts.as_array()
4200        .and_then(|a| a.first())
4201        .and_then(|a| a["id"].as_str())
4202        .map(|s| s.to_owned())
4203        .context("No Cloudflare accounts found for this token")
4204}
4205
4206fn cf_api_get_zone_id(token: &str, root_domain: &str) -> Result<String> {
4207    let zones: serde_json::Value = cf_api(token, "GET",
4208        &format!("/zones?name={root_domain}&per_page=1"), None)?;
4209    zones.as_array()
4210        .and_then(|a| a.first())
4211        .and_then(|z| z["id"].as_str())
4212        .map(|s| s.to_owned())
4213        .with_context(|| format!("Zone '{root_domain}' not found — is this domain on Cloudflare?"))
4214}
4215
4216fn cf_api_find_or_create_tunnel(
4217    token: &str, account_id: &str, creds_path: &std::path::Path,
4218) -> Result<String> {
4219    // Search for existing "shunt" tunnel
4220    let tunnels: serde_json::Value = cf_api(token, "GET",
4221        &format!("/accounts/{account_id}/cfd_tunnel?name=shunt&per_page=10&is_deleted=false"), None)?;
4222
4223    if let Some(existing) = tunnels.as_array().and_then(|a| a.iter().find(|t| t["name"] == "shunt")) {
4224        let id = existing["id"].as_str().context("Tunnel has no id")?.to_owned();
4225        println!("  {} Found existing 'shunt' tunnel.", green(CHECK));
4226        // Write a minimal creds file if not present (tunnel run needs it)
4227        if !creds_path.exists() {
4228            let account_tag = existing["account_tag"].as_str().unwrap_or(account_id);
4229            let creds = serde_json::json!({
4230                "AccountTag": account_tag,
4231                "TunnelID": id,
4232                "TunnelName": "shunt"
4233            });
4234            std::fs::write(creds_path, creds.to_string())?;
4235            #[cfg(unix)]
4236            {
4237                use std::os::unix::fs::PermissionsExt;
4238                std::fs::set_permissions(creds_path, std::fs::Permissions::from_mode(0o600))?;
4239            }
4240        }
4241        return Ok(id);
4242    }
4243
4244    // Create new tunnel — generate a random 32-byte secret
4245    print!("  {} Creating 'shunt' tunnel…", dim("·"));
4246    let _ = std::io::Write::flush(&mut std::io::stdout());
4247    let secret_bytes = crate::oauth::rand_bytes::<32>();
4248    let secret_b64 = base64_encode(&secret_bytes);
4249
4250    let resp: serde_json::Value = cf_api(token, "POST",
4251        &format!("/accounts/{account_id}/cfd_tunnel"),
4252        Some(serde_json::json!({"name": "shunt", "tunnel_secret": secret_b64})))?;
4253
4254    let tunnel_id = resp["id"].as_str().context("No tunnel id in response")?.to_owned();
4255    let account_tag = resp["account_tag"].as_str().unwrap_or(account_id);
4256    println!(" {}", green(CHECK));
4257
4258    // Write credentials file
4259    let creds = serde_json::json!({
4260        "AccountTag":   account_tag,
4261        "TunnelSecret": secret_b64,
4262        "TunnelID":     tunnel_id,
4263        "TunnelName":   "shunt"
4264    });
4265    std::fs::write(creds_path, creds.to_string())?;
4266    #[cfg(unix)]
4267    {
4268        use std::os::unix::fs::PermissionsExt;
4269        std::fs::set_permissions(creds_path, std::fs::Permissions::from_mode(0o600))?;
4270    }
4271
4272    Ok(tunnel_id)
4273}
4274
4275fn cf_api_upsert_dns(token: &str, zone_id: &str, hostname: &str, tunnel_id: &str) -> Result<()> {
4276    let content = format!("{tunnel_id}.cfargotunnel.com");
4277
4278    // Check if record already exists
4279    let records: serde_json::Value = cf_api(token, "GET",
4280        &format!("/zones/{zone_id}/dns_records?type=CNAME&name={hostname}&per_page=1"), None)?;
4281
4282    if let Some(record) = records.as_array().and_then(|a| a.first()) {
4283        let record_id = record["id"].as_str().context("DNS record has no id")?;
4284        cf_api::<serde_json::Value>(token, "PATCH",
4285            &format!("/zones/{zone_id}/dns_records/{record_id}"),
4286            Some(serde_json::json!({"content": content, "proxied": true})))?;
4287    } else {
4288        cf_api::<serde_json::Value>(token, "POST",
4289            &format!("/zones/{zone_id}/dns_records"),
4290            Some(serde_json::json!({"type": "CNAME", "name": hostname, "content": content, "proxied": true})))?;
4291    }
4292    Ok(())
4293}
4294
4295fn base64_encode(bytes: &[u8]) -> String {
4296    // simple base64 without external dep — use the alphabet
4297    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4298    let mut out = String::new();
4299    for chunk in bytes.chunks(3) {
4300        let b0 = chunk[0] as u32;
4301        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
4302        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
4303        let n = (b0 << 16) | (b1 << 8) | b2;
4304        out.push(ALPHABET[((n >> 18) & 63) as usize] as char);
4305        out.push(ALPHABET[((n >> 12) & 63) as usize] as char);
4306        out.push(if chunk.len() > 1 { ALPHABET[((n >> 6) & 63) as usize] as char } else { '=' });
4307        out.push(if chunk.len() > 2 { ALPHABET[(n & 63) as usize] as char } else { '=' });
4308    }
4309    out
4310}
4311
4312fn extract_cloudflare_url(line: &str) -> Option<String> {
4313    // cloudflared prints the URL in a line like:
4314    //   INF | https://random-words.trycloudflare.com |
4315    // or just contains the URL somewhere in the log line
4316    let lower = line.to_lowercase();
4317    if lower.contains("trycloudflare.com") || lower.contains("cfargotunnel.com") {
4318        // Extract the https:// URL from the line
4319        if let Some(start) = line.find("https://") {
4320            let rest = &line[start..];
4321            let end = rest.find(|c: char| c.is_whitespace() || c == '|' || c == '"')
4322                .unwrap_or(rest.len());
4323            return Some(rest[..end].trim_end_matches('/').to_owned());
4324        }
4325    }
4326    None
4327}
4328
4329fn generate_remote_key() -> String {
4330    hex::encode(crate::oauth::rand_bytes::<16>())
4331}
4332
4333fn extract_remote_key(config: &str) -> Option<String> {
4334    for line in config.lines() {
4335        let line = line.trim();
4336        if line.starts_with("remote_key") {
4337            return line.split('=')
4338                .nth(1)
4339                .map(|s| s.trim().trim_matches('"').to_owned());
4340        }
4341    }
4342    None
4343}
4344
4345fn write_config_atomic(path: &std::path::Path, content: &str) -> Result<()> {
4346    let tmp = path.with_extension("tmp");
4347    std::fs::write(&tmp, content)?;
4348    std::fs::rename(&tmp, path)?;
4349    Ok(())
4350}
4351
4352fn local_ip() -> Option<String> {
4353    let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
4354    socket.connect("8.8.8.8:80").ok()?;
4355    Some(socket.local_addr().ok()?.ip().to_string())
4356}
4357
4358/// If the proxy is currently running, offer to restart it immediately.
4359async fn offer_restart(config_override: Option<PathBuf>) {
4360    use std::io::Write;
4361    let Ok(cfg) = crate::config::load_config(config_override.as_deref()) else { return };
4362    let health_url = format!("http://{}:{}/health", cfg.server.host, cfg.server.control_port);
4363    let running = reqwest::get(&health_url).await
4364        .map(|r| r.status().is_success())
4365        .unwrap_or(false);
4366    if !running { return; }
4367
4368    print!("  {} Proxy is running — restart now? [Y/n]: ", dim("·"));
4369    std::io::stdout().flush().ok();
4370    let mut buf = String::new();
4371    std::io::stdin().read_line(&mut buf).ok();
4372    if matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
4373        println!("  {} Run {} when ready.", dim("·"), cyan("shunt restart"));
4374        return;
4375    }
4376    if let Err(e) = cmd_restart(config_override).await {
4377        println!("  {} Restart failed: {e}", red(CROSS));
4378    }
4379}
4380
4381// ---------------------------------------------------------------------------
4382// connect
4383// ---------------------------------------------------------------------------
4384
4385async fn cmd_connect(code: String) -> Result<()> {
4386    use std::io::{self, Write};
4387
4388    crate::sync::validate_share_code(&code)?;
4389
4390    let relay_url = std::env::var("SHUNT_RELAY_URL")
4391        .unwrap_or_else(|_| "https://relay.ramcharan.shop".to_string());
4392
4393    print_splash(&[
4394        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
4395        dim("Connecting to remote shunt…").to_string(),
4396        String::new(),
4397    ]);
4398
4399    println!("  {} Fetching credentials for {}…", dim("·"), cyan(&code));
4400    println!();
4401
4402    let (base_url, api_key) = crate::sync::pull_share(&code, &relay_url).await?;
4403
4404    println!("  {}  Retrieved:", green(CHECK));
4405    println!("      {} {}", dim("ANTHROPIC_BASE_URL ="), cyan(&base_url));
4406    println!("      {} {}", dim("ANTHROPIC_API_KEY  ="), cyan(&format!("{}…", &api_key[..api_key.len().min(12)])));
4407    println!();
4408
4409    // --- Offer to write to shell profile ---
4410    let profile = detect_shell_profile();
4411    let prompt = match &profile {
4412        Some(p) => format!("  Write to {}? [Y/n]: ", dim(&p.display().to_string())),
4413        None => "  Write to shell profile? [Y/n]: ".into(),
4414    };
4415    print!("{prompt}");
4416    io::stdout().flush()?;
4417    let mut buf = String::new();
4418    io::stdin().read_line(&mut buf)?;
4419
4420    if !matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
4421        match profile {
4422            Some(p) => {
4423                write_connect_vars_to_profile(&p, &base_url, &api_key)?;
4424            }
4425            None => {
4426                println!("  {} Could not detect shell profile. Set manually:", dim("·"));
4427                println!("      export ANTHROPIC_BASE_URL={base_url}");
4428                println!("      export ANTHROPIC_API_KEY={api_key}");
4429            }
4430        }
4431    }
4432
4433    // --- Write to Claude Code settings.json ---
4434    if let Err(e) = write_claude_settings(&base_url, &api_key) {
4435        println!("  {} Could not write ~/.claude/settings.json: {e}", dim("·"));
4436    } else {
4437        println!("  {} Written to {}", green(CHECK), dim("~/.claude/settings.json"));
4438    }
4439
4440    println!();
4441    println!("  {} Done! Restart shell or run: {}", green(CHECK),
4442        cyan(detect_shell_profile()
4443            .map(|p| format!("source {}", p.display()))
4444            .unwrap_or_else(|| "source ~/.zshrc".to_string()).as_str()));
4445    println!();
4446
4447    Ok(())
4448}
4449
4450async fn cmd_live(config_override: Option<PathBuf>, subdomain: Option<String>, relay_override: Option<String>) -> Result<()> {
4451    let config = crate::config::load_config(config_override.as_deref())
4452        .context("No config found. Run `shunt setup` first.")?;
4453
4454    let subdomain = subdomain
4455        .or_else(|| std::env::var("SHUNT_TUNNEL_SUBDOMAIN").ok())
4456        .unwrap_or_else(|| "shunt".to_string());
4457
4458    let relay_ws = relay_override
4459        .or_else(|| std::env::var("SHUNT_RELAY_WS_URL").ok())
4460        .unwrap_or_else(|| "wss://relay.ramcharan.shop/tunnel".to_string());
4461
4462    let token = match std::env::var("SHUNT_TUNNEL_TOKEN") {
4463        Ok(t) if !t.is_empty() => t,
4464        _ => {
4465            let config_p = config_override.clone().unwrap_or_else(config_path);
4466            setup_live_tunnel(&subdomain, &config_p).await?
4467        }
4468    };
4469
4470    let local_url = format!("http://{}:{}", config.server.host, config.server.port);
4471
4472    print_splash(&[
4473        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
4474        dim("Live tunnel").to_string(),
4475        String::new(),
4476    ]);
4477    println!("  {} Subdomain:  {}", dim("·"), cyan(&format!("{subdomain}.ramcharan.shop")));
4478    println!("  {} Local:      {}", dim("·"), dim(&local_url));
4479    println!("  {} Relay:      {}", dim("·"), dim(&relay_ws));
4480    println!("  {} Press Ctrl+C to disconnect.", dim("·"));
4481    println!();
4482
4483    crate::tunnel::run_live(&relay_ws, &subdomain, &token, &local_url).await
4484}
4485
4486/// First-run wizard for `shunt live`: generates a tunnel token, sets up DNS,
4487/// waits for the relay, and saves the token to the shell profile.
4488/// Returns the generated token so `cmd_live` can use it immediately.
4489async fn setup_live_tunnel(subdomain: &str, config_path: &std::path::Path) -> Result<String> {
4490    use std::io::Write as _;
4491
4492    println!();
4493    println!("  {} {}", brand_green("shunt live"), dim("— first-time setup"));
4494    println!();
4495
4496    // Step 1: Generate token
4497    println!("  {} Generating tunnel token…", dim("1/5"));
4498    let token = hex::encode(crate::oauth::rand_bytes::<32>());
4499    println!("  {} Token generated (64 hex chars)", green(CHECK));
4500    println!();
4501
4502    // Step 2: DNS setup — get CF token, VPS IP, create wildcard A record
4503    println!("  {} Setting up DNS…", dim("2/5"));
4504    let cf_token = cf_api_get_token(config_path)?;
4505
4506    print!("  Enter your VPS IP address: ");
4507    std::io::stdout().flush()?;
4508    let mut vps_ip = String::new();
4509    std::io::stdin().read_line(&mut vps_ip)?;
4510    let vps_ip = vps_ip.trim().to_string();
4511    vps_ip.parse::<std::net::IpAddr>()
4512        .with_context(|| format!("Invalid IP address: {vps_ip}"))?;
4513
4514    let zone_id = cf_api_get_zone_id(&cf_token, "ramcharan.shop")?;
4515    let dns_name = "*.ramcharan.shop";
4516    cf_api_upsert_dns_a(&cf_token, &zone_id, dns_name, &vps_ip)?;
4517    println!("  {} DNS: {} → {}", green(CHECK), cyan(dns_name), cyan(&vps_ip));
4518    println!();
4519
4520    // Step 3: Show the relay command
4521    println!("  {} Start the relay on your VPS", dim("3/5"));
4522    println!("  ┌─────────────────────────────────────────────────────────────┐");
4523    println!("  │  SHUNT_RELAY_TOKEN={} shunt relay serve  │", &token[..20]);
4524    // Print the full command separately so it's easy to copy
4525    println!("  └─────────────────────────────────────────────────────────────┘");
4526    println!();
4527    println!("  Full command:");
4528    println!("    SHUNT_RELAY_TOKEN={token} shunt relay serve --port 8085");
4529    println!();
4530    println!("  SSH into your VPS and run the command above.");
4531    print!("  Press Enter when ready…");
4532    std::io::stdout().flush()?;
4533    let mut buf = String::new();
4534    std::io::stdin().read_line(&mut buf)?;
4535    println!();
4536
4537    // Step 4: Wait for relay
4538    println!("  {} Waiting for relay…", dim("4/5"));
4539    let relay_url = "wss://relay.ramcharan.shop/tunnel";
4540    poll_relay_ws(relay_url, std::time::Duration::from_secs(300)).await?;
4541    println!("  {} Relay is online", green(CHECK));
4542    println!();
4543
4544    // Step 5: Save token to shell profile
4545    println!("  {} Saving config…", dim("5/5"));
4546    write_tunnel_token_to_profile(&token, subdomain)?;
4547    println!();
4548
4549    // Set in current process so the tunnel can start immediately
4550    #[allow(unused_unsafe)]
4551    unsafe { std::env::set_var("SHUNT_TUNNEL_TOKEN", &token); }
4552    if subdomain != "shunt" {
4553        #[allow(unused_unsafe)]
4554        unsafe { std::env::set_var("SHUNT_TUNNEL_SUBDOMAIN", subdomain); }
4555    }
4556
4557    println!("  Setup complete! Starting tunnel…");
4558    println!();
4559
4560    Ok(token)
4561}
4562
4563/// Create or update an A record in Cloudflare DNS.
4564fn cf_api_upsert_dns_a(token: &str, zone_id: &str, hostname: &str, ip: &str) -> Result<()> {
4565    // Check if A record already exists
4566    let records: serde_json::Value = cf_api(token, "GET",
4567        &format!("/zones/{zone_id}/dns_records?type=A&name={hostname}&per_page=1"), None)?;
4568
4569    if let Some(record) = records.as_array().and_then(|a| a.first()) {
4570        let record_id = record["id"].as_str().context("DNS record has no id")?;
4571        cf_api::<serde_json::Value>(token, "PATCH",
4572            &format!("/zones/{zone_id}/dns_records/{record_id}"),
4573            Some(serde_json::json!({"content": ip, "proxied": true})))?;
4574    } else {
4575        cf_api::<serde_json::Value>(token, "POST",
4576            &format!("/zones/{zone_id}/dns_records"),
4577            Some(serde_json::json!({"type": "A", "name": hostname, "content": ip, "proxied": true})))?;
4578    }
4579    Ok(())
4580}
4581
4582/// Poll the relay WebSocket endpoint until it responds or timeout is reached.
4583async fn poll_relay_ws(url: &str, timeout: std::time::Duration) -> Result<()> {
4584    let start = std::time::Instant::now();
4585    let interval = std::time::Duration::from_secs(5);
4586
4587    loop {
4588        match tokio_tungstenite::connect_async(url).await {
4589            Ok((_ws, _)) => {
4590                // Connected successfully — drop closes the connection
4591                return Ok(());
4592            }
4593            Err(_) => {
4594                if start.elapsed() >= timeout {
4595                    bail!(
4596                        "Relay did not respond after {}s. Check that the relay is running on your VPS \
4597                         and that DNS has propagated (*.ramcharan.shop).",
4598                        timeout.as_secs()
4599                    );
4600                }
4601                print!(".");
4602                let _ = std::io::Write::flush(&mut std::io::stdout());
4603                tokio::time::sleep(interval).await;
4604            }
4605        }
4606    }
4607}
4608
4609/// Write SHUNT_TUNNEL_TOKEN (and optionally SHUNT_TUNNEL_SUBDOMAIN) to the
4610/// user's shell profile.
4611fn write_tunnel_token_to_profile(token: &str, subdomain: &str) -> Result<()> {
4612    use std::io::Write as _;
4613
4614    let profile = detect_shell_profile()
4615        .context("Could not detect shell profile. Set SHUNT_TUNNEL_TOKEN manually.")?;
4616
4617    let token_line = format!("export SHUNT_TUNNEL_TOKEN={token}");
4618    let subdomain_line = if subdomain != "shunt" {
4619        Some(format!("export SHUNT_TUNNEL_SUBDOMAIN={subdomain}"))
4620    } else {
4621        None
4622    };
4623
4624    if profile.exists() {
4625        let contents = std::fs::read_to_string(&profile)?;
4626
4627        // Replace existing lines if present
4628        if contents.contains("SHUNT_TUNNEL_TOKEN") {
4629            let updated: String = contents
4630                .lines()
4631                .map(|l| {
4632                    if l.contains("SHUNT_TUNNEL_TOKEN") && !l.contains("SHUNT_TUNNEL_SUBDOMAIN") {
4633                        Some(token_line.as_str())
4634                    } else if l.contains("SHUNT_TUNNEL_SUBDOMAIN") {
4635                        subdomain_line.as_deref() // None = remove line
4636                    } else {
4637                        Some(l)
4638                    }
4639                })
4640                .flatten()
4641                .collect::<Vec<_>>()
4642                .join("\n")
4643                + "\n";
4644            std::fs::write(&profile, updated)?;
4645            println!("  {} Updated {}", green(CHECK), dim(&profile.display().to_string()));
4646            return Ok(());
4647        }
4648    }
4649
4650    // Append
4651    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&profile)?;
4652    writeln!(f, "\n# Added by shunt live")?;
4653    writeln!(f, "{token_line}")?;
4654    if let Some(sub_line) = &subdomain_line {
4655        writeln!(f, "{sub_line}")?;
4656    }
4657    println!("  {} Token saved to {}", green(CHECK), dim(&profile.display().to_string()));
4658    Ok(())
4659}
4660
4661async fn cmd_relay_serve(port: u16) -> Result<()> {
4662    let token = std::env::var("SHUNT_RELAY_TOKEN")
4663        .context("SHUNT_RELAY_TOKEN env var required")?;
4664    crate::live_relay::run_relay_server(port, token).await
4665}
4666
4667async fn cmd_disconnect() -> Result<()> {
4668    print_splash(&[
4669        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
4670        dim("Disconnecting from remote shunt…").to_string(),
4671        String::new(),
4672    ]);
4673
4674    let mut any = false;
4675
4676    // 1. Shell profile — strip ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY lines
4677    //    written by `shunt connect` (remote URLs, not localhost ones).
4678    if let Some(profile) = detect_shell_profile() {
4679        if let Ok(contents) = std::fs::read_to_string(&profile) {
4680            let needs_clean = contents.lines().any(|l| {
4681                (l.contains("ANTHROPIC_BASE_URL") && !l.contains("127.0.0.1") && !l.contains("localhost"))
4682                    || l.contains("ANTHROPIC_API_KEY")
4683                    || l.trim() == "# Added by shunt connect"
4684            });
4685            if needs_clean {
4686                let cleaned: String = contents
4687                    .lines()
4688                    .filter(|l| {
4689                        let is_remote_url = l.contains("ANTHROPIC_BASE_URL")
4690                            && !l.contains("127.0.0.1")
4691                            && !l.contains("localhost");
4692                        let is_api_key = l.contains("ANTHROPIC_API_KEY");
4693                        let is_comment = l.trim() == "# Added by shunt connect";
4694                        !is_remote_url && !is_api_key && !is_comment
4695                    })
4696                    .collect::<Vec<_>>()
4697                    .join("\n");
4698                let cleaned = if contents.ends_with('\n') {
4699                    format!("{cleaned}\n")
4700                } else {
4701                    cleaned
4702                };
4703                std::fs::write(&profile, cleaned)?;
4704                println!("  {} Removed from {}", green(CHECK), dim(&profile.display().to_string()));
4705                any = true;
4706            }
4707        }
4708    }
4709
4710    // 2. ~/.claude/settings.json — remove the env keys written by `shunt connect`.
4711    let home = dirs::home_dir().context("Cannot find home directory")?;
4712    let settings_path = home.join(".claude").join("settings.json");
4713    if settings_path.exists() {
4714        let text = std::fs::read_to_string(&settings_path)?;
4715        let mut root: serde_json::Value = serde_json::from_str(&text)
4716            .unwrap_or(serde_json::Value::Object(Default::default()));
4717        let mut changed = false;
4718        if let Some(env_obj) = root.get_mut("env").and_then(|e| e.as_object_mut()) {
4719            // Only remove ANTHROPIC_BASE_URL if it points at a remote host
4720            if let Some(url) = env_obj.get("ANTHROPIC_BASE_URL").and_then(|v| v.as_str()) {
4721                if !url.contains("127.0.0.1") && !url.contains("localhost") {
4722                    env_obj.remove("ANTHROPIC_BASE_URL");
4723                    changed = true;
4724                }
4725            }
4726            if env_obj.remove("ANTHROPIC_API_KEY").is_some() {
4727                changed = true;
4728            }
4729        }
4730        if changed {
4731            std::fs::write(&settings_path, serde_json::to_string_pretty(&root)?)?;
4732            println!("  {} Removed from {}", green(CHECK), dim(&settings_path.display().to_string()));
4733            any = true;
4734        }
4735    }
4736
4737    // 3. managed_settings.json — remove remote ANTHROPIC_BASE_URL if present
4738    let managed_path = managed_claude_settings_path(&home);
4739    if managed_path.exists() {
4740        if let Ok(text) = std::fs::read_to_string(&managed_path) {
4741            if let Ok(mut root) = serde_json::from_str::<serde_json::Value>(&text) {
4742                let mut changed = false;
4743                if let Some(env_obj) = root.get_mut("env").and_then(|e| e.as_object_mut()) {
4744                    if let Some(url) = env_obj.get("ANTHROPIC_BASE_URL").and_then(|v| v.as_str()) {
4745                        if !url.contains("127.0.0.1") && !url.contains("localhost") {
4746                            env_obj.remove("ANTHROPIC_BASE_URL");
4747                            changed = true;
4748                        }
4749                    }
4750                    if env_obj.remove("ANTHROPIC_API_KEY").is_some() {
4751                        changed = true;
4752                    }
4753                }
4754                if changed {
4755                    if let Ok(t) = serde_json::to_string_pretty(&root) {
4756                        let _ = std::fs::write(&managed_path, t);
4757                        println!("  {} Removed from {}", green(CHECK), dim(&managed_path.display().to_string()));
4758                        any = true;
4759                    }
4760                }
4761            }
4762        }
4763    }
4764
4765    if !any {
4766        println!("  {} Nothing to remove — no remote connection found.", dim("·"));
4767    }
4768
4769    println!();
4770    println!("  {} Run {} to clear the current shell session.", dim("·"),
4771        cyan("unset ANTHROPIC_BASE_URL ANTHROPIC_API_KEY"));
4772    println!();
4773    Ok(())
4774}
4775
4776/// Write ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY to a shell profile, replacing
4777/// existing entries in-place or appending if absent.
4778fn write_connect_vars_to_profile(profile: &std::path::Path, base_url: &str, api_key: &str) -> Result<()> {
4779    use std::io::Write as _;
4780
4781    let url_line = format!("export ANTHROPIC_BASE_URL={base_url}");
4782    let key_line = format!("export ANTHROPIC_API_KEY={api_key}");
4783
4784    if profile.exists() {
4785        let contents = std::fs::read_to_string(profile)?;
4786        let has_url = contents.contains("ANTHROPIC_BASE_URL");
4787        let has_key = contents.contains("ANTHROPIC_API_KEY");
4788
4789        if has_url || has_key {
4790            // Replace in-place
4791            let updated: String = contents
4792                .lines()
4793                .map(|l| {
4794                    if l.contains("ANTHROPIC_BASE_URL") {
4795                        url_line.as_str()
4796                    } else if l.contains("ANTHROPIC_API_KEY") {
4797                        key_line.as_str()
4798                    } else {
4799                        l
4800                    }
4801                })
4802                .collect::<Vec<_>>()
4803                .join("\n")
4804                + "\n";
4805            // Append any var that wasn't already there
4806            let mut final_content = updated;
4807            if !has_url {
4808                final_content.push_str(&format!("{url_line}\n"));
4809            }
4810            if !has_key {
4811                final_content.push_str(&format!("{key_line}\n"));
4812            }
4813            std::fs::write(profile, &final_content)?;
4814            println!("  {} Updated {} — {}", green(CHECK),
4815                dim(&profile.display().to_string()),
4816                cyan("ANTHROPIC_BASE_URL + ANTHROPIC_API_KEY"));
4817            return Ok(());
4818        }
4819    }
4820
4821    // Append both vars
4822    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(profile)?;
4823    writeln!(f, "\n# Added by shunt connect")?;
4824    writeln!(f, "{url_line}")?;
4825    writeln!(f, "{key_line}")?;
4826    println!("  {} Added to {} — {}", green(CHECK),
4827        dim(&profile.display().to_string()),
4828        cyan("ANTHROPIC_BASE_URL + ANTHROPIC_API_KEY"));
4829    Ok(())
4830}
4831
4832/// Write ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY into ~/.claude/settings.json
4833/// and the managed-settings policy file under the `env` key (creating if absent).
4834/// Both files must be updated so the managed policy (highest priority) does not
4835/// shadow the user settings when switching between local and remote shunt.
4836fn write_claude_settings(base_url: &str, api_key: &str) -> Result<()> {
4837    let home = dirs::home_dir().context("Cannot find home directory")?;
4838
4839    for settings_path in [
4840        home.join(".claude").join("settings.json"),
4841        managed_claude_settings_path(&home),
4842    ] {
4843        let mut root: serde_json::Value = if settings_path.exists() {
4844            let text = std::fs::read_to_string(&settings_path)?;
4845            serde_json::from_str(&text).unwrap_or(serde_json::Value::Object(Default::default()))
4846        } else {
4847            serde_json::Value::Object(Default::default())
4848        };
4849
4850        let obj = root.as_object_mut().context("settings root is not an object")?;
4851        let env = obj.entry("env").or_insert(serde_json::Value::Object(Default::default()));
4852        let env_obj = env.as_object_mut().context("settings 'env' is not an object")?;
4853        env_obj.insert("ANTHROPIC_BASE_URL".to_string(), serde_json::Value::String(base_url.to_string()));
4854        env_obj.insert("ANTHROPIC_API_KEY".to_string(), serde_json::Value::String(api_key.to_string()));
4855
4856        if let Some(parent) = settings_path.parent() {
4857            std::fs::create_dir_all(parent)?;
4858        }
4859        std::fs::write(&settings_path, serde_json::to_string_pretty(&root)?)?;
4860    }
4861    Ok(())
4862}
4863
4864/// Write `ANTHROPIC_BASE_URL` pointing at the local shunt proxy into
4865/// `~/.claude/settings.json` so Claude Code picks it up immediately without
4866/// requiring a shell restart.  Only sets the URL — never touches API keys.
4867/// Skips if settings.json already has a non-localhost ANTHROPIC_BASE_URL
4868/// (i.e. user connected to a remote shunt; don't clobber that).
4869fn write_local_claude_settings(port: u16) {
4870    let url = format!("http://127.0.0.1:{port}");
4871    let home = match dirs::home_dir() {
4872        Some(h) => h,
4873        None => return,
4874    };
4875    let settings_path = home.join(".claude").join("settings.json");
4876
4877    let mut root: serde_json::Value = if settings_path.exists() {
4878        std::fs::read_to_string(&settings_path).ok()
4879            .and_then(|t| serde_json::from_str(&t).ok())
4880            .unwrap_or(serde_json::Value::Object(Default::default()))
4881    } else {
4882        serde_json::Value::Object(Default::default())
4883    };
4884
4885    // Don't override a remote URL that was set by `shunt connect`.
4886    if let Some(existing) = root.get("env")
4887        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
4888        .and_then(|v| v.as_str())
4889    {
4890        if !existing.contains("127.0.0.1") && !existing.contains("localhost") {
4891            return;
4892        }
4893    }
4894
4895    let obj = match root.as_object_mut() { Some(o) => o, None => return };
4896    let env = obj.entry("env").or_insert(serde_json::Value::Object(Default::default()));
4897    if let Some(env_obj) = env.as_object_mut() {
4898        env_obj.insert("ANTHROPIC_BASE_URL".to_string(), serde_json::Value::String(url));
4899    }
4900
4901    if let Some(parent) = settings_path.parent() {
4902        let _ = std::fs::create_dir_all(parent);
4903    }
4904    if let Ok(text) = serde_json::to_string_pretty(&root) {
4905        if std::fs::write(&settings_path, text).is_ok() {
4906            println!("  {} {} → {}", green(CHECK),
4907                cyan("ANTHROPIC_BASE_URL"),
4908                dim(&settings_path.display().to_string()));
4909        }
4910    }
4911}
4912
4913// ---------------------------------------------------------------------------
4914// managed_settings: highest-priority Claude Code policy file
4915// On macOS this sits in ~/Library/Application Support/Claude/managed_settings.json
4916// and takes precedence over user settings — Claude Code login cannot clear it.
4917// ---------------------------------------------------------------------------
4918
4919#[cfg(target_os = "macos")]
4920fn managed_claude_settings_path(home: &std::path::Path) -> std::path::PathBuf {
4921    home.join("Library").join("Application Support").join("Claude").join("managed_settings.json")
4922}
4923#[cfg(not(target_os = "macos"))]
4924fn managed_claude_settings_path(home: &std::path::Path) -> std::path::PathBuf {
4925    home.join(".config").join("claude").join("managed_settings.json")
4926}
4927
4928/// Remove ANTHROPIC_BASE_URL from a settings JSON file (user or managed).
4929fn remove_from_settings_file(path: &std::path::Path) -> bool {
4930    remove_from_settings_file_impl(path, false)
4931}
4932
4933fn remove_from_settings_file_quiet(path: &std::path::Path) -> bool {
4934    remove_from_settings_file_impl(path, true)
4935}
4936
4937fn remove_from_settings_file_impl(path: &std::path::Path, quiet: bool) -> bool {
4938    if !path.exists() { return false; }
4939    let Ok(text) = std::fs::read_to_string(path) else { return false };
4940    let Ok(mut root) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
4941    let removed = if let Some(env) = root.get_mut("env").and_then(|e| e.as_object_mut()) {
4942        env.remove("ANTHROPIC_BASE_URL").is_some()
4943    } else {
4944        false
4945    };
4946    if removed {
4947        if let Ok(t) = serde_json::to_string_pretty(&root) {
4948            let _ = std::fs::write(path, t);
4949            if !quiet {
4950                println!("  {} Removed from {}", green(CHECK), dim(&path.display().to_string()));
4951            }
4952        }
4953    }
4954    removed
4955}
4956
4957/// Write ANTHROPIC_BASE_URL into both settings files without any console output.
4958/// Used by the daemon on startup and by the guardian loop.
4959fn apply_local_routing_silent(port: u16) {
4960    let url = format!("http://127.0.0.1:{port}");
4961    let home = match dirs::home_dir() { Some(h) => h, None => return };
4962    let managed = managed_claude_settings_path(&home);
4963
4964    for settings_path in [home.join(".claude").join("settings.json"), managed.clone()] {
4965        // For user settings.json: only touch if it already exists.
4966        // For managed_settings: always create — it survives re-login.
4967        if !settings_path.exists() && settings_path != managed { continue; }
4968
4969        let mut root: serde_json::Value = if settings_path.exists() {
4970            std::fs::read_to_string(&settings_path).ok()
4971                .and_then(|t| serde_json::from_str(&t).ok())
4972                .unwrap_or(serde_json::Value::Object(Default::default()))
4973        } else {
4974            serde_json::Value::Object(Default::default())
4975        };
4976
4977        // Never clobber a remote URL written by `shunt connect` — only touch localhost URLs.
4978        if let Some(existing) = root.get("env")
4979            .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
4980            .and_then(|v| v.as_str())
4981        {
4982            if !existing.contains("127.0.0.1") && !existing.contains("localhost") {
4983                continue;
4984            }
4985        }
4986
4987        // Skip if already correct to avoid unnecessary writes.
4988        let current = root.get("env").and_then(|e| e.get("ANTHROPIC_BASE_URL")).and_then(|v| v.as_str());
4989        if current == Some(url.as_str()) { continue; }
4990
4991        let obj = match root.as_object_mut() { Some(o) => o, None => continue };
4992        let env = obj.entry("env").or_insert(serde_json::Value::Object(Default::default()));
4993        if let Some(e) = env.as_object_mut() {
4994            e.insert("ANTHROPIC_BASE_URL".to_string(), serde_json::Value::String(url.clone()));
4995        }
4996
4997        if let Some(parent) = settings_path.parent() { let _ = std::fs::create_dir_all(parent); }
4998        if let Ok(out) = serde_json::to_string_pretty(&root) {
4999            let _ = std::fs::write(&settings_path, out);
5000        }
5001    }
5002}
5003
5004/// Background task: re-inject ANTHROPIC_BASE_URL into ~/.claude/settings.json if a Claude Code
5005/// re-login clears it while the shunt daemon is running.
5006async fn settings_guardian_loop(port: u16) {
5007    let url = format!("http://127.0.0.1:{port}");
5008    let mut interval = tokio::time::interval(std::time::Duration::from_secs(5));
5009    let home = match dirs::home_dir() { Some(h) => h, None => return };
5010    let settings_path = home.join(".claude").join("settings.json");
5011
5012    loop {
5013        interval.tick().await;
5014        if !settings_path.exists() { continue; }
5015
5016        let current = std::fs::read_to_string(&settings_path).ok()
5017            .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
5018            .and_then(|v| v.get("env")?.get("ANTHROPIC_BASE_URL")?.as_str().map(String::from));
5019
5020        if current.as_deref() != Some(url.as_str()) {
5021            apply_local_routing_silent(port);
5022        }
5023    }
5024}
5025
5026fn offer_shell_export(port: u16) -> Result<()> {
5027    use std::io::{self, Write};
5028
5029    let line = format!("export ANTHROPIC_BASE_URL=http://127.0.0.1:{port}");
5030    let line = line.as_str();
5031    println!();
5032    println!("  For other tools (curl, Python SDK, …), set:");
5033    println!("    {}", cyan(line));
5034
5035    let profile = detect_shell_profile();
5036    let prompt = match &profile {
5037        Some(p) => format!("  Add to {}? [Y/n]: ", dim(&p.display().to_string())),
5038        None => "  Add to your shell profile? [Y/n]: ".into(),
5039    };
5040
5041    print!("{prompt}");
5042    io::stdout().flush()?;
5043    let mut buf = String::new();
5044    io::stdin().read_line(&mut buf)?;
5045
5046    if matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
5047        return Ok(());
5048    }
5049
5050    let path = match profile {
5051        Some(p) => p,
5052        None => {
5053            println!("  {} Could not detect shell profile. Add manually.", dim("·"));
5054            return Ok(());
5055        }
5056    };
5057
5058    if path.exists() {
5059        let contents = std::fs::read_to_string(&path)?;
5060        if contents.contains("ANTHROPIC_BASE_URL") {
5061            println!("  {} Already set in {}", CHECK, dim(&path.display().to_string()));
5062            return Ok(());
5063        }
5064    }
5065
5066    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
5067    #[allow(unused_imports)]
5068    use std::io::Write as _;
5069    writeln!(f, "\n# Added by shunt")?;
5070    writeln!(f, "{line}")?;
5071    println!("  {} Added to {} — restart shell or: {}", green(CHECK),
5072        dim(&path.display().to_string()),
5073        cyan(&format!("source {}", path.display())));
5074
5075    Ok(())
5076}
5077
5078// ---------------------------------------------------------------------------
5079// uninstall
5080// ---------------------------------------------------------------------------
5081
5082async fn cmd_uninstall() -> Result<()> {
5083    use std::io::Write as _;
5084
5085    // ── Collect what exists ───────────────────────────────────────────────────
5086    let config_dir = dirs::config_dir()
5087        .unwrap_or_else(|| PathBuf::from("."))
5088        .join("shunt");
5089
5090    let data_dir = dirs::data_local_dir()
5091        .unwrap_or_else(|| PathBuf::from("."))
5092        .join("shunt");
5093
5094    let exe = std::env::current_exe().ok();
5095
5096    // Shell profile line to remove
5097    let shell_profile = detect_shell_profile();
5098    let profile_has_export = shell_profile.as_ref().and_then(|p| {
5099        std::fs::read_to_string(p).ok()
5100    }).map(|s| s.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:")).unwrap_or(false);
5101
5102    let uninstall_home = dirs::home_dir();
5103    let user_settings_has_shunt = uninstall_home.as_ref().map(|h| {
5104        let p = h.join(".claude").join("settings.json");
5105        std::fs::read_to_string(&p).ok()
5106            .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
5107            .and_then(|v| v.get("env")?.get("ANTHROPIC_BASE_URL")?.as_str().map(|u| u.contains("127.0.0.1") || u.contains("localhost")))
5108            .unwrap_or(false)
5109    }).unwrap_or(false);
5110    let managed_settings_has_shunt = uninstall_home.as_ref().map(|h| {
5111        let p = managed_claude_settings_path(h);
5112        std::fs::read_to_string(&p).ok()
5113            .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
5114            .and_then(|v| v.get("env")?.get("ANTHROPIC_BASE_URL")?.as_str().map(|u| u.contains("127.0.0.1") || u.contains("localhost")))
5115            .unwrap_or(false)
5116    }).unwrap_or(false);
5117
5118    #[cfg(target_os = "macos")]
5119    let service_plist = {
5120        let p = service_plist_path();
5121        if p.exists() { Some(p) } else { None }
5122    };
5123    #[cfg(not(target_os = "macos"))]
5124    let service_plist: Option<PathBuf> = None;
5125
5126    #[cfg(target_os = "linux")]
5127    let service_unit = {
5128        let p = service_unit_path();
5129        if p.exists() { Some(p) } else { None }
5130    };
5131    #[cfg(not(target_os = "linux"))]
5132    let service_unit: Option<PathBuf> = None;
5133
5134    // ── Show plan ─────────────────────────────────────────────────────────────
5135    print_splash(&[
5136        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
5137        red("Uninstall").to_string(),
5138        String::new(),
5139    ]);
5140
5141    println!("  This will permanently remove:");
5142    println!();
5143
5144    if service_plist.is_some() || service_unit.is_some() {
5145        println!("  {}  Stop and unregister login service", red("✕"));
5146    }
5147
5148    if config_dir.exists() {
5149        println!("  {}  {} {}", red("✕"), dim("delete"), cyan(&config_dir.display().to_string()));
5150    }
5151    if data_dir.exists() && data_dir != config_dir {
5152        println!("  {}  {} {}", red("✕"), dim("delete"), cyan(&data_dir.display().to_string()));
5153    }
5154    if let Some(ref p) = shell_profile {
5155        if profile_has_export {
5156            println!("  {}  {} ANTHROPIC_BASE_URL from {}", red("✕"), dim("remove"), cyan(&p.display().to_string()));
5157        }
5158    }
5159    if user_settings_has_shunt {
5160        if let Some(ref h) = uninstall_home {
5161            println!("  {}  {} ANTHROPIC_BASE_URL from {}", red("✕"), dim("remove"),
5162                cyan(&h.join(".claude").join("settings.json").display().to_string()));
5163        }
5164    }
5165    if managed_settings_has_shunt {
5166        if let Some(ref h) = uninstall_home {
5167            println!("  {}  {} ANTHROPIC_BASE_URL from {}", red("✕"), dim("remove"),
5168                cyan(&managed_claude_settings_path(h).display().to_string()));
5169        }
5170    }
5171    if let Some(ref exe_path) = exe {
5172        println!("  {}  {} {}", red("✕"), dim("delete"), cyan(&exe_path.display().to_string()));
5173    }
5174
5175    println!();
5176
5177    // ── Reconfirm ─────────────────────────────────────────────────────────────
5178    if !term::confirm("Are you sure you want to completely uninstall shunt?") {
5179        println!("  {} Cancelled.", dim("·"));
5180        println!();
5181        return Ok(());
5182    }
5183
5184    // Second confirmation — type "uninstall"
5185    println!();
5186    print!("  {} Type {} to confirm: ", dim("·"), bold("uninstall"));
5187    std::io::stdout().flush()?;
5188    let mut buf = String::new();
5189    std::io::stdin().read_line(&mut buf)?;
5190    if buf.trim() != "uninstall" {
5191        println!("  {} Cancelled.", dim("·"));
5192        println!();
5193        return Ok(());
5194    }
5195
5196    println!();
5197
5198    // ── Execute ───────────────────────────────────────────────────────────────
5199
5200    // 1. Stop + unregister service
5201    #[cfg(target_os = "macos")]
5202    if let Some(ref p) = service_plist {
5203        let _ = std::process::Command::new("launchctl")
5204            .args(["unload", &p.display().to_string()])
5205            .output();
5206        let _ = std::fs::remove_file(p);
5207        println!("  {} Login service removed", green(CHECK));
5208    }
5209    #[cfg(target_os = "linux")]
5210    if let Some(ref p) = service_unit {
5211        let _ = std::process::Command::new("systemctl")
5212            .args(["--user", "disable", "--now", "shunt"])
5213            .output();
5214        let _ = std::fs::remove_file(p);
5215        let _ = std::process::Command::new("systemctl")
5216            .args(["--user", "daemon-reload"])
5217            .output();
5218        println!("  {} Login service removed", green(CHECK));
5219    }
5220
5221    // 2. Config + credentials dir
5222    if config_dir.exists() {
5223        std::fs::remove_dir_all(&config_dir)
5224            .with_context(|| format!("failed to remove {}", config_dir.display()))?;
5225        println!("  {} Config removed  {}", green(CHECK), dim(&config_dir.display().to_string()));
5226    }
5227
5228    // 3. Data dir (logs, state, pid) — skip if same as config_dir (macOS)
5229    if data_dir.exists() && data_dir != config_dir {
5230        std::fs::remove_dir_all(&data_dir)
5231            .with_context(|| format!("failed to remove {}", data_dir.display()))?;
5232        println!("  {} Data removed    {}", green(CHECK), dim(&data_dir.display().to_string()));
5233    }
5234
5235    // 4. Shell profile — strip ANTHROPIC_BASE_URL lines
5236    if let Some(ref profile_path) = shell_profile {
5237        if profile_has_export {
5238            if let Ok(contents) = std::fs::read_to_string(profile_path) {
5239                let cleaned: String = contents
5240                    .lines()
5241                    .filter(|l| {
5242                        !l.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:")
5243                            && *l != "# Added by shunt"
5244                    })
5245                    .collect::<Vec<_>>()
5246                    .join("\n");
5247                // Preserve trailing newline if original had one
5248                let cleaned = if contents.ends_with('\n') {
5249                    format!("{cleaned}\n")
5250                } else {
5251                    cleaned
5252                };
5253                std::fs::write(profile_path, cleaned)?;
5254                println!("  {} Shell export removed  {}", green(CHECK),
5255                    dim(&profile_path.display().to_string()));
5256            }
5257        }
5258    }
5259
5260    // 5. Claude Code settings — remove ANTHROPIC_BASE_URL from user + managed settings
5261    if let Some(ref h) = uninstall_home {
5262        remove_from_settings_file(&h.join(".claude").join("settings.json"));
5263        remove_from_settings_file(&managed_claude_settings_path(h));
5264    }
5265
5266    // 6. Binary — do this last so error messages can still print
5267    if let Some(exe_path) = exe {
5268        // Spawn a tiny shell to delete the binary after this process exits
5269        let path_str = exe_path.display().to_string();
5270        std::process::Command::new("sh")
5271            .args(["-c", &format!("sleep 0.3 && rm -f '{path_str}'")])
5272            .stdin(std::process::Stdio::null())
5273            .stdout(std::process::Stdio::null())
5274            .stderr(std::process::Stdio::null())
5275            .spawn()
5276            .ok();
5277        println!("  {} Binary removed   {}", green(CHECK), dim(&exe_path.display().to_string()));
5278    }
5279
5280    println!();
5281    println!("  {} shunt fully removed.", green(CHECK));
5282    // Only hint if the variable is actually set in this shell session.
5283    if std::env::var("ANTHROPIC_BASE_URL").is_ok() {
5284        println!("  {} Run {} to clear the proxy from this shell session.", dim("·"), cyan("unset ANTHROPIC_BASE_URL"));
5285    }
5286    println!();
5287
5288    Ok(())
5289}
5290
5291// ---------------------------------------------------------------------------
5292// report
5293// ---------------------------------------------------------------------------
5294
5295async fn cmd_report(config_override: Option<PathBuf>) -> Result<()> {
5296    use std::io::{BufRead, BufReader};
5297
5298    let sep = || println!("  {}", dim(&"─".repeat(60)));
5299
5300    println!();
5301    println!("  {}  {}  {}", brand_green(DIAMOND), bold("shunt report"), dim(&format!("v{}", env!("CARGO_PKG_VERSION"))));
5302    println!("  {}", dim("Paste this output when reporting an issue."));
5303    println!("  {}", dim("Emails and tokens are automatically redacted."));
5304    println!();
5305
5306    // ── environment ─────────────────────────────────────────────────────
5307    sep();
5308    println!("  {} {}", dim("·"), bold("environment"));
5309    sep();
5310    println!("  {:<22} {}", dim("version"), env!("CARGO_PKG_VERSION"));
5311    println!("  {:<22} {}", dim("os"), std::env::consts::OS);
5312    println!("  {:<22} {}", dim("arch"), std::env::consts::ARCH);
5313    let config_p = config_override.clone().unwrap_or_else(config_path);
5314    println!("  {:<22} {}", dim("config"), config_p.display());
5315    println!("  {:<22} {}", dim("log"), log_path().display());
5316
5317    // ── accounts ────────────────────────────────────────────────────────
5318    sep();
5319    println!("  {} {}", dim("·"), bold("accounts"));
5320    sep();
5321    match crate::config::load_config(config_override.as_deref()) {
5322        Ok(cfg) => {
5323            println!("  {:<22} {}", dim("count"), cfg.accounts.len());
5324            for (i, acc) in cfg.accounts.iter().enumerate() {
5325                let cred_type = match &acc.credential {
5326                    Some(crate::credential::Credential::Apikey { .. }) => "api-key",
5327                    Some(_) => "oauth",
5328                    None    => "none",
5329                };
5330                println!("  {}  account-{}   {}   {}", dim("·"), i + 1, acc.provider, cred_type);
5331            }
5332        }
5333        Err(e) => println!("  {} {}", red(CROSS), e),
5334    }
5335
5336    // ── proxy status ─────────────────────────────────────────────────────
5337    sep();
5338    println!("  {} {}", dim("·"), bold("proxy"));
5339    sep();
5340    let pid_p = pid_path();
5341    let running = if pid_p.exists() {
5342        let pid_str = std::fs::read_to_string(&pid_p).unwrap_or_default();
5343        let pid: u32 = pid_str.trim().parse().unwrap_or(0);
5344        let alive = pid > 0 && unsafe { libc::kill(pid as i32, 0) } == 0;
5345        if alive {
5346            println!("  {:<22} {} (PID {})", dim("status"), green("running"), pid);
5347        } else {
5348            println!("  {:<22} {} (stale PID {})", dim("status"), yellow("stale"), pid);
5349        }
5350        alive
5351    } else {
5352        println!("  {:<22} {}", dim("status"), red("not running"));
5353        false
5354    };
5355
5356    if running {
5357        if let Ok(cfg) = crate::config::load_config(config_override.as_deref()) {
5358            println!("  {:<22} {}:{}", dim("port"), cfg.server.host, cfg.server.port);
5359            // Try fetching live status
5360            let url = format!("http://{}:{}/status", cfg.server.host, cfg.server.control_port);
5361            match reqwest::Client::new().get(&url).timeout(std::time::Duration::from_secs(2)).send().await {
5362                Ok(r) if r.status().is_success() => {
5363                    if let Ok(v) = r.json::<serde_json::Value>().await {
5364                        if let Some(started_ms) = v["started_ms"].as_u64() {
5365                            let now_ms = SystemTime::now()
5366                                .duration_since(UNIX_EPOCH).ok()
5367                                .map(|d| d.as_millis() as u64)
5368                                .unwrap_or(0);
5369                            let uptime = (now_ms.saturating_sub(started_ms)) / 1000;
5370                            let h = uptime / 3600;
5371                            let m = (uptime % 3600) / 60;
5372                            let s = uptime % 60;
5373                            println!("  {:<22} {}h {}m {}s", dim("uptime"), h, m, s);
5374                        }
5375                        if let Some(reqs) = v["recent_requests"].as_array() {
5376                            println!("  {:<22} {} (recent)", dim("requests"), reqs.len());
5377                        }
5378                        let alltime_usd = v["savings"]["all_time_cost_usd"].as_f64().unwrap_or(0.0);
5379                        let today_usd   = v["savings"]["today_cost_usd"].as_f64().unwrap_or(0.0);
5380                        if alltime_usd > 0.001 {
5381                            println!("  {:<22} {}", dim("saved today"), crate::pricing::fmt_cost(today_usd));
5382                            println!("  {:<22} {}", dim("saved all time"), crate::pricing::fmt_cost(alltime_usd));
5383                        }
5384                    }
5385                }
5386                Ok(r) => println!("  {:<22} HTTP {}", dim("control port"), r.status()),
5387                Err(e) => println!("  {:<22} {}", dim("control port"), e),
5388            }
5389        }
5390    }
5391
5392    // ── routing injection ────────────────────────────────────────────────
5393    sep();
5394    println!("  {} {}", dim("·"), bold("routing injection"));
5395    sep();
5396
5397    let home = dirs::home_dir();
5398    let paths: Vec<(&str, std::path::PathBuf)> = if let Some(ref h) = home {
5399        vec![
5400            ("~/.claude/settings.json",    h.join(".claude").join("settings.json")),
5401            ("managed_settings.json",      managed_claude_settings_path(h)),
5402        ]
5403    } else { vec![] };
5404
5405    for (label, path) in &paths {
5406        let url = read_anthropic_base_url_from_file(path);
5407        match url.as_deref() {
5408            Some(u) => println!("  {:<28} {} = {}", dim(label), green(CHECK), u),
5409            None if path.exists() => println!("  {:<28} {} not set", dim(label), dim("·")),
5410            None => println!("  {:<28} {} file not found", dim(label), dim("·")),
5411        }
5412    }
5413
5414    let shell_val = std::env::var("ANTHROPIC_BASE_URL").ok();
5415    match shell_val.as_deref() {
5416        Some(v) => println!("  {:<28} {} = {}", dim("shell $ANTHROPIC_BASE_URL"), green(CHECK), v),
5417        None    => println!("  {:<28} {} not set", dim("shell $ANTHROPIC_BASE_URL"), dim("·")),
5418    }
5419
5420    // ── notification log ─────────────────────────────────────────────────
5421    sep();
5422    println!("  {} {}", dim("·"), bold("last 50 notification triggers"));
5423    sep();
5424    let notify_log = crate::config::notify_log_path();
5425    if notify_log.exists() {
5426        let file = std::fs::File::open(&notify_log)?;
5427        let reader = BufReader::new(file);
5428        let mut ring: std::collections::VecDeque<String> = std::collections::VecDeque::with_capacity(51);
5429        for line in reader.lines().flatten() {
5430            if ring.len() >= 50 { ring.pop_front(); }
5431            ring.push_back(line);
5432        }
5433        for l in &ring { println!("  {l}"); }
5434    } else {
5435        println!("  {} no notification log found ({})", dim("·"), notify_log.display());
5436    }
5437
5438    // ── last 100 log lines ───────────────────────────────────────────────
5439    sep();
5440    println!("  {} {}", dim("·"), bold("last 100 log lines  (redacted)"));
5441    sep();
5442    let log = log_path();
5443    if log.exists() {
5444        let file = std::fs::File::open(&log)?;
5445        let reader = BufReader::new(file);
5446        let mut ring: std::collections::VecDeque<String> = std::collections::VecDeque::with_capacity(101);
5447        for line in reader.lines().flatten() {
5448            if ring.len() >= 100 { ring.pop_front(); }
5449            ring.push_back(redact_log_line(&line));
5450        }
5451        for l in &ring { println!("  {l}"); }
5452    } else {
5453        println!("  {} no log file found", dim("·"));
5454    }
5455
5456    sep();
5457    println!();
5458    Ok(())
5459}
5460
5461/// Read ANTHROPIC_BASE_URL from the `env` key in a Claude settings JSON file.
5462fn read_anthropic_base_url_from_file(path: &std::path::Path) -> Option<String> {
5463    let content = std::fs::read_to_string(path).ok()?;
5464    let v: serde_json::Value = serde_json::from_str(&content).ok()?;
5465    v["env"]["ANTHROPIC_BASE_URL"].as_str().map(|s| s.to_owned())
5466}
5467
5468/// Redact email addresses and long tokens from a log line, and strip ANSI codes.
5469fn redact_log_line(line: &str) -> String {
5470    let clean = strip_ansi(line);
5471    // Redact email addresses: anything@anything.anything
5472    let re_email = regex::Regex::new(r"[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}").unwrap();
5473    let s = re_email.replace_all(&clean, "[email]");
5474    // Redact long base64/hex strings that look like tokens (≥40 chars to avoid short IDs)
5475    let re_token = regex::Regex::new(r"[A-Za-z0-9+/\-_]{40,}={0,2}").unwrap();
5476    let s = re_token.replace_all(&s, "[token]");
5477    s.into_owned()
5478}
5479
5480// ---------------------------------------------------------------------------
5481// service
5482// ---------------------------------------------------------------------------
5483
5484#[cfg(target_os = "macos")]
5485fn service_plist_path() -> PathBuf {
5486    dirs::home_dir()
5487        .unwrap_or_else(|| PathBuf::from("/tmp"))
5488        .join("Library/LaunchAgents/sh.shunt.proxy.plist")
5489}
5490
5491#[cfg(target_os = "linux")]
5492fn service_unit_path() -> PathBuf {
5493    dirs::home_dir()
5494        .unwrap_or_else(|| PathBuf::from("/tmp"))
5495        .join(".config/systemd/user/shunt.service")
5496}
5497
5498/// Write the platform service file and enable it to run at login.
5499/// Write the platform service file and attempt to activate it.
5500/// Returns `true` if the service was successfully loaded/started by the init
5501/// system, `false` if the plist/unit was written but activation was skipped
5502/// or timed out (e.g. SSH session without a GUI bootstrap context).
5503fn register_service() -> Result<bool> {
5504    let exe = std::env::current_exe().context("cannot locate current executable")?;
5505    let exe_str = exe.display().to_string();
5506
5507    #[cfg(target_os = "macos")]
5508    {
5509        let plist_path = service_plist_path();
5510        let plist_was_present = plist_path.exists();
5511        if let Some(parent) = plist_path.parent() {
5512            std::fs::create_dir_all(parent)?;
5513        }
5514        let plist = format!(r#"<?xml version="1.0" encoding="UTF-8"?>
5515<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
5516  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5517<plist version="1.0">
5518<dict>
5519  <key>Label</key>
5520  <string>sh.shunt.proxy</string>
5521  <key>ProgramArguments</key>
5522  <array>
5523    <string>{exe_str}</string>
5524    <string>start</string>
5525    <string>--foreground</string>
5526  </array>
5527  <key>RunAtLoad</key>
5528  <true/>
5529  <key>KeepAlive</key>
5530  <true/>
5531  <key>StandardOutPath</key>
5532  <string>{home}/Library/Logs/shunt.log</string>
5533  <key>StandardErrorPath</key>
5534  <string>{home}/Library/Logs/shunt.log</string>
5535</dict>
5536</plist>
5537"#,
5538            exe_str = exe_str,
5539            home = dirs::home_dir().unwrap_or_default().display(),
5540        );
5541        std::fs::write(&plist_path, &plist)?;
5542
5543        // launchctl hangs in SSH sessions without a GUI bootstrap context.
5544        // Wrap both unload and load in threads with timeouts.
5545        let plist_str = plist_path.display().to_string();
5546
5547        // Unload only if a plist was already there (i.e. this is a reinstall)
5548        if plist_was_present {
5549            let p = plist_str.clone();
5550            let (tx, rx) = std::sync::mpsc::channel();
5551            std::thread::spawn(move || {
5552                let _ = std::process::Command::new("launchctl")
5553                    .args(["unload", &p])
5554                    .output();
5555                let _ = tx.send(());
5556            });
5557            let _ = rx.recv_timeout(std::time::Duration::from_secs(4));
5558        }
5559
5560        // Load
5561        let (tx, rx) = std::sync::mpsc::channel();
5562        std::thread::spawn(move || {
5563            let ok = std::process::Command::new("launchctl")
5564                .args(["load", "-w", &plist_str])
5565                .output()
5566                .map(|o| o.status.success())
5567                .unwrap_or(false);
5568            let _ = tx.send(ok);
5569        });
5570
5571        let loaded = rx
5572            .recv_timeout(std::time::Duration::from_secs(4))
5573            .unwrap_or(false);
5574
5575        return Ok(loaded);
5576    }
5577
5578    #[cfg(target_os = "linux")]
5579    {
5580        let unit_path = service_unit_path();
5581        if let Some(parent) = unit_path.parent() {
5582            std::fs::create_dir_all(parent)?;
5583        }
5584        let unit = format!(
5585            "[Unit]\nDescription=shunt Claude Code proxy\nAfter=network.target\n\n\
5586             [Service]\nExecStart={exe_str} start --foreground\nRestart=always\nRestartSec=5\n\n\
5587             [Install]\nWantedBy=default.target\n"
5588        );
5589        std::fs::write(&unit_path, &unit)?;
5590
5591        let _ = std::process::Command::new("systemctl")
5592            .args(["--user", "daemon-reload"])
5593            .output();
5594
5595        let out = std::process::Command::new("systemctl")
5596            .args(["--user", "enable", "--now", "shunt"])
5597            .output()
5598            .context("failed to run systemctl")?;
5599
5600        return Ok(out.status.success());
5601    }
5602
5603    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
5604    bail!("Service management is only supported on macOS and Linux.");
5605
5606    #[allow(unreachable_code)]
5607    Ok(false)
5608}
5609
5610async fn cmd_service_install() -> Result<()> {
5611    print_splash(&[
5612        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
5613        dim("Service install"),
5614        String::new(),
5615    ]);
5616
5617    // 1. Ensure config + credentials exist.
5618    //    If stdin is not a TTY (e.g. curl | sh), skip interactive setup to
5619    //    avoid blocking on keychain/OAuth. The service is still registered and
5620    //    the proxy started; user runs `shunt setup` in a terminal to finish.
5621    let config_p = config_path();
5622    let stdin_is_tty = unsafe { libc::isatty(libc::STDIN_FILENO) != 0 };
5623    if !config_p.exists() {
5624        if stdin_is_tty {
5625            cmd_setup_auto(None).await?;
5626        } else {
5627            println!("  {} No config — run {} in a terminal to import credentials",
5628                yellow("·"), cyan("shunt setup"));
5629        }
5630    }
5631
5632    // 2. Read port from config for shell export
5633    let port = crate::config::load_config(None)
5634        .map(|c| c.server.port)
5635        .unwrap_or(8082);
5636
5637    // 3. Register the platform service
5638    print!("  {} Registering login service… ", dim("·"));
5639    use std::io::Write as _;
5640    std::io::stdout().flush().ok();
5641    let service_loaded = register_service()?;
5642    if service_loaded {
5643        println!("{}", green("done"));
5644    } else {
5645        println!("{}", dim("skipped (SSH session — activates on next login)"));
5646    }
5647
5648    // 4. If launchd/systemd couldn't activate the service (e.g. SSH session
5649    //    without a GUI bootstrap context), start the proxy directly.
5650    if !service_loaded {
5651        print!("  {} Starting proxy… ", dim("·"));
5652        std::io::stdout().flush().ok();
5653        let exe = std::env::current_exe().context("cannot locate current executable")?;
5654        let _ = std::process::Command::new(&exe)
5655            .args(["start", "--daemon"])
5656            .stdin(std::process::Stdio::null())
5657            .stdout(std::process::Stdio::null())
5658            .stderr(std::process::Stdio::null())
5659            .spawn();
5660    }
5661
5662    // 5. Write shell export silently
5663    auto_write_shell_export(port);
5664
5665    // 6. Wait for proxy to be healthy
5666    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
5667    let config = crate::config::load_config(None).ok();
5668    let host = config.as_ref().map(|c| c.server.host.clone()).unwrap_or_else(|| "127.0.0.1".into());
5669    let running = wait_for_health(&host, port, 8).await;
5670    if !service_loaded {
5671        println!("{}", if running { green("done").to_string() } else { dim("starting…").to_string() });
5672    }
5673
5674    println!();
5675    if running {
5676        println!("  {}  {}  {}", green(DOT), green_bold("proxy running"),
5677            cyan(&format!("http://{host}:{port}")));
5678    } else {
5679        println!("  {}  {} — proxy starting in background",
5680            yellow(DOT), yellow("starting"));
5681    }
5682
5683    #[cfg(target_os = "macos")]
5684    if service_loaded {
5685        println!("  {}  LaunchAgent registered — starts automatically at login", green(CHECK));
5686    } else {
5687        println!("  {}  LaunchAgent written — will activate on next login", yellow("·"));
5688        println!("  {}  To activate now (in a GUI session): {}",
5689            dim("·"), cyan("launchctl load -w ~/Library/LaunchAgents/sh.shunt.proxy.plist"));
5690    }
5691    #[cfg(target_os = "linux")]
5692    if service_loaded {
5693        println!("  {}  systemd user unit registered — starts automatically at login", green(CHECK));
5694    } else {
5695        println!("  {}  systemd unit written — run {} to activate",
5696            yellow("·"), cyan("systemctl --user enable --now shunt"));
5697    }
5698
5699    println!();
5700    println!("  {} To unregister: {}", dim("·"), cyan("shunt service uninstall"));
5701    println!();
5702
5703    Ok(())
5704}
5705
5706async fn cmd_service_uninstall() -> Result<()> {
5707    #[cfg(target_os = "macos")]
5708    {
5709        let plist_path = service_plist_path();
5710        if plist_path.exists() {
5711            let _ = std::process::Command::new("launchctl")
5712                .args(["unload", &plist_path.display().to_string()])
5713                .output();
5714            std::fs::remove_file(&plist_path)
5715                .context("failed to remove plist")?;
5716            println!("  {} Service unregistered.", green(CHECK));
5717        } else {
5718            println!("  {} Service not registered.", dim("·"));
5719        }
5720    }
5721
5722    #[cfg(target_os = "linux")]
5723    {
5724        let unit_path = service_unit_path();
5725        let _ = std::process::Command::new("systemctl")
5726            .args(["--user", "disable", "--now", "shunt"])
5727            .output();
5728        if unit_path.exists() {
5729            std::fs::remove_file(&unit_path)
5730                .context("failed to remove unit file")?;
5731        }
5732        let _ = std::process::Command::new("systemctl")
5733            .args(["--user", "daemon-reload"])
5734            .output();
5735        println!("  {} Service unregistered.", green(CHECK));
5736    }
5737
5738    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
5739    bail!("Service management is only supported on macOS and Linux.");
5740
5741    println!();
5742    Ok(())
5743}
5744
5745async fn cmd_service_status() -> Result<()> {
5746    #[cfg(target_os = "macos")]
5747    {
5748        let plist_path = service_plist_path();
5749        let registered = plist_path.exists();
5750        if registered {
5751            println!("  {} Registered  {}", green(CHECK), dim(&plist_path.display().to_string()));
5752        } else {
5753            println!("  {} Not registered (run {})", dim("·"), cyan("shunt service install"));
5754        }
5755
5756        // Check if launchd considers it running
5757        let out = std::process::Command::new("launchctl")
5758            .args(["list", "sh.shunt.proxy"])
5759            .output();
5760        let running = out.map(|o| o.status.success()).unwrap_or(false);
5761        if running {
5762            println!("  {} Running (launchd)", green(DOT));
5763        } else {
5764            println!("  {} Not running", dim(DOT));
5765        }
5766    }
5767
5768    #[cfg(target_os = "linux")]
5769    {
5770        let unit_path = service_unit_path();
5771        let registered = unit_path.exists();
5772        if registered {
5773            println!("  {} Registered  {}", green(CHECK), dim(&unit_path.display().to_string()));
5774        } else {
5775            println!("  {} Not registered (run {})", dim("·"), cyan("shunt service install"));
5776        }
5777
5778        let out = std::process::Command::new("systemctl")
5779            .args(["--user", "is-active", "shunt"])
5780            .output();
5781        let active = out.map(|o| o.status.success()).unwrap_or(false);
5782        if active {
5783            println!("  {} Running (systemd)", green(DOT));
5784        } else {
5785            println!("  {} Not running", dim(DOT));
5786        }
5787    }
5788
5789    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
5790    println!("  {} Service management is only supported on macOS and Linux.", dim("·"));
5791
5792    println!();
5793    Ok(())
5794}
5795
5796fn detect_shell_profile() -> Option<PathBuf> {
5797    let home = dirs::home_dir()?;
5798    if let Ok(shell) = std::env::var("SHELL") {
5799        if shell.contains("zsh")  { return Some(home.join(".zshrc")); }
5800        if shell.contains("fish") { return Some(home.join(".config/fish/config.fish")); }
5801        if shell.contains("bash") {
5802            let p = home.join(".bash_profile");
5803            return Some(if p.exists() { p } else { home.join(".bashrc") });
5804        }
5805    }
5806    for f in &[".zshrc", ".bashrc", ".bash_profile"] {
5807        let p = home.join(f);
5808        if p.exists() { return Some(p); }
5809    }
5810    None
5811}