shift-preflight-cli 0.10.2

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

mod env;
mod proxy;
mod setup;

/// SHIFT — Smart Hybrid Input Filtering & Transformation
///
/// A multimodal preflight layer that automatically adapts inputs
/// before they are sent to an AI model.
///
/// Reads a JSON request payload from stdin or a file, transforms
/// images to meet provider constraints, and writes the safe payload
/// to stdout.
#[derive(Parser, Debug)]
#[command(name = "shift-ai", version, about)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Input file (JSON request payload). Reads stdin if omitted.
    #[arg()]
    file: Option<String>,

    /// Target provider
    #[arg(short, long, default_value = "openai", value_parser = ["openai", "anthropic", "claude"])]
    provider: String,

    /// Drive mode
    #[arg(short, long, default_value = "balanced", value_parser = ["performance", "perf", "balanced", "bal", "economy", "eco"])]
    mode: String,

    /// SVG handling mode
    #[arg(long, default_value = "raster", value_parser = ["raster", "source", "hybrid"])]
    svg_mode: String,

    /// Output format
    ///   json        = transformed payload (default)
    ///   report      = human-readable transformation report
    ///   json-report = machine-readable report as JSON (for dashboards)
    ///   both        = report to stderr + payload to stdout
    #[arg(short, long, default_value = "json", value_parser = ["json", "report", "json-report", "both"])]
    output: String,

    /// Show what would change without modifying
    #[arg(long)]
    dry_run: bool,

    /// Custom provider profile JSON file
    #[arg(long)]
    profile: Option<String>,

    /// Target model (overrides model in payload)
    #[arg(long)]
    model: Option<String>,

    /// Disable saving run statistics to ~/.shift/stats.jsonl
    #[arg(long)]
    no_stats: bool,

    /// Verbose output
    #[arg(short, long)]
    verbose: bool,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Show cumulative token savings across all recorded runs
    Gain {
        /// Show day-by-day breakdown
        #[arg(long)]
        daily: bool,

        /// Output as JSON
        #[arg(long, value_parser = ["json"])]
        format: Option<String>,
    },

    /// Validate payload and preview image optimizations without transforming
    ///
    /// Runs the full inspection pipeline in dry-run mode and outputs a
    /// structured JSON report with environment checks, per-image analysis,
    /// token estimates, and optimization recommendations.
    Preflight {
        /// Input file (JSON request payload). Reads stdin if omitted.
        #[arg()]
        file: Option<String>,

        /// Target provider
        #[arg(short, long, default_value = "openai", value_parser = ["openai", "anthropic", "claude"])]
        provider: String,

        /// Drive mode
        #[arg(short, long, default_value = "balanced", value_parser = ["performance", "perf", "balanced", "bal", "economy", "eco"])]
        mode: String,

        /// Target model (overrides model in payload)
        #[arg(long)]
        model: Option<String>,

        /// Custom provider profile JSON file
        #[arg(long)]
        profile: Option<String>,

        /// Verbose output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Manage the SHIFT preflight proxy daemon
    ///
    /// The proxy intercepts AI API requests and optimizes image payloads
    /// before forwarding to the provider. It supports Anthropic, OpenAI,
    /// and Google routes simultaneously.
    Proxy {
        #[command(subcommand)]
        action: ProxyAction,
    },

    /// Output configuration for an AI agent
    ///
    /// Prints the correct config for each agent (env vars, TOML snippets,
    /// or manual instructions). For Claude Code, add to your shell profile:
    ///
    ///   eval "$(shift-ai env claude-code)"
    Env {
        /// Agent name: opencode, claude-code, codex, cursor
        agent: Option<String>,

        /// Proxy port
        #[arg(long, default_value = "8787")]
        port: u16,

        /// Show all agents
        #[arg(long)]
        all: bool,

        /// List supported agents and their env vars
        #[arg(long)]
        list: bool,
    },

    /// Interactive setup for multi-agent SHIFT integration
    ///
    /// Detects installed AI agents, configures each to use the SHIFT proxy,
    /// and optionally installs a macOS LaunchAgent for auto-start.
    Setup,
}

