aboutsummaryrefslogtreecommitdiff
path: root/internal/cli/cli.go
blob: ef00010ad170a6d9856d558e0e0fe1b8ea738ac4 (plain) (blame)
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
// Package cli is lectio's flag-driven command dispatcher: it wires config,
// the readings router, liturgy.Harvest and render together into the
// `lectio` binary's Run entry point.
package cli

import (
	"flag"
	"fmt"
	"io"
	"os"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/lukaszkasprzak/lectio/internal/bible"
	"github.com/lukaszkasprzak/lectio/internal/config"
	"github.com/lukaszkasprzak/lectio/internal/i18n"
	"github.com/lukaszkasprzak/lectio/internal/liturgy"
	"github.com/lukaszkasprzak/lectio/internal/readings"
	"github.com/lukaszkasprzak/lectio/internal/render"
	"github.com/lukaszkasprzak/lectio/internal/tradlit"
)

const helpText = `lectio — daily Catholic liturgy readings (Polish + 4 versions)

Usage:
  lectio [DATE] [flags]     DATE = YYYY-MM-DD (default: today), any position

Flags:
  -a, --all              all readings, not just the gospel
  -b, --bible VER        one version's text: bt,wuj,vul,grb,drb
  -c, --compare LIST     versions side by side (comma-separated)
  -p, --ref REF          look up a passage (e.g. "J 3:16") with -b/-c
  -r, --raw              text only, no banner/headings (for piping)
  -w, --width N          wrap width; 0 = detect terminal
  -R, --refresh          ignore cache, re-download
  -o, --offline          cache/sigla only, no network
  -l, --lectionary WHICH new|trad (trad -> traditional)
  -g, --lang LANG        traditional lectionary language: pl|en
  -u, --update           harvest sigla maximally to the horizon (idempotent)
  -C, --clean            prune cached readings older than a year
  -P, --pager            page reading output (like git); default from config
      --no-pager         never page, even if config sets one
      --list             list all books + abbreviations (dialect from sigla_style)
      --citation         print the day's gospel reference (scripts/cron) and exit
      --week             list the coming week's gospel references and exit
  -v, --version          print the version and exit
  -h, --help             this help

Versions: bt (Biblia Tysiąclecia) wuj (Wujek) vul (Wulgata) grb (Grecki)
          drb (Douay-Rheims)

Examples:
  lectio                        today's gospel
  lectio 2026-07-22 -a          all readings for a date
  lectio -c bt,wuj 2026-07-22   compare two versions for a date
  lectio -b vul -a              Vulgate text, all readings
  lectio -l trad -a             traditional lectionary, all readings
  lectio -u                     harvest sigla to the horizon
  lectio -p "Jn 3:16" -b vul    look up a passage (English sigla)
  lectio -p "J 3,16" -c wuj,drb    Polish sigla when sigla_style=polish/auto+pl UI
  lectio --list                 list every book + abbreviations
  lectio --citation             today's gospel reference
  lectio --week 2026-07-22      a week of gospel references from a date

Flags override config. Exit codes: 0 ok, 1 runtime error (fetch/parse),
2 usage error (bad flag, bad date, bad version, bad --lectionary/--lang).
`

const (
	defaultWidth        = 80
	compareDefaultWidth = 120
)

var dateRe = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)

func today() string {
	return time.Now().Format("2006-01-02")
}

