paddington 0.6.0

A fast status line and cost tracker for Claude Code and Pi
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
use chrono::{Datelike, TimeZone};
use clap::{Parser, Subcommand};
use serde::Deserialize;
use std::io::Read;
use std::process::Command;

mod config;
mod db;
mod setup;

use config::{BLUE, GRAY, GREEN, RED, RESET, YELLOW};

#[derive(Parser)]
#[command(name = "paddington", about = "Status line renderer for Claude Code")]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Show monthly cost analytics
    Stats {
        /// Month to display (YYYY-MM format, default: current)
        #[arg(long, conflicts_with = "all")]
        month: Option<String>,
        /// Compare against another month (YYYY-MM format)
        #[arg(long, conflicts_with = "all")]
        compare: Option<String>,
        /// Show all-time stats across all months
        #[arg(long)]
        all: bool,
    },
    /// Validate config and preview template with mock data
    Check,
    /// Browse session history
    History {
        /// Max sessions to show (default: 20)
        #[arg(long, short = 'n', default_value = "20")]
        limit: u32,
        /// Filter by project name
        #[arg(long, short)]
        project: Option<String>,
    },
    /// Configure Claude Code and Pi to use paddington
    Setup {
        /// Configure Claude Code only
        #[arg(long)]
        claude: bool,
        /// Configure Pi only
        #[arg(long)]
        pi: bool,
        /// Install into a specific Pi profile (e.g. "agent-prodsec")
        #[arg(long, requires = "pi")]
        profile: Option<String>,
        /// Overwrite existing configuration without prompting
        #[arg(long)]
        force: bool,
        /// Remove paddington configuration from agents
        #[arg(long)]
        uninstall: bool,
    },
}

#[derive(Deserialize, Default)]
pub struct Input {
    pub session_id: Option<String>,
    pub model: Option<Model>,
    pub cwd: Option<String>,
    pub workspace: Option<Workspace>,
    pub worktree: Option<Worktree>,
    pub pr: Option<PullRequest>,
    pub session_name: Option<String>,
    pub context_window: Option<ContextWindow>,
    pub cost: Option<Cost>,
    /// Pi-specific: provider name (e.g. "anthropic", "openai")
    pub provider: Option<String>,
    /// Pi-specific: reasoning/thinking level (e.g. "off", "high", "max")
    pub reasoning_level: Option<String>,
    /// Pi-specific: which coding agent is calling us
    pub agent: Option<String>,
    /// Pi-specific: cache token stats
    pub cache: Option<CacheStats>,
    /// Pi-specific: cumulative token counts (separate from context window)
    pub tokens: Option<TokenStats>,
    /// Pi-specific: git branch passed from the extension (avoids shelling out)
    #[serde(rename = "_git_branch")]
    pub git_branch_override: Option<String>,
    /// Pi-specific: aggregate subagent cost for this session
    pub subagent_cost_usd: Option<f64>,
    /// Pi-specific: individual subagent run details
    pub subagent_runs: Option<Vec<SubagentRun>>,
}

#[derive(Deserialize, Default)]
pub struct Model {
    pub id: Option<String>,
    pub display_name: Option<String>,
}

#[derive(Deserialize, Default)]
pub struct Workspace {
    pub project_dir: Option<String>,
    pub repo: Option<Repo>,
}

#[derive(Deserialize, Default)]
pub struct Repo {
    pub owner: Option<String>,
    pub name: Option<String>,
}

#[derive(Deserialize, Default)]
pub struct Worktree {
    pub name: Option<String>,
}

#[derive(Deserialize, Default)]
pub struct PullRequest {
    pub number: Option<serde_json::Value>,
    pub review_state: Option<String>,
}

#[derive(Deserialize, Default)]
pub struct ContextWindow {
    pub total_input_tokens: Option<u64>,
    pub total_output_tokens: Option<u64>,
    pub context_window_size: Option<u64>,
    pub used_percentage: Option<f64>,
}