#[derive(Subcommand, Debug)]
enum ProxyAction {
    /// Start the proxy daemon (idempotent — skips if already running)
    Start {
        /// Port to listen on
        #[arg(long, default_value = "8787")]
        port: u16,

        /// Drive mode: performance, balanced, economy
        #[arg(long, default_value = "balanced")]
        mode: String,

        /// Suppress output
        #[arg(long)]
        quiet: bool,

        /// Run in foreground (for LaunchAgent / systemd)
        #[arg(long)]
        foreground: bool,

        /// Enable verbose logging
        #[arg(long, short)]
        verbose: bool,
    },

    /// Stop the proxy daemon
    Stop {
        /// Suppress output
        #[arg(long)]
        quiet: bool,
    },

    /// Show proxy status
    Status {
        /// Port to check
        #[arg(long, default_value = "8787")]
        port: u16,
    },

    /// Ensure proxy is running (start if needed, no-op if healthy)
    ///
    /// This is the primary command that agent plugins should call.
    /// It's fast (<5ms) when the proxy is already running.
    Ensure {
        /// Port to listen on
        #[arg(long, default_value = "8787")]
        port: u16,

        /// Drive mode: performance, balanced, economy
        #[arg(long, default_value = "balanced")]
        mode: String,

        /// Suppress output
        #[arg(long)]
        quiet: bool,
    },
}

/// Structured preflight report output (JSON to stdout).
#[derive(Debug, Serialize)]
struct PreflightReport {
    shift_version: String,
    provider: String,
    model_detected: Option<String>,
    mode: String,
    api_key_present: bool,
    api_key_env_var: String,
    images_found: usize,
    images_needing_transform: usize,
    images_ok: usize,
    total_original_bytes: usize,
    estimated_transformed_bytes: usize,
    estimated_byte_savings_pct: f64,
    token_estimate: TokenSavings,
    images: Vec<ImageMetrics>,
    warnings: Vec<String>,
    recommendations: Vec<String>,
}

/// Maximum stdin input size: 500 MB
const MAX_STDIN_BYTES: u64 = 500_000_000;

fn main() {
    if let Err(e) = run() {
        eprintln!("shift-ai: error: {:#}", e);
        std::process::exit(1);
    }
}