// Run is the CLI entry point; returns a process exit code.
func Run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
	if wantsHelp(args) {
		fmt.Fprint(stdout, helpText)
		return 0
	}
	if wantsVersion(args) {
		fmt.Fprintln(stdout, "lectio "+config.Version)
		return 0
	}
	if len(args) > 0 && args[0] == "help" {
		fmt.Fprint(stdout, helpText)
		return 0
	}

	date, rest, err := extractDate(args)
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 2
	}

	var all, raw, refresh, offline, update, clean, pagerFlag, noPager, citation, week bool
	var bibleVer, compareList, lectionary, lang string
	var width int
	var list bool
	var ref string

	fs := flag.NewFlagSet("lectio", flag.ContinueOnError)
	fs.SetOutput(stderr)
	fs.Usage = func() { fmt.Fprint(stderr, helpText) }

	fs.BoolVar(&all, "a", false, "all readings, not just the gospel")
	fs.BoolVar(&all, "all", false, "all readings, not just the gospel")
	fs.StringVar(&bibleVer, "b", "", "one version's text: bt,wuj,vul,grb,drb")
	fs.StringVar(&bibleVer, "bible", "", "one version's text: bt,wuj,vul,grb,drb")
	fs.StringVar(&compareList, "c", "", "versions side by side (comma list)")
	fs.StringVar(&compareList, "compare", "", "versions side by side (comma list)")
	fs.BoolVar(&raw, "r", false, "text only, no banner/headings")
	fs.BoolVar(&raw, "raw", false, "text only, no banner/headings")
	fs.IntVar(&width, "w", 0, "wrap width (0 = detect terminal)")
	fs.IntVar(&width, "width", 0, "wrap width (0 = detect terminal)")
	fs.BoolVar(&refresh, "R", false, "ignore cache, re-download")
	fs.BoolVar(&refresh, "refresh", false, "ignore cache, re-download")
	fs.BoolVar(&offline, "o", false, "cache/sigla only, no network")
	fs.BoolVar(&offline, "offline", false, "cache/sigla only, no network")
	fs.StringVar(&lectionary, "l", "", "new|trad")
	fs.StringVar(&lectionary, "lectionary", "", "new|trad")
	fs.StringVar(&lang, "g", "", "pl|en")
	fs.StringVar(&lang, "lang", "", "pl|en")
	fs.BoolVar(&update, "u", false, "harvest sigla maximally to the horizon")
	fs.BoolVar(&update, "update", false, "harvest sigla maximally to the horizon")
	fs.BoolVar(&clean, "C", false, "prune cached readings older than a year")
	fs.BoolVar(&clean, "clean", false, "prune cached readings older than a year")
	fs.BoolVar(&pagerFlag, "P", false, "page reading output (like git)")
	fs.BoolVar(&pagerFlag, "pager", false, "page reading output (like git)")
	fs.BoolVar(&noPager, "no-pager", false, "never page, even if config sets one")
	fs.StringVar(&ref, "p", "", "look up a passage, e.g. \"J 3:16\" (with -b/-c)")
	fs.StringVar(&ref, "ref", "", "look up a passage, e.g. \"J 3:16\" (with -b/-c)")
	fs.BoolVar(&list, "list", false, "list all books + abbreviations (in your sigla_style)")
	fs.BoolVar(&citation, "citation", false, "print the day's gospel reference and exit")
	fs.BoolVar(&week, "week", false, "list the coming week's gospel references and exit")

	if err := fs.Parse(rest); err != nil {
		return 2
	}
	if fs.NArg() > 0 {
		fmt.Fprintf(stderr, "lectio: unexpected argument %q; see 'lectio -h'\n", fs.Arg(0))
		return 2
	}

	lectionary, err = normalizeLectionary(lectionary)
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 2
	}
	if lang != "" && lang != "pl" && lang != "en" {
		fmt.Fprintf(stderr, "lectio: invalid --lang %q (want pl|en)\n", lang)
		return 2
	}

	if clean {
		return runClean(stdout, stderr)
	}
	if update {
		return runHarvest(date, stdout, stderr)
	}

	cfg, err := config.Load()
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 1
	}
	if offline {
		cfg.Offline = true
	}
	if lectionary != "" {
		cfg.Lectionary = lectionary
	}
	if lang != "" {
		cfg.TraditionalLang = lang
	}

	if citation || week {
		tbl, _ := bible.LoadBookTable(userBooksTOML())
		if citation {
			return runCitation(cfg, tbl, date, refresh, stdout, stderr)
		}
		return runWeek(cfg, tbl, date, refresh, stdout, stderr)
	}

	effAll := all || cfg.All
	effWidth := width
	if effWidth == 0 {
		effWidth = cfg.Width
	}
	if effWidth == 0 {
		// Detect the real terminal width now, from stdout, before it may be
		// replaced by the pager's pipe below -- otherwise paging would wrap at
		// the default width instead of the terminal's.
		if tw := termWidth(stdout); tw > 0 {
			effWidth = tw
		}
	}

	// Validate versions before any pager starts -- don't page an error.
	var refVersions []string
	if ref != "" {
		rv, verr := refLookupVersions(cfg, bibleVer, compareList)
		if verr != nil {
			fmt.Fprintln(stderr, "lectio:", verr)
			return 2
		}
		refVersions = rv
	} else {
		// Day-reading paths: bt is a valid version here (compareList wins over
		// bibleVer, as before, so bibleVer is left unvalidated when a list is given).
		if bibleVer != "" && compareList == "" && !config.ValidVersion(bibleVer) {
			fmt.Fprintf(stderr, "lectio: unknown version %q (want one of bt, wuj, vul, grb, drb)\n", bibleVer)
			return 2
		}
		if compareList != "" {
			for _, v := range strings.Split(compareList, ",") {
				if v = strings.TrimSpace(v); v != "" && !config.ValidVersion(v) {
					fmt.Fprintf(stderr, "lectio: unknown version %q (want one of bt, wuj, vul, grb, drb)\n", v)
					return 2
				}
			}
		}
	}

	var bookTbl *bible.BookTable
	if list || ref != "" {
		tbl, terr := bible.LoadBookTable(userBooksTOML())
		if terr != nil {
			fmt.Fprintln(stderr, "lectio:", terr) // warn; tbl is still a usable defaults table
		}
		bookTbl = tbl
	}

	out := stdout
	finish := func() {}
	if pagerRequested(pagerFlag, noPager, cfg) && isTerminalWriter(stdout) {
		if o, f, ok := startPager(pagerCommand(cfg), stdout, stderr); ok {
			out = o
			finish = f
		}
	}

	var code int
	switch {
	case list:
		code = runList(bookTbl, cfg.SiglaLang(), out)
	case ref != "":
		code = lookupRef(cfg, bookTbl, ref, refVersions, raw, effWidth, out, stderr)
	case compareList != "":
		code = renderCompare(cfg, compareList, date, effAll, raw, effWidth, refresh, out, stderr)
	case bibleVer != "":
		code = fetchAndPrint(cfg, bibleVer, date, effAll, raw, effWidth, refresh, out, stderr)
	default:
		code = fetchAndPrint(cfg, cfg.DefaultVersion, date, effAll, raw, effWidth, refresh, out, stderr)
	}
	finish()
	return code
}