#[derive(Deserialize, Default)]
pub struct Cost {
    pub total_cost_usd: Option<f64>,
    pub total_duration_ms: Option<u64>,
    pub total_lines_added: Option<u64>,
    pub total_lines_removed: Option<u64>,
}

#[derive(Deserialize, Default)]
pub struct CacheStats {
    pub read_tokens: Option<u64>,
    pub write_tokens: Option<u64>,
    pub hit_rate: Option<f64>,
}

#[derive(Deserialize, Default)]
pub struct TokenStats {
    pub input: Option<u64>,
    pub output: Option<u64>,
}

#[derive(Deserialize, Default)]
pub struct SubagentRun {
    pub run_id: Option<String>,
    pub agent: Option<String>,
    pub model: Option<String>,
    pub cost_usd: Option<f64>,
    pub input_tokens: Option<u64>,
    pub output_tokens: Option<u64>,
    pub duration_ms: Option<u64>,
}

fn git_branch(project_dir: &str) -> Option<String> {
    let try_symbolic = Command::new("git")
        .args(["--no-optional-locks", "symbolic-ref", "--short", "HEAD"])
        .current_dir(project_dir)
        .output()
        .ok()?;

    if try_symbolic.status.success() {
        return Some(
            String::from_utf8_lossy(&try_symbolic.stdout)
                .trim()
                .to_string(),
        );
    }

    let try_rev = Command::new("git")
        .args(["--no-optional-locks", "rev-parse", "--short", "HEAD"])
        .current_dir(project_dir)
        .output()
        .ok()?;

    if try_rev.status.success() {
        return Some(String::from_utf8_lossy(&try_rev.stdout).trim().to_string());
    }

    None
}

fn git_is_dirty(project_dir: &str) -> bool {
    Command::new("git")
        .args(["--no-optional-locks", "status", "--porcelain"])
        .current_dir(project_dir)
        .output()
        .ok()
        .map(|o| o.status.success() && !o.stdout.is_empty())
        .unwrap_or(false)
}

fn format_relative_time(delta: chrono::TimeDelta) -> String {
    let secs = delta.num_seconds();
    if secs < 60 {
        "just now".to_string()
    } else if secs < 3600 {
        format!("{}m ago", secs / 60)
    } else {
        format!("{}h ago", secs / 3600)
    }
}

pub fn format_duration(ms: u64) -> String {
    let total_secs = ms / 1000;
    let hrs = total_secs / 3600;
    let mins = (total_secs % 3600) / 60;
    let secs = total_secs % 60;

    if hrs > 0 {
        format!("{hrs}h {mins}m")
    } else if mins > 0 {
        format!("{mins}m {secs}s")
    } else {
        format!("{secs}s")
    }
}

fn main() {
    match Cli::try_parse() {
        Ok(cli) => match cli.command {
            None => render_status_line(),
            Some(Commands::Stats {
                month,
                compare,
                all,
            }) => {
                if all {
                    show_all_time_stats();
                } else {
                    show_stats(month, compare);
                }
            }
            Some(Commands::Check) => run_check(),
            Some(Commands::History { limit, project }) => show_history(limit, project),
            Some(Commands::Setup { claude, pi, profile, force, uninstall }) => {
                setup::run_setup(claude, pi, profile, force, uninstall);
            }
        },
        Err(e) if e.use_stderr() => {
            use clap::error::ErrorKind;
            match e.kind() {
                // Constraint errors mean clap recognized a subcommand but
                // the args are invalid — show the real error.
                ErrorKind::ArgumentConflict | ErrorKind::MissingRequiredArgument => {
                    e.exit()
                }
                // Everything else (e.g. UnknownArgument from piped JSON
                // passed as argv) — fall through to the stdin render path.
                _ => render_status_line(),
            }
        }
        Err(e) => e.exit(),
    }
}