fn run() -> Result<()> {
    let cli = Cli::parse();

    // Handle subcommands
    if let Some(cmd) = &cli.command {
        return match cmd {
            Commands::Gain { daily, format } => run_gain(*daily, format.as_deref()),
            Commands::Preflight {
                file,
                provider,
                mode,
                model,
                profile,
                verbose,
            } => run_preflight(
                file,
                provider,
                mode,
                model.as_deref(),
                profile.as_deref(),
                *verbose,
            ),
            Commands::Proxy { action } => match action {
                ProxyAction::Start {
                    port,
                    mode,
                    quiet,
                    foreground,
                    verbose,
                } => {
                    if *foreground {
                        // Run the native Rust proxy server in foreground (blocking).
                        // Used by daemon spawn and LaunchAgent/systemd.
                        proxy::run_foreground(*port, mode.as_str(), *verbose)
                    } else {
                        proxy::start(Some(*port), Some(mode.as_str()), *quiet)
                    }
                }
                ProxyAction::Stop { quiet } => proxy::stop(*quiet),
                ProxyAction::Status { port } => proxy::status(Some(*port)),
                ProxyAction::Ensure { port, mode, quiet } => {
                    proxy::ensure(Some(*port), Some(mode.as_str()), *quiet)
                }
            },
            Commands::Env {
                agent,
                port,
                all,
                list,
            } => {
                if *list {
                    env::print_agent_list(Some(*port))
                } else if *all {
                    env::print_env_all(Some(*port))
                } else if let Some(agent) = agent {
                    env::print_env(agent, Some(*port))
                } else {
                    env::print_agent_list(Some(*port))
                }
            }
            Commands::Setup => setup::run_setup(),
        };
    }

    // Read input
    let input = read_input(&cli.file)?;

    // Parse JSON
    let payload: serde_json::Value =
        serde_json::from_str(&input).context("failed to parse input as JSON")?;

    // Build config
    let drive_mode: DriveMode = cli.mode.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    let svg_mode: SvgMode = cli
        .svg_mode
        .parse()
        .map_err(|e: String| anyhow::anyhow!(e))?;

    let provider = if cli.provider == "claude" {
        "anthropic".to_string()
    } else {
        cli.provider.clone()
    };

    // Fix #7: Thread profile_path through ShiftConfig instead of env var
    let config = ShiftConfig {
        mode: drive_mode,
        svg_mode,
        provider: provider.clone(),
        model: cli.model,
        dry_run: cli.dry_run,
        verbose: cli.verbose,
        profile_path: cli.profile,
        limits: shift_preflight::SafetyLimits::default(),
    };

    if cli.verbose {
        eprintln!(
            "shift-ai: mode={}, provider={}, svg_mode={}, dry_run={}",
            config.mode, config.provider, config.svg_mode, config.dry_run
        );
    }

    // Process (with timing)
    let start = std::time::Instant::now();
    let (result, report) = shift_preflight::process(&payload, &config)?;
    let duration_ms = start.elapsed().as_millis() as u64;

    // Record stats (unless disabled or dry-run)
    if !cli.no_stats && !cli.dry_run && report.images_found > 0 {
        let record = shift_preflight::stats::record_from_report(&report, &provider, duration_ms);
        if let Err(e) = shift_preflight::stats::record_run(&record, None) {
            eprintln!("shift-ai: warning: failed to save stats: {}", e);
        }
    }

    // Output
    match cli.output.as_str() {
        "json" => {
            let json = serde_json::to_string_pretty(&result)?;
            println!("{}", json);

            if cli.verbose || cli.dry_run {
                eprintln!("{}", report);
            }
        }
        "report" => {
            println!("{}", report);
        }
        "json-report" => {
            let json = serde_json::to_string_pretty(&report)?;
            println!("{}", json);
        }
        "both" => {
            eprintln!("{}", report);
            let json = serde_json::to_string_pretty(&result)?;
            println!("{}", json);
        }
        _ => unreachable!(),
    }

    Ok(())
}