// gospelSection returns the gospel section from a (gospel-only, All=false)
// load: the section tagged "ewangelia" (modern) or "evangelium" (traditional),
// else the first section present. ok is false only when secs is empty.
func gospelSection(secs []liturgy.Section) (liturgy.Section, bool) {
	for _, s := range secs {
		if s.PartID == "ewangelia" || s.PartID == "evangelium" {
			return s, true
		}
	}
	if len(secs) > 0 {
		return secs[0], true
	}
	return liturgy.Section{}, false
}

// gospelCitation returns a section's scripture reference: its Citation field if
// set, else the reference parsed out of its Heading (e.g. "Ewangelia (Mt 7,
// 1-5)" -> "Mt 7, 1-5"), else "" (source-form, never translated).
func gospelCitation(sec liturgy.Section) string {
	if sec.Citation != "" {
		return sec.Citation
	}
	if c, err := liturgy.ExtractCitation(sec.Heading); err == nil {
		return c
	}
	return ""
}

// dialectCitation renders a gospel section's reference in the configured sigla
// dialect (cfg.SiglaLang(): sigla_style, or -- "auto" -- ui_language). The
// source citation's language is the lectionary's: Polish for the modern
// (niedziela) lectionary, cfg.TraditionalLang for the traditional one. The ref
// is parsed to canonical and re-rendered in the target dialect; a citation
// whose book can't be parsed comes back in its source form unchanged.
func dialectCitation(cfg config.Config, tbl *bible.BookTable, sec liturgy.Section) string {
	raw := gospelCitation(sec)
	if raw == "" || tbl == nil {
		return raw
	}
	sourceLang := "pl"
	if cfg.Lectionary == "traditional" {
		sourceLang = cfg.TraditionalLang
	}
	canonical, ok := tbl.ParseRef(sourceLang, raw)
	if !ok {
		return raw
	}
	return tbl.FormatRef(cfg.SiglaLang(), canonical)
}