fn render_status_line() {
    let mut raw = String::new();
    std::io::stdin().read_to_string(&mut raw).unwrap();

    let input: Input = serde_json::from_str(&raw).unwrap_or_default();

    let project_dir = input
        .workspace
        .as_ref()
        .and_then(|w| w.project_dir.as_deref())
        .unwrap_or("");

    // Compute monthly total (same DB logic as before)
    let monthly_total: Option<f64> = (|| -> Option<f64> {
        let session_id = input.session_id.as_deref()?;
        let cost_data = input.cost.as_ref()?;
        let conn = db::open_db().ok()?;
        let record = db::SessionRecord {
            session_id: session_id.to_string(),
            project_dir: input.workspace.as_ref().and_then(|w| w.project_dir.clone()),
            model_id: input.model.as_ref().and_then(|m| m.id.clone()),
            model_name: input.model.as_ref().and_then(|m| m.display_name.clone()),
            cost_usd: cost_data.total_cost_usd.unwrap_or(0.0),
            duration_ms: cost_data.total_duration_ms.unwrap_or(0),
            lines_added: cost_data.total_lines_added.unwrap_or(0),
            lines_removed: cost_data.total_lines_removed.unwrap_or(0),
            subagent_cost_usd: input.subagent_cost_usd.unwrap_or(0.0),
        };
        db::upsert_session(&conn, &record).ok()?;
        if let Some(ref runs) = input.subagent_runs {
            let run_records: Vec<db::SubagentRunRecord> = runs.iter().filter_map(|r| {
                Some(db::SubagentRunRecord {
                    session_id: session_id.to_string(),
                    run_id: r.run_id.clone()?,
                    agent_name: r.agent.clone(),
                    model_name: r.model.clone(),
                    cost_usd: r.cost_usd.unwrap_or(0.0),
                    input_tokens: r.input_tokens.unwrap_or(0),
                    output_tokens: r.output_tokens.unwrap_or(0),
                    duration_ms: r.duration_ms.unwrap_or(0),
                })
            }).collect();
            if !run_records.is_empty() {
                let _ = db::upsert_subagent_runs(&conn, &run_records);
            }
        }
        let now = chrono::Local::now();
        db::get_monthly_total(&conn, now.year(), now.month()).ok()
    })();

    // Compute git branch and dirty status
    // If the caller passed _git_branch (e.g. pi extension), use it and skip shelling out
    let has_git =
        !project_dir.is_empty() && std::path::Path::new(project_dir).join(".git").exists();
    let branch = if let Some(ref b) = input.git_branch_override {
        b.clone()
    } else if has_git {
        git_branch(project_dir).unwrap_or_default()
    } else {
        String::new()
    };
    let git_dirty = if input.git_branch_override.is_some() {
        false // pi extension doesn't provide dirty status, skip the shell call
    } else {
        has_git && git_is_dirty(project_dir)
    };

    // Load config
    let (cfg, config_err) = config::load_config();
    let template_str = cfg
        .format
        .as_ref()
        .and_then(|f| f.template.clone())
        .unwrap_or_else(|| config::DEFAULT_TEMPLATE.to_string());
    let budget_limit = config::resolve_budget_limit(&cfg);

    // Build context
    let ctx = config::build_context(&input, monthly_total, &branch, git_dirty, budget_limit, input.subagent_cost_usd);

    // Render
    let output = if let Some(err) = config_err {
        // Config error: show error on first line, render default for rest
        let error_line = config::render_error_line(&err);
        let default_output =
            config::render_template(config::DEFAULT_TEMPLATE, &ctx).unwrap_or_default();
        format!("{error_line}\n{default_output}")
    } else {
        match config::render_template(&template_str, &ctx) {
            Ok(rendered) => rendered,
            Err(err) => {
                let error_line = config::render_error_line(&err);
                let default_output =
                    config::render_template(config::DEFAULT_TEMPLATE, &ctx).unwrap_or_default();
                format!("{error_line}\n{default_output}")
            }
        }
    };

    print!("{output}");
}