fn run_preflight(
    file: &Option<String>,
    provider: &str,
    mode: &str,
    model: Option<&str>,
    profile: Option<&str>,
    verbose: bool,
) -> Result<()> {
    // 1. Read input
    let input = read_input(file)?;
    let payload: serde_json::Value =
        serde_json::from_str(&input).context("failed to parse input as JSON")?;

    // 2. Resolve provider
    let provider = if provider == "claude" {
        "anthropic"
    } else {
        provider
    };

    // 3. Detect model from payload if not overridden
    let model_detected = model.map(String::from).or_else(|| {
        payload
            .get("model")
            .and_then(|v| v.as_str())
            .map(String::from)
    });

    // 4. Check API key
    let api_key_env_var = match provider {
        "anthropic" => "ANTHROPIC_API_KEY",
        _ => "OPENAI_API_KEY",
    };
    let api_key_present = std::env::var(api_key_env_var).is_ok();

    // 5. Build config and run dry-run pipeline
    let drive_mode: DriveMode = mode.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    let config = ShiftConfig {
        mode: drive_mode,
        svg_mode: SvgMode::Raster,
        provider: provider.to_string(),
        model: model.map(String::from),
        dry_run: true,
        verbose,
        profile_path: profile.map(String::from),
        limits: shift_preflight::SafetyLimits::default(),
    };

    let (_result, report) = shift_preflight::process(&payload, &config)?;

    // 6. Compute images needing transform vs ok
    let images_needing_transform = report
        .image_metrics
        .iter()
        .filter(|m| {
            m.original_width != m.transformed_width
                || m.original_height != m.transformed_height
                || m.format_before != m.format_after
        })
        .count();
    let images_ok = report.images_found.saturating_sub(images_needing_transform);

    // 7. Compute byte savings percentage
    let estimated_byte_savings_pct = if report.original_size > 0 {
        let diff = report.original_size as f64 - report.transformed_size as f64;
        (diff / report.original_size as f64) * 100.0
    } else {
        0.0
    };

    // 8. Build recommendations
    let mut recommendations = Vec::new();

    if !api_key_present {
        recommendations.push(format!(
            "Set {} environment variable before sending API requests",
            api_key_env_var
        ));
    }

    if images_needing_transform > 0 && drive_mode != DriveMode::Economy {
        // Estimate what economy mode would save
        let eco_config = ShiftConfig {
            mode: DriveMode::Economy,
            ..config.clone()
        };
        if let Ok((_eco_result, eco_report)) = shift_preflight::process(&payload, &eco_config) {
            let current_anthropic = report.token_savings.anthropic_after;
            let eco_anthropic = eco_report.token_savings.anthropic_after;
            if eco_anthropic < current_anthropic {
                let extra_pct = if current_anthropic > 0 {
                    ((current_anthropic - eco_anthropic) as f64 / current_anthropic as f64) * 100.0
                } else {
                    0.0
                };
                recommendations.push(format!(
                    "Economy mode would save an additional {:.0}% Anthropic tokens ({} -> {} tokens)",
                    extra_pct,
                    fmt_tokens(current_anthropic),
                    fmt_tokens(eco_anthropic),
                ));
            }
        }
    }

    if report.images_found == 0 {
        recommendations
            .push("No images found in payload — shift-ai optimization not needed".to_string());
    }

    if images_needing_transform == 0 && report.images_found > 0 {
        recommendations.push(
            "All images are within provider constraints — no optimization needed".to_string(),
        );
    }

    // 9. Build and output the preflight report
    let preflight = PreflightReport {
        shift_version: env!("CARGO_PKG_VERSION").to_string(),
        provider: provider.to_string(),
        model_detected,
        mode: format!("{}", drive_mode),
        api_key_present,
        api_key_env_var: api_key_env_var.to_string(),
        images_found: report.images_found,
        images_needing_transform,
        images_ok,
        total_original_bytes: report.original_size,
        estimated_transformed_bytes: report.transformed_size,
        estimated_byte_savings_pct,
        token_estimate: report.token_savings,
        images: report.image_metrics,
        warnings: report.warnings,
        recommendations,
    };

    let json = serde_json::to_string_pretty(&preflight)?;
    println!("{}", json);

    Ok(())
}