// runCitation handles --citation: fetch the day's gospel (gospel-only) and
// print just its scripture reference in the configured sigla dialect (see
// dialectCitation), for scripts/cron/prompt use. Honors the resolved cfg
// (lectionary/lang/offline) and date. Exit 1 if the day has no gospel
// reference (unpublished date, no network while offline, ...).
func runCitation(cfg config.Config, tbl *bible.BookTable, date string, refresh bool, stdout, stderr io.Writer) int {
	secs, _, err := readings.Load(cfg, readings.Options{Date: date, Refresh: refresh, Offline: cfg.Offline, All: false})
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 1
	}
	sec, ok := gospelSection(secs)
	if !ok {
		fmt.Fprintln(stderr, "lectio: no gospel for", date)
		return 1
	}
	cit := dialectCitation(cfg, tbl, sec)
	if cit == "" {
		fmt.Fprintln(stderr, "lectio: no gospel reference for", date)
		return 1
	}
	fmt.Fprintln(stdout, cit)
	return 0
}

// runWeek handles --week: print the gospel reference for each of the seven days
// starting at date, one "YYYY-MM-DD  <reference>" line per day. A day that
// can't be loaded (unpublished, offline gap, no gospel) shows "—" rather than
// aborting the run, so the list is always seven lines. Honors cfg
// (lectionary/lang/offline).
func runWeek(cfg config.Config, tbl *bible.BookTable, date string, refresh bool, stdout, stderr io.Writer) int {
	start, err := time.Parse("2006-01-02", date)
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 2
	}
	for i := 0; i < 7; i++ {
		d := start.AddDate(0, 0, i).Format("2006-01-02")
		cit := "—"
		secs, _, err := readings.Load(cfg, readings.Options{Date: d, Refresh: refresh, Offline: cfg.Offline, All: false})
		if err == nil {
			if sec, ok := gospelSection(secs); ok {
				if c := dialectCitation(cfg, tbl, sec); c != "" {
					cit = c
				}
			}
		}
		fmt.Fprintf(stdout, "%s  %s\n", d, cit)
	}
	return 0
}

// userBooksTOML returns the bytes of the optional user books.toml, or nil if
// it is absent/unreadable (built-in defaults are used).
func userBooksTOML() []byte {
	p, err := config.BooksPath()
	if err != nil {
		return nil
	}
	b, err := os.ReadFile(p)
	if err != nil {
		return nil
	}
	return b
}

// wantsHelp reports whether -h/--help appears anywhere in args.
func wantsHelp(args []string) bool {
	for _, a := range args {
		if a == "-h" || a == "--help" {
			return true
		}
	}
	return false
}

// wantsVersion reports whether -v/--version appears anywhere in args (like
// wantsHelp), so `lectio DATE -v` prints the version rather than erroring on
// an "undefined flag".
func wantsVersion(args []string) bool {
	for _, a := range args {
		if a == "-v" || a == "--version" {
			return true
		}
	}
	return false
}

// extractDate pulls the single positional DATE token (YYYY-MM-DD, matching
// dateRe) out of args, wherever it appears, and returns it along with the
// remaining tokens for flag.FlagSet to parse. No flag's own value can match
// dateRe's shape (width is an int, versions/lists/lang/lectionary are short
// codes), so scanning raw tokens this way is unambiguous. Defaults to
// today() when no date token is present; errors if more than one is found.
func extractDate(args []string) (date string, rest []string, err error) {
	found := false
	for _, a := range args {
		if dateRe.MatchString(a) {
			if found {
				return "", nil, fmt.Errorf("multiple dates given (%q and %q)", date, a)
			}
			date = a
			found = true
			continue
		}
		rest = append(rest, a)
	}
	if !found {
		date = today()
	}
	return date, rest, nil
}