fn run_check() {
    let path = config::config_path();
    let (cfg, config_err) = config::load_config();
    let template_str = cfg
        .format
        .as_ref()
        .and_then(|f| f.template.clone())
        .unwrap_or_else(|| config::DEFAULT_TEMPLATE.to_string());

    if std::path::Path::new(&path).exists() {
        println!("Config: {path}");
    } else {
        println!("Config: none found, using default template");
    }

    if let Some(err) = config_err {
        eprintln!("{RED}Error: {err}{RESET}");
        std::process::exit(1);
    }

    // Pre-compile template to check syntax before printing OK
    let env = minijinja::Environment::new();
    if let Err(err) = env.template_from_str(&template_str) {
        eprintln!("{RED}Template syntax error: {err}{RESET}");
        std::process::exit(1);
    }

    println!("{GREEN}Template syntax: OK{RESET}");

    // Test-render to catch template compilation errors
    let ctx = config::mock_context();
    match config::render_template(&template_str, &ctx) {
        Ok(rendered) => {
            println!("\n{GREEN}Preview:{RESET}\n");
            println!("{rendered}");
        }
        Err(err) => {
            eprintln!("{RED}Render error: {err}{RESET}");
            std::process::exit(1);
        }
    }
}

fn show_stats(month_arg: Option<String>, compare_arg: Option<String>) {
    let (year, month) = match month_arg.as_deref() {
        Some(s) => parse_month_arg(s),
        None => {
            let now = chrono::Local::now();
            (now.year(), now.month())
        }
    };

    let conn = match db::open_db_readonly() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Failed to open database: {e}");
            std::process::exit(1);
        }
    };

    let (total, subagent_cost, total_dur, total_added, total_removed) =
        match db::monthly_totals(&conn, year, month) {
            Ok(v) => v,
            Err(e) => {
                eprintln!("Database error: {e}");
                std::process::exit(1);
            }
        };
    let count = match db::monthly_session_count(&conn, year, month) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Database error: {e}");
            std::process::exit(1);
        }
    };

    // Budget summary
    let budget_limit = {
        let (cfg, _) = config::load_config();
        config::resolve_budget_limit(&cfg)
    };
    if let Some(limit) = budget_limit {
        let pct = (total / limit * 100.0).round();
        let remaining = (limit - total).max(0.0);
        let color = config::budget_color(pct);
        println!(
            "{color}Budget: ${total:.2} / ${limit:.2} ({pct:.0}% used, ${remaining:.2} remaining){RESET}"
        );
    }

    if count == 0 {
        println!("No session data recorded yet.");
        // Still run comparison if requested
        if let Some(ref cmp) = compare_arg {
            let (cy, cm) = parse_month_arg(cmp);
            show_comparison(&conn, year, month, cy, cm);
        }
        return;
    }

    let month_full = month_name_full(month);
    let month_short = month_name_short(month);
    let dur_str = format_duration(total_dur);
    let cost_str = if subagent_cost > 0.0 {
        let parent_cost = total - subagent_cost;
        format!("${total:.2} (${parent_cost:.2} + ${subagent_cost:.2} subagents)")
    } else {
        format!("${total:.2}")
    };
    println!(
        "{YELLOW}Monthly Cost: {cost_str}{RESET}  ({month_full} {year}, {count} session{}, {dur_str})",
        if count == 1 { "" } else { "s" }
    );
    if total_added > 0 || total_removed > 0 {
        println!(
            "  {GREEN}+{total_added}{RESET}{GRAY}/{RESET}{RED}-{total_removed}{RESET} {GRAY}lines{RESET}"
        );
    }
    println!();

    // By Day
    if let Ok(days) = db::daily_breakdown(&conn, year, month) {
        let max_cost = days.iter().map(|(_, c, _)| *c).fold(0.0_f64, f64::max);
        println!("{GREEN}By Day:{RESET}");
        for (day, cost, sessions) in &days {
            let bar = render_bar(*cost, max_cost, 10);
            println!(
                "  {month_short} {day:<2}   {YELLOW}${cost:.2}{RESET}  {bar}  {GRAY}({sessions} session{}){RESET}",
                if *sessions == 1 { "" } else { "s" }
            );
        }
        println!();
    }

    // By Model
    if let Ok(models) = db::model_breakdown(&conn, year, month) {
        println!("{GREEN}By Model:{RESET}");
        let name_width = models.iter().map(|(n, ..)| n.len()).max().unwrap_or(0);
        for (name, cost, dur) in &models {
            let pct = if total > 0.0 {
                cost / total * 100.0
            } else {
                0.0
            };
            let dur_str = format_duration(*dur);
            println!(
                "  {name:<name_width$}  {YELLOW}${cost:.2}{RESET}  {GRAY}({pct:.0}%) {dur_str}{RESET}"
            );
        }
        println!();
    }

    // By Project
    if let Ok(projects) = db::project_breakdown(&conn, year, month) {
        println!("{GREEN}By Project:{RESET}");
        let name_width = projects.iter().map(|(n, ..)| n.len()).max().unwrap_or(0);
        for (name, cost, dur, added, removed) in &projects {
            let pct = if total > 0.0 {
                cost / total * 100.0
            } else {
                0.0
            };
            let dur_str = format_duration(*dur);
            let lines = if *added > 0 || *removed > 0 {
                format!(" {GREEN}+{added}{RESET}{GRAY}/{RESET}{RED}-{removed}{RESET}")
            } else {
                String::new()
            };
            println!(
                "  {name:<name_width$}  {YELLOW}${cost:.2}{RESET}  {GRAY}({pct:.0}%) {dur_str}{RESET}{lines}"
            );
        }
        println!();
    }

    // By Subagent
    if let Ok(subagents) = db::subagent_breakdown(&conn, year, month)
        && !subagents.is_empty()
    {
        println!("{GREEN}By Subagent:{RESET}");
        let max_cost = subagents.iter().map(|(_, c, ..)| *c).fold(0.0_f64, f64::max);
        let name_width = subagents.iter().map(|(n, ..)| n.len()).max().unwrap_or(0);
        for (name, cost, runs, model, _tokens) in &subagents {
            let bar = render_bar(*cost, max_cost, 10);
            let run_label = if *runs == 1 { "run" } else { "runs" };
            println!(
                "  {name:<name_width$}  {YELLOW}${cost:.2}{RESET}  {bar}  {GRAY}({runs} {run_label}, {model}){RESET}"
            );
        }
        println!();
    }

    // Active Sessions (updated in the last 15 minutes)
    if let Ok(active) = db::active_sessions(&conn, 15)
        && !active.is_empty()
    {
        println!("{GREEN}Active Sessions:{RESET}");
        let now = chrono::Utc::now();
        let proj_width = active.iter().map(|s| s.project.len()).max().unwrap_or(0);
        for s in &active {
            let dur = format_duration(s.duration_ms);
            let ago = chrono::DateTime::parse_from_rfc3339(&s.updated_at)
                .ok()
                .map(|t| format_relative_time(now - t.to_utc()))
                .unwrap_or_default();
            println!(
                "  {:<proj_width$}  {YELLOW}${:.2}{RESET}  {GRAY}{dur} · {} · {ago}{RESET}",
                s.project, s.cost_usd, s.model
            );
        }
    }

    // All-time
    if let Ok((all_cost, all_count, all_dur)) = db::all_time_totals(&conn)
        && all_count > count
    {
        let dur_str = format_duration(all_dur);
        println!("\n{GRAY}All-time: ${all_cost:.2} across {all_count} sessions ({dur_str}){RESET}");
    }

    // Comparison (if requested)
    if let Some(ref cmp) = compare_arg {
        let (cy, cm) = parse_month_arg(cmp);
        show_comparison(&conn, year, month, cy, cm);
    }
}