fn run_gain(daily: bool, format: Option<&str>) -> Result<()> {
    use colored::Colorize;

    let load_result = shift_preflight::stats::load_records(None)?;
    let records = load_result.records;
    let use_color = std::io::stdout().is_terminal();

    if records.is_empty() {
        println!("No SHIFT runs recorded yet. Stats are saved automatically after each run.");
        println!("Use --no-stats to disable.");
        return Ok(());
    }

    if daily {
        let days = shift_preflight::stats::daily_breakdown(&records);
        if format == Some("json") {
            let json_days: Vec<serde_json::Value> = days
                .iter()
                .map(|d| {
                    serde_json::json!({
                        "date": d.date,
                        "runs": d.runs,
                        "images": d.images,
                        "openai_tokens_saved": d.openai_saved,
                        "anthropic_tokens_saved": d.anthropic_saved,
                    })
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&json_days)?);
        } else {
            if use_color {
                println!("{}", "SHIFT Daily Token Savings".bold().green());
                println!("{}", "".repeat(58).green());
            } else {
                println!("=== SHIFT Daily Token Savings ===");
            }
            println!();
            println!(
                "{:<12} {:>5} {:>7} {:>15} {:>15}",
                "Date", "Runs", "Images", "OpenAI saved", "Anthropic saved"
            );
            println!("{}", "".repeat(58));
            for d in &days {
                let oai = fmt_tokens(d.openai_saved);
                let ant = fmt_tokens(d.anthropic_saved);
                if use_color {
                    println!(
                        "{:<12} {:>5} {:>7} {:>15} {:>15}",
                        d.date,
                        d.runs,
                        d.images,
                        oai.green(),
                        ant.green(),
                    );
                } else {
                    println!(
                        "{:<12} {:>5} {:>7} {:>15} {:>15}",
                        d.date, d.runs, d.images, oai, ant,
                    );
                }
            }
        }
    } else {
        let summary = shift_preflight::stats::summarize(&records);
        if format == Some("json") {
            let json = serde_json::json!({
                "total_runs": summary.total_runs,
                "total_images": summary.total_images,
                "total_modified": summary.total_modified,
                "bytes_saved": summary.bytes_saved(),
                "total_duration_ms": summary.total_duration_ms,
                "openai_tokens_before": summary.total_openai_before,
                "openai_tokens_after": summary.total_openai_after,
                "openai_tokens_saved": summary.openai_saved(),
                "openai_pct": summary.openai_pct(),
                "anthropic_tokens_before": summary.total_anthropic_before,
                "anthropic_tokens_after": summary.total_anthropic_after,
                "anthropic_tokens_saved": summary.anthropic_saved(),
                "anthropic_pct": summary.anthropic_pct(),
                "by_provider": summary.by_provider.iter().map(|p| {
                    serde_json::json!({
                        "provider": p.provider,
                        "runs": p.runs,
                        "images": p.images,
                        "tokens_saved": p.tokens_saved,
                        "overall_pct": p.overall_pct,
                        "avg_duration_ms": p.avg_duration_ms,
                    })
                }).collect::<Vec<_>>(),
                "by_action": summary.by_action.iter().map(|a| {
                    serde_json::json!({
                        "action": a.action,
                        "count": a.count,
                    })
                }).collect::<Vec<_>>(),
            });
            println!("{}", serde_json::to_string_pretty(&json)?);
        } else {
            // ── Header ──────────────────────────────────────────────
            if use_color {
                println!("{}", "SHIFT Token Savings".bold().green());
                println!("{}", "".repeat(50).green());
            } else {
                println!("=== SHIFT Token Savings ===");
            }
            println!();

            // ── Summary stats ───────────────────────────────────────
            println!("{:<18}{}", "Total runs:", summary.total_runs);
            println!(
                "{:<18}{} ({} modified)",
                "Images processed:", summary.total_images, summary.total_modified
            );
            println!("{:<18}{}", "Bytes saved:", fmt_bytes(summary.bytes_saved()));
            if summary.total_duration_ms > 0 {
                let avg_ms = if summary.total_runs > 0 {
                    summary.total_duration_ms / summary.total_runs as u64
                } else {
                    0
                };
                println!(
                    "{:<18}{} (avg {})",
                    "Total exec time:",
                    fmt_duration(summary.total_duration_ms),
                    fmt_duration(avg_ms)
                );
            }
            if load_result.skipped_lines > 0 {
                let msg = format!(
                    "{} corrupted stats line(s) skipped",
                    load_result.skipped_lines
                );
                if use_color {
                    println!("{:<18}{}", "Warning:", msg.yellow());
                } else {
                    println!("{:<18}{}", "Warning:", msg);
                }
            }
            println!();

            // ── Token savings ────────────────────────────────────────
            if summary.total_openai_before > 0 {
                let pct_str = format!("{:.1}%", summary.openai_pct());
                if use_color {
                    println!(
                        "{:<18}{} -> {} tokens  ({})",
                        "OpenAI tokens:",
                        fmt_tokens(summary.total_openai_before),
                        fmt_tokens(summary.total_openai_after),
                        colorize_pct(&pct_str, summary.openai_pct(), use_color),
                    );
                } else {
                    println!(
                        "{:<18}{} -> {} tokens  ({} saved)",
                        "OpenAI tokens:",
                        fmt_tokens(summary.total_openai_before),
                        fmt_tokens(summary.total_openai_after),
                        pct_str,
                    );
                }
            }
            if summary.total_anthropic_before > 0 {
                let pct_str = format!("{:.1}%", summary.anthropic_pct());
                if use_color {
                    println!(
                        "{:<18}{} -> {} tokens  ({})",
                        "Anthropic tokens:",
                        fmt_tokens(summary.total_anthropic_before),
                        fmt_tokens(summary.total_anthropic_after),
                        colorize_pct(&pct_str, summary.anthropic_pct(), use_color),
                    );
                } else {
                    println!(
                        "{:<18}{} -> {} tokens  ({} saved)",
                        "Anthropic tokens:",
                        fmt_tokens(summary.total_anthropic_before),
                        fmt_tokens(summary.total_anthropic_after),
                        pct_str,
                    );
                }
            }

            // ── Efficiency meter ─────────────────────────────────────
            // Use the best savings percentage across providers
            let best_pct = if summary.anthropic_pct() > summary.openai_pct() {
                summary.anthropic_pct()
            } else {
                summary.openai_pct()
            };
            println!();
            print_efficiency_meter(best_pct, use_color);

            // ── By Provider ──────────────────────────────────────────
            if summary.by_provider.len() > 1 {
                println!();
                if use_color {
                    println!("{}", "By Provider".bold().green());
                } else {
                    println!("By Provider");
                }
                println!();
                println!(
                    " {:<3}{:<14}{:>6}{:>9}{:>14}{:>8}{:>8}  Impact",
                    "#", "Provider", "Runs", "Images", "Tokens Saved", "Avg%", "Time"
                );
                println!(" {}", "".repeat(70));
                let max_saved = summary
                    .by_provider
                    .iter()
                    .map(|p| p.tokens_saved)
                    .max()
                    .unwrap_or(1);
                for (i, p) in summary.by_provider.iter().enumerate() {
                    let pct_str = format!("{:.1}%", p.overall_pct);
                    let bar = mini_bar(p.tokens_saved, max_saved, 10, use_color);
                    if use_color {
                        println!(
                            " {:<3}{:<14}{:>6}{:>9}{:>14}{:>8}{:>8}  {}",
                            format!("{}.", i + 1),
                            p.provider,
                            p.runs,
                            p.images,
                            fmt_tokens(p.tokens_saved),
                            colorize_pct(&pct_str, p.overall_pct, use_color),
                            fmt_duration(p.avg_duration_ms),
                            bar,
                        );
                    } else {
                        println!(
                            " {:<3}{:<14}{:>6}{:>9}{:>14}{:>8}{:>8}  {}",
                            format!("{}.", i + 1),
                            p.provider,
                            p.runs,
                            p.images,
                            fmt_tokens(p.tokens_saved),
                            pct_str,
                            fmt_duration(p.avg_duration_ms),
                            bar,
                        );
                    }
                }
            }

            // ── By Action ────────────────────────────────────────────
            if !summary.by_action.is_empty() {
                println!();
                if use_color {
                    println!("{}", "By Action".bold().green());
                } else {
                    println!("By Action");
                }
                println!();
                println!(" {:<3}{:<20}{:>8}", "#", "Action", "Count");
                println!(" {}", "".repeat(32));
                for (i, a) in summary.by_action.iter().enumerate() {
                    println!(
                        " {:<3}{:<20}{:>8}",
                        format!("{}.", i + 1),
                        a.action,
                        a.count,
                    );
                }
            }

            // ── Daily sparkline (last 30 days) ───────────────────────
            let days = shift_preflight::stats::daily_breakdown(&records);
            if days.len() > 1 {
                println!();
                if use_color {
                    println!("{}", "Last 30 Days".bold().green());
                } else {
                    println!("Last 30 Days");
                }
                println!();
                print_sparkline(&days, use_color);
            }
        }
    }

    Ok(())
}