// normalizeLectionary maps -l/--lectionary's accepted spellings ("new",
// "trad", "traditional") onto the canonical config.Config.Lectionary values
// ("new", "traditional") via config.NormalizeLectionary; "" (flag not given)
// passes through unchanged so the caller knows to leave config's own
// setting alone.
func normalizeLectionary(lectionary string) (string, error) {
	if lectionary == "" {
		return "", nil
	}
	v, ok := config.NormalizeLectionary(lectionary)
	if !ok {
		return "", fmt.Errorf("invalid --lectionary %q (want new|trad)", lectionary)
	}
	return v, nil
}

// runHarvest handles -u/--update: harvest sigla maximally (to the
// unpublished horizon) from date for the modern lectionary, printing the
// outcome or -- on a genuine interruption (see liturgy.Harvest) -- the
// error. On a successful harvest it also best-effort pre-caches the
// traditional lectionary's propers (internal/tradlit) for every date in
// that same [date, furthest] window, so 'lectio update' prepares both
// lectionaries for offline use in one run. The 1962 calendar has no
// "unpublished horizon" (every date has propers), so this is a plain
// date-range fetch; a per-date failure is not fatal here -- it never
// prevented the traditional lectionary from working live before, and the
// modern-harvest outcome is still reported either way.
func runHarvest(date string, stdout, stderr io.Writer) int {
	added, furthest, err := liturgy.Harvest(date, 0)
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 1
	}

	lang := config.Default().TraditionalLang
	cachedTrad := 0
	if furthest != "" {
		if cfg, cfgErr := config.Load(); cfgErr == nil {
			lang = cfg.TraditionalLang
			cachedTrad = cacheTraditionalRange(date, furthest, lang)
		}
	}

	fmt.Fprintf(stdout, "harvested %d day(s), furthest %s; cached traditional propers (%s) for %d day(s)\n",
		added, furthest, lang, cachedTrad)
	return 0
}

// cacheTraditionalRange best-effort pre-caches tradlit's traditional propers
// for lang for every date in [from, to] inclusive (walking forward a day at
// a time), returning how many dates succeeded. A per-date failure (e.g. a
// transient network hiccup) is ignored -- the traditional 1962 calendar has
// propers for every date, so there is no "unpublished horizon" to stop at
// the way liturgy.Harvest has for the modern lectionary.
func cacheTraditionalRange(from, to, lang string) int {
	start, err := time.Parse("2006-01-02", from)
	if err != nil {
		return 0
	}
	end, err := time.Parse("2006-01-02", to)
	if err != nil {
		return 0
	}

	cached := 0
	for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
		if _, _, err := tradlit.Load(d.Format("2006-01-02"), lang, false); err == nil {
			cached++
		}
	}
	return cached
}

// runClean handles -C/--clean: prune cached readings older than one year
// (relative to today()) and print a human-readable summary of what was
// removed. Like -u/--update, this is a maintenance mode -- it ignores DATE
// and every render flag, and is dispatched before the render paths. If both
// --clean and -u/--update are given, --clean takes precedence (see Run).
func runClean(stdout, stderr io.Writer) int {
	now, err := time.Parse("2006-01-02", today())
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 1
	}
	before := now.AddDate(-1, 0, 0)

	removed, freed, err := liturgy.CleanCache(before)
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 1
	}

	cutoff := before.Format("2006-01-02")
	if removed == 0 {
		fmt.Fprintf(stdout, "cache already clean (nothing older than %s)\n", cutoff)
		return 0
	}
	entries := "entries"
	if removed == 1 {
		entries = "entry"
	}
	fmt.Fprintf(stdout, "cleaned %d cache %s older than %s (freed %s)\n", removed, entries, cutoff, formatFreed(freed))
	return 0
}

// formatFreed renders a byte count the way -C/--clean's summary line wants
// it: megabytes with one decimal once it's a meaningful size, kilobytes
// (also one decimal) for anything smaller.
func formatFreed(bytes int64) string {
	const mb = 1024 * 1024
	if bytes >= mb {
		return fmt.Sprintf("%.1f MB", float64(bytes)/mb)
	}
	return fmt.Sprintf("%.1f KB", float64(bytes)/1024)
}