fn show_all_time_stats() {
    let conn = match db::open_db_readonly() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Failed to open database: {e}");
            std::process::exit(1);
        }
    };

    let (total, subagent_cost, count, total_dur, total_added, total_removed) =
        match db::all_time_totals_full(&conn) {
            Ok(v) => v,
            Err(e) => {
                eprintln!("Database error: {e}");
                std::process::exit(1);
            }
        };

    if count == 0 {
        println!("No session data recorded yet.");
        return;
    }

    let dur_str = format_duration(total_dur);
    let cost_str = if subagent_cost > 0.0 {
        let parent_cost = total - subagent_cost;
        format!("${total:.2} (${parent_cost:.2} + ${subagent_cost:.2} subagents)")
    } else {
        format!("${total:.2}")
    };
    println!(
        "{YELLOW}All-Time Cost: {cost_str}{RESET}  ({count} session{}, {dur_str})",
        if count == 1 { "" } else { "s" }
    );
    if total_added > 0 || total_removed > 0 {
        println!(
            "  {GREEN}+{total_added}{RESET}{GRAY}/{RESET}{RED}-{total_removed}{RESET} {GRAY}lines{RESET}"
        );
    }
    println!();

    // By Month
    if let Ok(months) = db::monthly_breakdown(&conn) {
        let max_cost = months.iter().map(|(.., c, _, _)| *c).fold(0.0_f64, f64::max);
        println!("{GREEN}By Month:{RESET}");
        for (year, month, cost, sessions, dur) in &months {
            let bar = render_bar(*cost, max_cost, 10);
            let mon = month_name_short(*month);
            let dur_str = format_duration(*dur);
            let pct = if total > 0.0 {
                cost / total * 100.0
            } else {
                0.0
            };
            println!(
                "  {mon} {year}  {YELLOW}${cost:.2}{RESET}  {bar}  {GRAY}({sessions} session{}, {dur_str}, {pct:.0}%){RESET}",
                if *sessions == 1 { "" } else { "s" }
            );
        }
        println!();
    }

    // By Model
    if let Ok(models) = db::all_time_model_breakdown(&conn) {
        println!("{GREEN}By Model:{RESET}");
        let name_width = models.iter().map(|(n, ..)| n.len()).max().unwrap_or(0);
        for (name, cost, dur) in &models {
            let pct = if total > 0.0 {
                cost / total * 100.0
            } else {
                0.0
            };
            let dur_str = format_duration(*dur);
            println!(
                "  {name:<name_width$}  {YELLOW}${cost:.2}{RESET}  {GRAY}({pct:.0}%) {dur_str}{RESET}"
            );
        }
        println!();
    }

    // By Project
    if let Ok(projects) = db::all_time_project_breakdown(&conn) {
        println!("{GREEN}By Project:{RESET}");
        let name_width = projects.iter().map(|(n, ..)| n.len()).max().unwrap_or(0);
        for (name, cost, dur, added, removed) in &projects {
            let pct = if total > 0.0 {
                cost / total * 100.0
            } else {
                0.0
            };
            let dur_str = format_duration(*dur);
            let lines = if *added > 0 || *removed > 0 {
                format!(" {GREEN}+{added}{RESET}{GRAY}/{RESET}{RED}-{removed}{RESET}")
            } else {
                String::new()
            };
            println!(
                "  {name:<name_width$}  {YELLOW}${cost:.2}{RESET}  {GRAY}({pct:.0}%) {dur_str}{RESET}{lines}"
            );
        }
        println!();
    }

    // By Subagent
    if let Ok(subagents) = db::all_time_subagent_breakdown(&conn)
        && !subagents.is_empty()
    {
        println!("{GREEN}By Subagent:{RESET}");
        let max_cost = subagents.iter().map(|(_, c, ..)| *c).fold(0.0_f64, f64::max);
        let name_width = subagents.iter().map(|(n, ..)| n.len()).max().unwrap_or(0);
        for (name, cost, runs, model, _tokens) in &subagents {
            let bar = render_bar(*cost, max_cost, 10);
            let run_label = if *runs == 1 { "run" } else { "runs" };
            println!(
                "  {name:<name_width$}  {YELLOW}${cost:.2}{RESET}  {bar}  {GRAY}({runs} {run_label}, {model}){RESET}"
            );
        }
        println!();
    }

    // Active Sessions
    if let Ok(active) = db::active_sessions(&conn, 15)
        && !active.is_empty()
    {
        println!("{GREEN}Active Sessions:{RESET}");
        let now = chrono::Utc::now();
        let proj_width = active.iter().map(|s| s.project.len()).max().unwrap_or(0);
        for s in &active {
            let dur = format_duration(s.duration_ms);
            let ago = chrono::DateTime::parse_from_rfc3339(&s.updated_at)
                .ok()
                .map(|t| format_relative_time(now - t.to_utc()))
                .unwrap_or_default();
            println!(
                "  {:<proj_width$}  {YELLOW}${:.2}{RESET}  {GRAY}{dur} · {} · {ago}{RESET}",
                s.project, s.cost_usd, s.model
            );
        }
    }
}