/// Print an RTK-style efficiency meter bar.
fn print_efficiency_meter(pct: f64, use_color: bool) {
    use colored::Colorize;
    let width = 24usize;
    let filled = ((pct / 100.0) * width as f64).round() as usize;
    let filled = filled.min(width);
    let meter = format!("{}{}", "".repeat(filled), "".repeat(width - filled));
    let pct_str = format!("{:.1}%", pct);
    if use_color {
        println!(
            "{:<18}{} {}",
            "Efficiency meter:",
            meter.green(),
            colorize_pct(&pct_str, pct, use_color),
        );
    } else {
        println!("{:<18}{} {}", "Efficiency meter:", meter, pct_str,);
    }
}

/// Print an ASCII sparkline graph of daily token savings (last 30 days).
fn print_sparkline(days: &[shift_preflight::stats::DailyGain], use_color: bool) {
    use colored::Colorize;

    // Take last 30 days
    let days: Vec<_> = if days.len() > 30 {
        days[days.len() - 30..].to_vec()
    } else {
        days.to_vec()
    };

    // Use combined tokens saved (best of openai/anthropic per day)
    let values: Vec<(String, u64)> = days
        .iter()
        .map(|d| {
            let saved = d.openai_saved.max(d.anthropic_saved);
            // Shorten date: "2026-04-23" -> "04-23"
            let short = if d.date.len() >= 10 {
                d.date[5..10].to_string()
            } else {
                d.date.clone()
            };
            (short, saved)
        })
        .collect();

    let max_val = values.iter().map(|(_, v)| *v).max().unwrap_or(1).max(1);
    let bar_width = 36usize;

    for (date, value) in &values {
        let filled = ((*value as f64 / max_val as f64) * bar_width as f64).round() as usize;
        let filled = filled.min(bar_width);
        let bar = "".repeat(filled);
        let tokens = fmt_short_tokens(*value);
        if use_color {
            println!(
                " {} │{:<width$} {}",
                date,
                bar.cyan(),
                tokens,
                width = bar_width
            );
        } else {
            println!(" {} │{:<width$} {}", date, bar, tokens, width = bar_width);
        }
    }
}