// fetchAndPrint is the shared single-version render path (default version or
// -b/--bible): fetch via the readings router, apply the offline version
// swap, then render each section's heading and render.GatherVersion blocks.
func fetchAndPrint(cfg config.Config, version, date string, all, raw bool, width int, refresh bool, stdout, stderr io.Writer) int {
	secs, dayInfo, err := readings.Load(cfg, readings.Options{
		Date:    date,
		Refresh: refresh,
		Offline: cfg.Offline,
		All:     all,
	})
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 1
	}
	if len(secs) == 0 {
		fmt.Fprintln(stderr, "lectio: no readings found for", date)
		return 1
	}

	if vs := render.EffectiveVersions([]string{version}, cfg.Lectionary, cfg.Offline); len(vs) > 0 {
		version = vs[0]
	}

	w := resolveWidth(width, false, stdout)

	if !raw {
		printDayInfo(stdout, dayInfo)
		banner := bannerFor(cfg.UILanguage, all, date)
		fmt.Fprintln(stdout, banner)
		fmt.Fprintln(stdout, strings.Repeat("=", minInt(len(banner), w)))
		fmt.Fprintln(stdout)
	}

	pieces := make([]string, 0, len(secs))
	for _, sec := range secs {
		pieces = append(pieces, renderSection(sec, version, cfg.Lectionary, cfg.UILanguage, w, raw))
	}
	fmt.Fprintln(stdout, strings.Join(pieces, "\n\n"))
	return 0
}

// printDayInfo prints the day's celebration name -- and, if the source
// carries one, its temporal Season on its own line -- above the banner.
// Name/Season are never translated (source-language, like the readings/
// citations themselves; see liturgy.DayInfo). A source that yielded no
// DayInfo (info.Name == "") prints nothing: the header is a nice-to-have,
// never an error condition. Callers only reach this when !raw; --raw skips
// it entirely, keeping piped output text-only.
//
// The CLI has no ANSI styling of its own (unlike the TUI's Faint/dim
// styles), so "dim" here is expressed structurally: the Season, if any,
// gets its own line under Name rather than sharing emphasis with it.
func printDayInfo(stdout io.Writer, info liturgy.DayInfo) {
	if info.Name == "" {
		return
	}
	name := info.Name
	if info.Colour != "" {
		name += " · " + info.Colour
	}
	fmt.Fprintln(stdout, name)
	if info.Season != "" {
		fmt.Fprintln(stdout, info.Season)
	}
}

// bannerFor builds the "<Gospel|Readings> <connective> DATE" banner: the
// "readings" word when every part is shown, "gospel" for the gospel-only
// default, and the connective between word and date, all localised via
// i18n.Get(lang) -- lang="pl" reproduces ewangelia.py's original Polish
// wording exactly ("Ewangelia na DATE" / "Czytania na DATE"); lang="en"
// gives "Gospel for DATE" / "Readings for DATE".
func bannerFor(lang string, all bool, date string) string {
	ui := i18n.Get(lang)
	word := ui.BannerGospel
	if all {
		word = ui.BannerReadings
	}
	return word + " " + ui.BannerConnective + " " + date
}

// renderSection formats one section as its heading (unless raw) followed by
// render.GatherVersion's blocks, each wrapped to width. The heading's part
// label is localised via render.LocalizeHeading (lang); the citation/verse
// text is never touched.
func renderSection(sec liturgy.Section, version, lectionary, lang string, width int, raw bool) string {
	var lines []string
	if !raw {
		lines = append(lines, render.HeadingWithRef(sec, lang))
		lines = append(lines, "")
	}
	_, blocks := render.GatherVersion(version, sec, lectionary, lang)
	for _, b := range blocks {
		lines = append(lines, wrapText(b, width))
	}
	return strings.TrimRight(strings.Join(lines, "\n"), "\n")
}