fn show_comparison(
    conn: &rusqlite::Connection,
    sel_year: i32,
    sel_month: u32,
    cmp_year: i32,
    cmp_month: u32,
) {
    let (cmp_cost, _, cmp_dur, _, _) = match db::monthly_totals(conn, cmp_year, cmp_month) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Database error: {e}");
            return;
        }
    };
    let cmp_count = match db::monthly_session_count(conn, cmp_year, cmp_month) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Database error: {e}");
            return;
        }
    };

    let cmp_month_name = month_name_full(cmp_month);

    if cmp_count == 0 {
        println!("\nNo data for {cmp_month_name} {cmp_year}.");
        return;
    }

    let (sel_cost, _, sel_dur, _, _) =
        db::monthly_totals(conn, sel_year, sel_month).unwrap_or((0.0, 0.0, 0, 0, 0));
    let sel_count = db::monthly_session_count(conn, sel_year, sel_month).unwrap_or_default();

    // Cost delta
    let cost_delta = sel_cost - cmp_cost;
    let cost_sign = if cost_delta >= 0.0 { "+" } else { "-" };
    let cost_pct_str = if cmp_cost > 0.0 {
        let pct = (cost_delta.abs() / cmp_cost * 100.0).round() as i64;
        format!(", {cost_sign}{pct}%")
    } else {
        String::new()
    };

    // Session delta
    let session_delta = sel_count as i64 - cmp_count as i64;
    let session_sign = if session_delta >= 0 { "+" } else { "" };

    // Duration delta
    let cmp_dur_str = format_duration(cmp_dur);
    let sel_dur_str = format_duration(sel_dur);
    let dur_pct_str = if cmp_dur > 0 {
        let pct = ((sel_dur as f64 - cmp_dur as f64) / cmp_dur as f64 * 100.0).round() as i64;
        let dur_sign = if pct >= 0 { "+" } else { "" };
        format!("  ({dur_sign}{pct}%)")
    } else {
        String::new()
    };

    println!("\n{GREEN}vs {cmp_month_name} {cmp_year}:{RESET}");
    println!(
        "  Cost:     {YELLOW}${cmp_cost:.2}{RESET} -> {YELLOW}${sel_cost:.2}{RESET}  ({cost_sign}${}{cost_pct_str})",
        cost_delta.abs()
    );
    println!("  Sessions: {cmp_count} -> {sel_count}  ({session_sign}{session_delta})");
    println!("  Duration: {GRAY}{cmp_dur_str}{RESET} -> {GRAY}{sel_dur_str}{RESET}{dur_pct_str}");
}