/// Format tokens in compact form: 1.2K, 3.5M, etc.
fn fmt_short_tokens(n: u64) -> String {
    if n >= 1_000_000 {
        format!("{:.1}M", n as f64 / 1_000_000.0)
    } else if n >= 1_000 {
        format!("{:.1}K", n as f64 / 1_000.0)
    } else {
        format!("{}", n)
    }
}

/// Color a percentage string by tier: green >= 50%, yellow >= 20%, red < 20%.
fn colorize_pct(s: &str, pct: f64, use_color: bool) -> String {
    use colored::Colorize;
    if !use_color {
        return s.to_string();
    }
    if pct >= 50.0 {
        s.green().bold().to_string()
    } else if pct >= 20.0 {
        s.yellow().bold().to_string()
    } else {
        s.red().bold().to_string()
    }
}

/// Build a mini impact bar (RTK-style).
fn mini_bar(value: u64, max: u64, width: usize, use_color: bool) -> String {
    use colored::Colorize;
    if max == 0 {
        return "".repeat(width);
    }
    let filled = ((value as f64 / max as f64) * width as f64).round() as usize;
    let filled = filled.min(width);
    let bar = format!("{}{}", "".repeat(filled), "".repeat(width - filled));
    if use_color {
        bar.cyan().to_string()
    } else {
        bar
    }
}

/// Format milliseconds as human-readable duration.
fn fmt_duration(ms: u64) -> String {
    if ms == 0 {
        return "0ms".to_string();
    }
    if ms < 1_000 {
        format!("{}ms", ms)
    } else if ms < 60_000 {
        format!("{:.1}s", ms as f64 / 1_000.0)
    } else {
        let mins = ms / 60_000;
        let secs = (ms % 60_000) / 1_000;
        format!("{}m{:02}s", mins, secs)
    }
}

fn fmt_bytes(n: u64) -> String {
    if n < 1_024 {
        format!("{} B", n)
    } else if n < 1_048_576 {
        format!("{:.1} KB", n as f64 / 1_024.0)
    } else {
        format!("{:.1} MB", n as f64 / 1_048_576.0)
    }
}

fn read_input(file: &Option<String>) -> Result<String> {
    match file {
        Some(path) => {
            std::fs::read_to_string(path).with_context(|| format!("failed to read {}", path))
        }
        None => {
            // Fix #18: Use std::io::IsTerminal instead of unmaintained `atty`
            if std::io::stdin().is_terminal() {
                anyhow::bail!(
                    "no input provided. Usage:\n  shift-ai <file.json>\n  cat request.json | shift-ai\n  shift-ai gain       (show cumulative savings)"
                );
            }
            // Fix #19: Limit stdin read size
            let mut buf = String::new();
            std::io::stdin()
                .take(MAX_STDIN_BYTES)
                .read_to_string(&mut buf)
                .context("failed to read stdin")?;
            Ok(buf)
        }
    }
}