// renderCompare handles -c/--compare LIST: LIST is a comma-separated list of
// version codes (falling back to cfg.Versions when empty), rendered side by
// side via render.Compare.
func renderCompare(cfg config.Config, list, date string, all, raw bool, width int, refresh bool, stdout, stderr io.Writer) int {
	var versions []string
	if list == "" {
		versions = append(versions, cfg.Versions...)
	} else {
		for _, v := range strings.Split(list, ",") {
			v = strings.TrimSpace(v)
			if v == "" {
				continue
			}
			versions = append(versions, v)
		}
	}
	for _, v := range versions {
		if !config.ValidVersion(v) {
			fmt.Fprintf(stderr, "lectio: unknown version %q (want one of bt, wuj, vul, grb, drb)\n", v)
			return 2
		}
	}
	versions = render.EffectiveVersions(versions, cfg.Lectionary, cfg.Offline)

	secs, dayInfo, err := readings.Load(cfg, readings.Options{
		Date:    date,
		Refresh: refresh,
		Offline: cfg.Offline,
		All:     all,
	})
	if err != nil {
		fmt.Fprintln(stderr, "lectio:", err)
		return 1
	}
	if len(secs) == 0 {
		fmt.Fprintln(stderr, "lectio: no readings found for", date)
		return 1
	}

	w := resolveWidth(width, true, stdout)

	if !raw {
		printDayInfo(stdout, dayInfo)
		banner := bannerFor(cfg.UILanguage, all, date)
		fmt.Fprintln(stdout, banner)
		fmt.Fprintln(stdout, strings.Repeat("=", minInt(len(banner), w)))
		fmt.Fprintln(stdout)
	}
	fmt.Fprintln(stdout, render.Compare(secs, versions, w, cfg.Lectionary, cfg.UILanguage))
	return 0
}

// isCorpusVersion reports whether v is a scripture-text version with an
// embedded corpus (wuj/vul/grb/drb) -- i.e. a valid version that is not "bt"
// (the niedziela.pl scrape, which has no full text to look a passage up in).
func isCorpusVersion(v string) bool {
	return config.ValidVersion(v) && v != "bt"
}

// refLookupVersions resolves which corpus version(s) `--ref` should look a
// passage up in, rejecting "bt" (no corpus). Precedence: an explicit -c LIST,
// then a single -b VER, then a sensible default (the configured default_version
// if it has a corpus, else the first corpus version in cfg.Versions). It errors
// (exit 2 in the caller) on any non-corpus version or if nothing usable is
// configured.
func refLookupVersions(cfg config.Config, bibleVer, compareList string) ([]string, error) {
	if compareList != "" {
		var versions []string
		for _, v := range strings.Split(compareList, ",") {
			if v = strings.TrimSpace(v); v == "" {
				continue
			}
			if !isCorpusVersion(v) {
				return nil, fmt.Errorf("--ref cannot use version %q; pass a corpus version (wuj, vul, grb, drb)", v)
			}
			versions = append(versions, v)
		}
		if len(versions) == 0 {
			return nil, fmt.Errorf("--ref needs at least one corpus version in -c")
		}
		return versions, nil
	}
	if bibleVer != "" {
		if !isCorpusVersion(bibleVer) {
			return nil, fmt.Errorf("--ref cannot use version %q; pass a corpus version (wuj, vul, grb, drb)", bibleVer)
		}
		return []string{bibleVer}, nil
	}
	if isCorpusVersion(cfg.DefaultVersion) {
		return []string{cfg.DefaultVersion}, nil
	}
	for _, v := range cfg.Versions {
		if isCorpusVersion(v) {
			return []string{v}, nil
		}
	}
	return nil, fmt.Errorf("--ref needs a corpus version; pass -b wuj|vul|grb|drb")
}