fn show_history(limit: u32, project_filter: Option<String>) {
    let conn = match db::open_db_readonly() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Failed to open database: {e}");
            std::process::exit(1);
        }
    };

    let sessions = match db::list_sessions(&conn, limit, project_filter.as_deref()) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Database error: {e}");
            std::process::exit(1);
        }
    };

    if sessions.is_empty() {
        println!("No sessions found.");
        return;
    }

    let proj_width = sessions.iter().map(|s| s.project.len()).max().unwrap_or(0);
    let model_width = sessions.iter().map(|s| s.model.len()).max().unwrap_or(0);

    for s in &sessions {
        let date = chrono::DateTime::parse_from_rfc3339(&s.started_at)
            .map(|dt| {
                chrono::Local
                    .from_utc_datetime(&dt.naive_utc())
                    .format("%Y-%m-%d")
                    .to_string()
            })
            .unwrap_or_else(|_| s.started_at[..10].to_string());
        let dur = format_duration(s.duration_ms);
        let lines = if s.lines_added > 0 || s.lines_removed > 0 {
            format!(
                " {GREEN}+{}{RESET}{GRAY}/{RESET}{RED}-{}{RESET}",
                s.lines_added, s.lines_removed
            )
        } else {
            String::new()
        };
        println!(
            "  {GRAY}{date}{RESET}  {BLUE}{:<proj_width$}{RESET}  {:<model_width$}  {YELLOW}${:.2}{RESET}  {GRAY}{dur}{RESET}{lines}",
            s.project, s.model, s.cost_usd
        );
    }
}