// lookupRef renders a passage lookup (-p/--ref). It parses the typed reference
// in the resolved sigla dialect (bookTbl.ParseRef -- dialect-scoped book names
// and number syntax) into an English colon-style reference, then reuses the
// same render path as the readings with lectionary="traditional" (the ref is
// already in target form, looked up literally per version -- no niedziela
// conversion, no cross-version psalm renumbering). versions is the validated
// corpus set (never "bt"). raw omits the header. Exit 2 on an unparseable ref,
// exit 1 if no requested version has the passage.
func lookupRef(cfg config.Config, tbl *bible.BookTable, ref string, versions []string, raw bool, width int, stdout, stderr io.Writer) int {
	ref = strings.TrimSpace(ref)
	engRef, ok := tbl.ParseRef(cfg.SiglaLang(), ref)
	if !ok {
		fmt.Fprintf(stderr, "lectio: could not read reference %q in the %s dialect; see 'lectio --list'\n", ref, cfg.SiglaLang())
		return 2
	}
	sec := liturgy.Section{Citation: engRef, Heading: engRef}

	found := false
	for _, v := range versions {
		if vs, _ := bible.Lookup(v, engRef); len(vs) > 0 {
			found = true
			break
		}
	}
	if !found {
		fmt.Fprintf(stderr, "lectio: no text found for %q in %s\n", ref, strings.Join(versions, ", "))
		return 1
	}

	w := width
	if w <= 0 {
		if len(versions) > 1 {
			w = compareDefaultWidth
		} else {
			w = defaultWidth
		}
	}

	if !raw {
		fmt.Fprintln(stdout, ref)
		fmt.Fprintln(stdout, strings.Repeat("=", minInt(len([]rune(ref)), w)))
		fmt.Fprintln(stdout)
	}

	if len(versions) == 1 {
		label, blocks := render.GatherVersion(versions[0], sec, "traditional", cfg.UILanguage)
		if !raw {
			fmt.Fprintln(stdout, label)
			fmt.Fprintln(stdout)
		}
		lines := make([]string, 0, len(blocks))
		for _, b := range blocks {
			lines = append(lines, render.Wrap(b, w))
		}
		fmt.Fprintln(stdout, strings.Join(lines, "\n"))
		return 0
	}

	fmt.Fprintln(stdout, render.Compare([]liturgy.Section{sec}, versions, w, "traditional", cfg.UILanguage))
	return 0
}

// runList handles --list: print every book of the sigla dialect (scriptural
// order) as "<shortcut>  <name>". The shortcut column is padded by rune count
// so diacritics ("Łk") still line up.
func runList(tbl *bible.BookTable, dialect string, stdout io.Writer) int {
	const col = 8
	for _, b := range tbl.Books(dialect) {
		pad := col - len([]rune(b.Shortcut))
		if pad < 1 {
			pad = 1
		}
		fmt.Fprintf(stdout, "%s%s%s\n", b.Shortcut, strings.Repeat(" ", pad), b.Name)
	}
	return 0
}

// resolveWidth applies the --width 0 = detect-terminal rule: an explicit
// positive width wins, then a real terminal width if stdout is a tty, then
// a sane per-mode default.
func resolveWidth(flagWidth int, isCompare bool, out io.Writer) int {
	if flagWidth > 0 {
		return flagWidth
	}
	if tw := termWidth(out); tw > 0 {
		return tw
	}
	if isCompare {
		return compareDefaultWidth
	}
	return defaultWidth
}

// termWidth checks $COLUMNS first (a common shell/CLI convention), then
// falls back to a TIOCGWINSZ ioctl when out is a real terminal file. It
// returns 0 (meaning: use the caller's default) when neither works.
func termWidth(out io.Writer) int {
	if v := os.Getenv("COLUMNS"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 {
			return n
		}
	}
	f, ok := out.(*os.File)
	if !ok {
		return 0
	}
	return ttyWidth(f)
}

// wrapText greedily wraps line to width without breaking words, matching
// ewangelia.py's textwrap.fill(..., break_long_words=False,
// break_on_hyphens=False). Duplicated (in miniature) from render.wrap,
// which is unexported: cli needs the same wrapping for single-version
// output, render.Compare does its own internally.
func wrapText(line string, width int) string {
	words := strings.Fields(line)
	if len(words) == 0 {
		return ""
	}
	var out []string
	cur := words[0]
	for _, word := range words[1:] {
		if len([]rune(cur))+1+len([]rune(word)) <= width {
			cur += " " + word
		} else {
			out = append(out, cur)
			cur = word
		}
	}
	out = append(out, cur)
	return strings.Join(out, "\n")
}

func minInt(a, b int) int {
	if a < b {
		return a
	}
	return b
}