fn parse_month_arg(s: &str) -> (i32, u32) {
    let parts: Vec<&str> = s.split('-').collect();
    if parts.len() == 2
        && let (Ok(y), Ok(m)) = (parts[0].parse::<i32>(), parts[1].parse::<u32>())
        && (1..=12).contains(&m)
    {
        return (y, m);
    }
    eprintln!("Invalid month format '{s}', expected YYYY-MM");
    std::process::exit(1);
}

fn month_name_short(month: u32) -> &'static str {
    match month {
        1 => "Jan",
        2 => "Feb",
        3 => "Mar",
        4 => "Apr",
        5 => "May",
        6 => "Jun",
        7 => "Jul",
        8 => "Aug",
        9 => "Sep",
        10 => "Oct",
        11 => "Nov",
        12 => "Dec",
        _ => "???",
    }
}

fn month_name_full(month: u32) -> &'static str {
    match month {
        1 => "January",
        2 => "February",
        3 => "March",
        4 => "April",
        5 => "May",
        6 => "June",
        7 => "July",
        8 => "August",
        9 => "September",
        10 => "October",
        11 => "November",
        12 => "December",
        _ => "???",
    }
}

fn render_bar(value: f64, max: f64, width: usize) -> String {
    let filled = if max > 0.0 {
        (value / max * width as f64).round() as usize
    } else {
        0
    };
    let empty = width.saturating_sub(filled);
    format!(
        "{GREEN}{}{GRAY}{}{RESET}",
        "".repeat(filled),
        "".repeat(empty)
    )
}

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

    #[test]
    fn test_format_duration() {
        assert_eq!(format_duration(0), "0s");
        assert_eq!(format_duration(5_000), "5s");
        assert_eq!(format_duration(65_000), "1m 5s");
        assert_eq!(format_duration(3_661_000), "1h 1m");
    }

    #[test]
    fn test_show_comparison_no_data_message() {
        // show_comparison with empty DB should print "No data for..."
        // We can't easily capture stdout in unit tests, but we can verify
        // the DB queries return zero for a month with no data
        let conn = db::open_db_in_memory().unwrap();
        let count = db::monthly_session_count(&conn, 2026, 1).unwrap();
        assert_eq!(count, 0);
    }

    #[test]
    fn test_comparison_delta_math() {
        // Cost delta: 85.50 - 142.00 = -56.50
        let cmp_cost = 142.0_f64;
        let sel_cost = 85.5_f64;
        let delta = sel_cost - cmp_cost;
        assert!((delta - (-56.5)).abs() < f64::EPSILON);
        let pct = (delta / cmp_cost * 100.0).round() as i64;
        assert_eq!(pct, -40);
    }

    #[test]
    fn test_comparison_zero_cost_no_percentage() {
        let cmp_cost = 0.0_f64;
        // When cmp_cost is 0, percentage should be omitted
        assert!(!(cmp_cost > 0.0));
    }
}