open-library-api-rs 0.1.0

Async Rust client for the Open Library API
Documentation
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
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
// v0.0.1
use std::collections::HashMap;
use std::process;

use clap::{Args, Parser, Subcommand};
use open_library_api_rs::{
    OpenLibraryClient, Result,
    models::{
        author::{Author, AuthorWorks},
        changes::{ChangesParams, RecentChange},
        common::{BooksJsCmd, ChangeKind, CoverKey, ImageSize, VolumeIdType},
        covers::CoverMeta,
        edition::Edition,
        list::{List, ListEditions, ListSeed, ListSeeds, ListSubjects, UserLists},
        partner::VolumesResponse,
        query::{HistoryEntry, QueryResponse},
        reading_log::ReadingLog,
        search::{
            AuthorDoc, AuthorSearchParams, BookDoc, InsideDoc, ListDoc, SearchParams,
            SearchResponse, SubjectDoc, SubjectParams,
        },
        subject::Subject,
        work::{Work, WorkBookshelves, WorkEditions, WorkRatings},
    },
};

// ── Top-level CLI ─────────────────────────────────────────────────────────────

#[derive(Parser)]
#[command(
    name    = "olib",
    version = env!("CARGO_PKG_VERSION"),
    about   = "Command-line client for the Open Library API",
    long_about = "\
olib — Open Library API command-line client

Covers every public read endpoint: works, editions, authors, search, subjects,
covers, user lists, reading logs, the partner/volumes API, recent changes, and
the generic query and history endpoints.

Results are printed to stdout in human-readable form. Use --json to emit raw
pretty-printed JSON (pipe to jq for further processing). Errors go to stderr;
exit code is 0 on success, 1 on failure.

RATE LIMITS
  Anonymous (default):  1 request / second
  Identified (--email): 3 requests / second
  Covers CDN:           100 requests / 5 minutes / IP

IDENTIFYING YOUR APPLICATION
  Supply --email and --rate-limit 3 together to use the 3 req/s tier:
    olib --email me@example.com --rate-limit 3 work get OL45804W

  The email is appended to the User-Agent header so Open Library can contact
  you if your application misbehaves. It is never sent in the request body.",
    after_help = "\
EXAMPLES
  olib work get OL45804W
  olib work editions OL45804W --limit 5
  olib edition isbn 9780140328724
  olib author get OL23919A
  olib search books --q \"rust programming\" --limit 5
  olib search books --author tolkien --language eng
  olib subject science_fiction --details --limit 10
  olib cover url id 5428012 large
  olib reading already-read alice
  olib changes --date 2024-06-15 --kind edit-book
  olib volume isbn 0451450523
  olib books ISBN:0451450523 OCLC:45883427

  # JSON output for scripting
  olib --json work get OL45804W | jq '{title, first_publish_date}'
  olib --json search books --q \"dune\" | jq '.docs[] | {key, title}'
  olib --json changes --kind add-book --limit 5 | jq '.[].key'",
)]
struct Cli {
    /// Emit raw pretty-printed JSON instead of human-readable text.
    /// Suitable for piping to jq or other JSON tools.
    #[arg(long, global = true)]
    json: bool,

    /// Maximum requests per second sent to the Open Library API.
    /// The default of 1 matches the anonymous rate limit. Set to 3 when
    /// also providing --email to use the identified-application tier.
    #[arg(long, global = true, default_value = "1", value_name = "N")]
    rate_limit: u32,

    /// Contact email address appended to the User-Agent header.
    /// Providing this identifies your application to Open Library and
    /// enables the 3 req/s tier. Combine with --rate-limit 3.
    #[arg(long, global = true, value_name = "EMAIL")]
    email: Option<String>,

    #[arg(long, global = true, hide = true, value_name = "URL")]
    base_url: Option<String>,

    #[arg(long, global = true, hide = true, value_name = "URL")]
    covers_url: Option<String>,

    #[command(subcommand)]
    command: Cmd,
}

// ── Subcommand tree ───────────────────────────────────────────────────────────

#[derive(Subcommand)]
enum Cmd {
    /// Fetch works, editions lists, ratings, and bookshelf counts
    Work(WorkArgs),
    /// Fetch editions by OLID or ISBN
    Edition(EditionArgs),
    /// Fetch author records and their attributed works
    Author(AuthorArgs),
    /// Search books, authors, subjects, lists, and book interiors
    Search(SearchArgs),
    /// Fetch the subject page for a topic slug (e.g. science_fiction)
    Subject(SubjectCliArgs),
    /// Generate cover/photo URLs or fetch cover metadata
    Cover(CoverArgs),
    /// Fetch user-created lists and their contents
    List(ListArgs),
    /// Fetch a user's public reading log shelves
    Reading(ReadingArgs),
    /// Browse the Open Library recent-changes feed
    Changes(ChangesCliArgs),
    /// Resolve book identifiers via the Partner / Volumes API
    Volume(VolumeArgs),
    /// Look up books by bibliographic key via /api/books
    Books(BooksCliArgs),
    /// Query any Open Library object type via /query.json
    Query(QueryCliArgs),
    /// Fetch the full revision history of an Open Library resource
    History(HistoryArgs),
}

// ── Work ──────────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Fetch works, editions lists, ratings, and bookshelf counts",
    long_about = "\
A 'work' is the canonical creative entity — the book as an idea, separate from
any particular printing. Each work has a unique Work OLID of the form OL<N>W
(e.g. OL45804W for 'Fantastic Mr. Fox').

Sub-commands:
  get          Core metadata: title, authors, subjects, description, covers
  editions     Paginated list of all known printings of the work
  ratings      Community star-rating average and per-star counts
  bookshelves  How many users have it on each reading shelf",
    after_help = "\
EXAMPLES
  olib work get OL45804W
  olib --json work get OL45804W | jq '{title, first_publish_date, subjects}'

  olib work editions OL45804W
  olib work editions OL45804W --limit 5 --offset 0

  olib work ratings OL45804W
  olib work bookshelves OL45804W",
)]
struct WorkArgs {
    #[command(subcommand)]
    cmd: WorkCmd,
}

#[derive(Subcommand)]
enum WorkCmd {
    /// Fetch a work's core metadata by its Work OLID (format: OL<N>W)
    #[command(
        after_help = "\
FIELDS RETURNED
  key, title, subtitle, description, authors, subjects, subject_places,
  subject_people, subject_times, covers (IDs), first_publish_date, latest_revision

EXAMPLES
  olib work get OL45804W
  olib --json work get OL45804W | jq '.subjects'
  olib --json work get OL45804W | jq '.authors[].author.key'",
    )]
    Get {
        /// Work OLID, e.g. OL45804W
        id: String,
    },

    /// Fetch the paginated list of editions for a work
    #[command(
        after_help = "\
EXAMPLES
  olib work editions OL45804W
  olib work editions OL45804W --limit 5
  olib work editions OL45804W --limit 20 --offset 20
  olib --json work editions OL45804W | jq '.entries[] | {key, title, publish_date}'",
    )]
    Editions {
        /// Work OLID, e.g. OL45804W
        id: String,
        /// Number of editions to return (1–1000)
        #[arg(long, default_value = "20", value_name = "N")]
        limit: u32,
        /// Number of editions to skip (for pagination)
        #[arg(long, default_value = "0", value_name = "N")]
        offset: u32,
    },

    /// Fetch community star ratings (average, count, per-star distribution)
    #[command(
        after_help = "\
EXAMPLES
  olib work ratings OL45804W
  olib --json work ratings OL45804W | jq '.summary'",
    )]
    Ratings {
        /// Work OLID, e.g. OL45804W
        id: String,
    },

    /// Fetch reading-shelf counts (want-to-read / currently-reading / already-read)
    #[command(
        after_help = "\
EXAMPLES
  olib work bookshelves OL45804W
  olib --json work bookshelves OL45804W | jq '.counts'",
    )]
    Bookshelves {
        /// Work OLID, e.g. OL45804W
        id: String,
    },
}

// ── Edition ───────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Fetch editions by OLID or ISBN",
    long_about = "\
An 'edition' is a specific physical or digital printing of a work. Edition OLIDs
have the form OL<N>M (e.g. OL7353617M). ISBNs can be 10 or 13 digits;
hyphens and spaces are stripped automatically.

Sub-commands:
  get    Fetch by Edition OLID
  isbn   Fetch by ISBN-10 or ISBN-13",
    after_help = "\
EXAMPLES
  olib edition get OL7353617M
  olib edition isbn 9780140328724
  olib edition isbn 0-14-032-872-6
  olib --json edition isbn 9780140328724 | jq '{title, publishers, publish_date}'",
)]
struct EditionArgs {
    #[command(subcommand)]
    cmd: EditionCmd,
}

#[derive(Subcommand)]
enum EditionCmd {
    /// Fetch an edition by its Edition OLID (format: OL<N>M)
    #[command(
        after_help = "\
FIELDS RETURNED
  key, title, subtitle, publishers, publish_date, number_of_pages, languages,
  isbn_13, isbn_10, lccn, oclc_numbers, covers, physical_format, weight

EXAMPLES
  olib edition get OL7353617M
  olib --json edition get OL7353617M | jq '{title, isbn_13, number_of_pages}'",
    )]
    Get {
        /// Edition OLID, e.g. OL7353617M
        id: String,
    },

    /// Fetch an edition by ISBN-10 or ISBN-13 (hyphens/spaces ignored)
    #[command(
        after_help = "\
ISBN VALIDATION
  ISBN-10: 10 digits (trailing X allowed); validated with Luhn mod-11 check
  ISBN-13: 13 digits starting with 978 or 979; validated with EAN-13 check
  Hyphens and spaces are stripped before validation.

EXAMPLES
  olib edition isbn 9780140328724
  olib edition isbn 0140328726
  olib edition isbn 978-0-14-032-872-4
  olib --json edition isbn 9780140328724 | jq '{title, publish_date}'",
    )]
    Isbn {
        /// ISBN-10 or ISBN-13 (hyphens/spaces are stripped automatically)
        isbn: String,
    },
}

// ── Author ────────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Fetch author records and their attributed works",
    long_about = "\
Author OLIDs have the form OL<N>A (e.g. OL23919A for J. K. Rowling).

Sub-commands:
  get    Core author record: name, dates, bio, photo IDs, Wikipedia link
  works  Paginated list of works attributed to this author",
    after_help = "\
EXAMPLES
  olib author get OL23919A
  olib author works OL23919A --limit 20
  olib --json author get OL23919A | jq '{name, birth_date, wikipedia}'",
)]
struct AuthorArgs {
    #[command(subcommand)]
    cmd: AuthorCmd,
}

#[derive(Subcommand)]
enum AuthorCmd {
    /// Fetch an author's core record by their Author OLID (format: OL<N>A)
    #[command(
        after_help = "\
FIELDS RETURNED
  key, name, personal_name, alternate_names, birth_date, death_date,
  bio, location, photos (IDs), wikipedia, links

EXAMPLES
  olib author get OL23919A
  olib --json author get OL23919A | jq '{name, birth_date, death_date}'
  olib --json author get OL23919A | jq '.photos[0]'  # first photo ID",
    )]
    Get {
        /// Author OLID, e.g. OL23919A
        id: String,
    },

    /// Fetch the works attributed to an author (paginated)
    #[command(
        after_help = "\
EXAMPLES
  olib author works OL23919A
  olib author works OL23919A --limit 50
  olib author works OL23919A --limit 20 --offset 40
  olib --json author works OL23919A | jq '.entries[] | {key, title}'",
    )]
    Works {
        /// Author OLID, e.g. OL23919A
        id: String,
        /// Number of works to return (1–1000)
        #[arg(long, default_value = "20", value_name = "N")]
        limit: u32,
        /// Number of works to skip (for pagination)
        #[arg(long, default_value = "0", value_name = "N")]
        offset: u32,
    },
}

// ── Search ────────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Search books, authors, subjects, lists, and book interiors",
    long_about = "\
Five distinct search endpoints are available:

  books    Full-text search across works and editions (/search.json)
  authors  Search author names (/search/authors.json)
  subjects Search subject names (/search/subjects.json)
  lists    Search user-created reading lists (/search/lists.json)
  inside   Full-text search inside scanned book content (/search/inside.json)

All return a result count (num_found) and a paginated list of documents.",
    after_help = "\
EXAMPLES
  olib search books --q \"lord of the rings\"
  olib search books --author tolkien --language eng --limit 5
  olib search books --title Foundation --author Asimov --sort new
  olib search books --q \"python\" --subject programming --limit 10
  olib search authors --q \"ursula le guin\"
  olib search subjects fantasy
  olib search lists \"classic sci-fi\" --limit 5
  olib search inside \"call me ishmael\" --limit 3
  olib --json search books --q dune | jq '.docs[] | {key, title}'",
)]
struct SearchArgs {
    #[command(subcommand)]
    cmd: SearchCmd,
}

#[derive(Subcommand)]
enum SearchCmd {
    /// Search books and works (/search.json)
    ///
    /// At least one filter flag must be provided. All filters are AND-ed together.
    /// Results include title, authors, first publication year, edition count, and more.
    #[command(
        after_help = "\
SORT VALUES
  relevance  (default) Solr relevance scoring
  new        Newest first (by first_publish_year)
  old        Oldest first

LANGUAGE CODES
  Use two-letter ISO 639-1 codes: eng, fre, ger, spa, ita, por, jpn, zho, ...

EXAMPLES
  olib search books --q \"lord of the rings\"
  olib search books --author tolkien --limit 5
  olib search books --title Dune --sort new
  olib search books --q python --subject programming --language eng
  olib search books --isbn 9780451450524
  olib search books --place France --person Napoleon
  olib --json search books --q tolkien | jq '.num_found'
  olib --json search books --q tolkien | jq '.docs[] | {key, title, author_name}'",
    )]
    Books {
        /// Free-text query (searches across all fields)
        #[arg(long, value_name = "QUERY")]
        q: Option<String>,
        /// Filter by title
        #[arg(long, value_name = "TITLE")]
        title: Option<String>,
        /// Filter by author name
        #[arg(long, value_name = "NAME")]
        author: Option<String>,
        /// Filter by ISBN
        #[arg(long, value_name = "ISBN")]
        isbn: Option<String>,
        /// Filter by subject tag
        #[arg(long, value_name = "SUBJECT")]
        subject: Option<String>,
        /// Filter by geographic place mentioned in the book
        #[arg(long, value_name = "PLACE")]
        place: Option<String>,
        /// Filter by person mentioned in the book
        #[arg(long, value_name = "PERSON")]
        person: Option<String>,
        /// Filter by language code (e.g. eng, fre, ger)
        #[arg(long, value_name = "CODE")]
        language: Option<String>,
        /// Number of results to return (1–1000)
        #[arg(long, default_value = "10", value_name = "N")]
        limit: u32,
        /// Number of results to skip (for pagination)
        #[arg(long, default_value = "0", value_name = "N")]
        offset: u32,
        /// Sort order: relevance | new | old
        #[arg(long, value_name = "ORDER")]
        sort: Option<String>,
    },

    /// Search author names (/search/authors.json)
    #[command(
        after_help = "\
EXAMPLES
  olib search authors --q tolkien
  olib search authors --q \"ursula le guin\" --limit 3
  olib --json search authors --q tolkien | jq '.docs[] | {key, name, work_count}'",
    )]
    Authors {
        /// Author name query (required)
        #[arg(long, value_name = "QUERY")]
        q: String,
        /// Number of results to return (1–1000)
        #[arg(long, default_value = "10", value_name = "N")]
        limit: u32,
        /// Number of results to skip (for pagination)
        #[arg(long, default_value = "0", value_name = "N")]
        offset: u32,
    },

    /// Search subject names (/search/subjects.json)
    #[command(
        after_help = "\
EXAMPLES
  olib search subjects fantasy
  olib search subjects \"artificial intelligence\"
  olib --json search subjects \"world war\" | jq '.docs[] | {name, work_count}'",
    )]
    Subjects {
        /// Subject name query
        query: String,
    },

    /// Search user-created reading lists (/search/lists.json)
    #[command(
        after_help = "\
EXAMPLES
  olib search lists tolkien
  olib search lists \"best sci-fi\" --limit 5
  olib --json search lists tolkien | jq '.docs[] | {name, key}'",
    )]
    Lists {
        /// List name query
        query: String,
        /// Number of results to return (1–1000)
        #[arg(long, default_value = "10", value_name = "N")]
        limit: u32,
    },

    /// Full-text search inside scanned book content (/search/inside.json)
    #[command(
        after_help = "\
This endpoint searches the text inside books digitized by the Internet Archive.
Results include a short excerpt from the matching passage.

EXAMPLES
  olib search inside \"call me ishmael\"
  olib search inside \"lembas bread\" --limit 3
  olib --json search inside \"recursion\" | jq '.docs[] | {title, author}'",
    )]
    Inside {
        /// Text to search for inside book content
        query: String,
        /// Number of results to return (1–1000)
        #[arg(long, default_value = "10", value_name = "N")]
        limit: u32,
    },
}

// ── Subject ───────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Fetch the subject page for a topic slug",
    long_about = "\
Fetches the subject page for a topic slug from /subjects/<slug>.json.

Slugs are lowercase ASCII with underscores (e.g. science_fiction, world_war_2).
The --details flag adds related subjects, top authors, and publisher breakdowns.

SLUG EXAMPLES
  love                  science_fiction       world_war_2
  python_(programming)  history               children_s_literature",
    after_help = "\
EXAMPLES
  olib subject love
  olib subject science_fiction --details
  olib subject cyberpunk --ebooks
  olib subject history --published-in 1900-1950 --limit 10
  olib subject mystery --limit 10 --offset 30
  olib --json subject fantasy --details | jq '.related_subjects[].name'
  olib --json subject fantasy | jq '.works[] | {key, title}'",
)]
struct SubjectCliArgs {
    /// Subject slug (lowercase with underscores), e.g. science_fiction
    slug: String,
    /// Include related subjects, top authors, and publisher statistics
    #[arg(long)]
    details: bool,
    /// Only return works that have freely readable e-book editions
    #[arg(long)]
    ebooks: bool,
    /// Restrict to works published within a year range, e.g. 1950-1999
    #[arg(long, value_name = "YYYY-YYYY")]
    published_in: Option<String>,
    /// Number of works to return (1–1000)
    #[arg(long, default_value = "20", value_name = "N")]
    limit: u32,
    /// Number of works to skip (for pagination)
    #[arg(long, default_value = "0", value_name = "N")]
    offset: u32,
}

// ── Cover ─────────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Generate cover/photo URLs or fetch cover image metadata",
    long_about = "\
Book cover images are served from covers.openlibrary.org. Author photos from
covers.openlibrary.org/a/olid/<OLID>-<SIZE>.jpg.

The 'url' and 'photo' sub-commands construct URLs without any network call.
The 'meta' sub-command fetches JSON metadata (width, height, URL) from the API.

KEY TYPES (for cover url and cover meta)
  id    Internal numeric cover ID (most stable)
  isbn  ISBN-10 or ISBN-13
  oclc  OCLC control number
  lccn  Library of Congress Control Number
  olid  Open Library edition OLID

SIZES
  small (s)   ~56px tall
  medium (m)  ~128px tall
  large (l)   ~400px tall",
    after_help = "\
EXAMPLES
  olib cover url id 5428012 large
  olib cover url isbn 9780451450524 medium
  olib cover url olid OL7353617M small
  olib cover meta id 5428012
  olib cover photo OL23919A large

  # Download a cover image
  curl -L \"$(olib cover url id 5428012 large)\" -o cover.jpg

  # Get an author's photo
  curl -L \"$(olib cover photo OL23919A medium)\" -o author.jpg",
)]
struct CoverArgs {
    #[command(subcommand)]
    cmd: CoverCmd,
}

#[derive(Subcommand)]
enum CoverCmd {
    /// Print a book cover image URL (no network call)
    ///
    /// Constructs the URL from a key type, key value, and image size.
    /// Key types: id | isbn | oclc | lccn | olid
    /// Sizes: small | medium | large (or s | m | l)
    #[command(
        after_help = "\
EXAMPLES
  olib cover url id 5428012 large
  olib cover url isbn 9780451450524 medium
  olib cover url oclc 45883427 small
  olib cover url lccn 2004046975 large
  olib cover url olid OL7353617M medium

  curl -L \"$(olib cover url id 5428012 large)\" -o cover.jpg",
    )]
    Url {
        /// Key type: id | isbn | oclc | lccn | olid
        key: String,
        /// Key value matching the key type
        value: String,
        /// Image size: small | medium | large (or s | m | l)
        size: String,
    },

    /// Fetch cover image metadata: dimensions, URL, size string
    #[command(
        after_help = "\
EXAMPLES
  olib cover meta id 5428012
  olib --json cover meta id 5428012 | jq '{width, height, url}'",
    )]
    Meta {
        /// Key type: id | isbn | oclc | lccn | olid
        key: String,
        /// Key value matching the key type
        value: String,
    },

    /// Print an author photo URL (no network call)
    ///
    /// Validates the Author OLID (format: OL<N>A), then constructs the URL.
    /// Sizes: small | medium | large (or s | m | l)
    #[command(
        after_help = "\
EXAMPLES
  olib cover photo OL23919A large
  olib cover photo OL23919A medium

  curl -L \"$(olib cover photo OL23919A large)\" -o author.jpg",
    )]
    Photo {
        /// Author OLID, e.g. OL23919A
        olid: String,
        /// Image size: small | medium | large (or s | m | l)
        size: String,
    },
}

// ── List ──────────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Fetch user-created lists and their contents",
    long_about = "\
Open Library users can create public reading lists containing works, editions,
authors, and subject references ('seeds').

All list endpoints are read-only in v0.1.

Sub-commands:
  user      Index of all public lists for a user
  show      Metadata for a single list (name, description, seed/edition counts)
  editions  Editions contained in the list (paginated)
  subjects  Subject tags derived from the list's works
  seeds     Raw list items (work keys, edition keys, subject URLs)",
    after_help = "\
EXAMPLES
  olib list user alice
  olib list user alice --limit 10 --offset 10
  olib list show alice OL123L
  olib list editions alice OL123L --limit 20
  olib list subjects alice OL123L
  olib list seeds alice OL123L
  olib --json list show alice OL123L | jq '{name, seed_count}'",
)]
struct ListArgs {
    #[command(subcommand)]
    cmd: ListCmd,
}

#[derive(Subcommand)]
enum ListCmd {
    /// List all public lists belonging to a user
    #[command(
        after_help = "\
EXAMPLES
  olib list user alice
  olib list user alice --limit 10
  olib list user alice --limit 10 --offset 10
  olib --json list user alice | jq '.lists[] | {key, name, seed_count}'",
    )]
    User {
        /// Open Library username
        username: String,
        /// Number of lists to return (1–1000)
        #[arg(long, default_value = "20", value_name = "N")]
        limit: u32,
        /// Number of lists to skip (for pagination)
        #[arg(long, default_value = "0", value_name = "N")]
        offset: u32,
    },

    /// Fetch metadata for a specific list (name, description, counts)
    #[command(
        after_help = "\
EXAMPLES
  olib list show alice OL123L
  olib --json list show alice OL123L | jq '{name, seed_count, edition_count}'",
    )]
    Show {
        /// Open Library username
        username: String,
        /// List ID (the OL…L part from the list's key)
        list_id: String,
    },

    /// Fetch editions contained in a list (paginated)
    #[command(
        after_help = "\
EXAMPLES
  olib list editions alice OL123L
  olib list editions alice OL123L --limit 5
  olib --json list editions alice OL123L | jq '.entries[] | {key, title}'",
    )]
    Editions {
        /// Open Library username
        username: String,
        /// List ID (the OL…L part from the list's key)
        list_id: String,
        /// Number of editions to return (1–1000)
        #[arg(long, default_value = "20", value_name = "N")]
        limit: u32,
        /// Number of editions to skip (for pagination)
        #[arg(long, default_value = "0", value_name = "N")]
        offset: u32,
    },

    /// Fetch subject tags derived from the works in a list
    ///
    /// Returns subjects, places, people, and time periods covered by the list.
    #[command(
        after_help = "\
EXAMPLES
  olib list subjects alice OL123L
  olib --json list subjects alice OL123L | jq '.subjects[] | {name, count}'",
    )]
    Subjects {
        /// Open Library username
        username: String,
        /// List ID (the OL…L part from the list's key)
        list_id: String,
    },

    /// Fetch the raw seeds (items) in a list
    ///
    /// Seeds can be work keys (/works/OL…W), edition keys (/books/OL…M),
    /// or subject references {url, title}.
    #[command(
        after_help = "\
EXAMPLES
  olib list seeds alice OL123L
  olib --json list seeds alice OL123L | jq '.entries'",
    )]
    Seeds {
        /// Open Library username
        username: String,
        /// List ID (the OL…L part from the list's key)
        list_id: String,
    },
}

// ── Reading log ───────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Fetch a user's public reading log shelves",
    long_about = "\
Open Library users maintain three public reading shelves:
  want-to-read       Books the user intends to read
  currently-reading  Books the user is actively reading
  already-read       Books the user has finished

Each entry includes the work key, title, author names, and the date logged.",
    after_help = "\
EXAMPLES
  olib reading want-to-read alice
  olib reading currently-reading alice
  olib reading already-read alice
  olib --json reading already-read alice | jq '.reading_log_entries[] | .work.title'
  olib --json reading want-to-read alice | jq '[.reading_log_entries[] | .work.key]'",
)]
struct ReadingArgs {
    #[command(subcommand)]
    cmd: ReadingCmd,
}

#[derive(Subcommand)]
enum ReadingCmd {
    /// Books on the user's 'want to read' shelf
    #[command(after_help = "EXAMPLE\n  olib reading want-to-read alice")]
    WantToRead {
        /// Open Library username
        username: String,
    },

    /// Books the user is currently reading
    #[command(after_help = "EXAMPLE\n  olib reading currently-reading alice")]
    CurrentlyReading {
        /// Open Library username
        username: String,
    },

    /// Books the user has already read
    #[command(
        after_help = "\
EXAMPLES
  olib reading already-read alice
  olib --json reading already-read alice | jq '.reading_log_entries[] | .work.title'",
    )]
    AlreadyRead {
        /// Open Library username
        username: String,
    },
}

// ── Changes ───────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Browse the Open Library recent-changes feed",
    long_about = "\
Fetches edits from /recentchanges.json (or sub-paths filtered by date / kind).
Without any filters, returns the most recent changes across all types.

All three filters (--date, --kind, --bot) can be combined freely.

KIND VALUES
  add-cover      A new cover image was added
  add-book       A new edition or work was created
  edit-book      An existing edition or work was updated
  merge-authors  Two author records were merged
  update         A generic update
  revert         A previous edit was reverted
  new-account    A new user account was created
  register       A registration event
  lists          A list was created or modified",
    after_help = "\
EXAMPLES
  olib changes
  olib changes --limit 50
  olib changes --date 2024-06-15
  olib changes --kind edit-book --limit 100
  olib changes --date 2024-06-15 --kind add-cover
  olib changes --bot false --limit 50
  olib --json changes --kind edit-book --limit 5 | jq '.[].key'
  olib --json changes --date 2024-01-01 | jq '.[].comment'",
)]
struct ChangesCliArgs {
    /// Restrict to changes on this date (format: YYYY-MM-DD)
    #[arg(long, value_name = "YYYY-MM-DD")]
    date: Option<String>,
    /// Restrict to one change type (see KIND VALUES above)
    #[arg(
        long,
        value_name = "KIND",
        long_help = "Filter by change kind. Values: add-cover | add-book | edit-book | \
                     merge-authors | update | revert | new-account | register | lists"
    )]
    kind: Option<String>,
    /// Number of changes to return (1–1000)
    #[arg(long, default_value = "20", value_name = "N")]
    limit: u32,
    /// Number of changes to skip (for pagination)
    #[arg(long, default_value = "0", value_name = "N")]
    offset: u32,
    /// Include (true) or exclude (false) bot-generated edits
    #[arg(long, value_name = "BOOL")]
    bot: Option<bool>,
}

// ── Volume ────────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Resolve book identifiers via the Partner / Volumes API",
    long_about = "\
The Partner API maps standard book identifiers to borrowing / reading availability
information from the Internet Archive's Open Library.

Response includes:
  records   Bibliographic data keyed by Open Library path
  items     Available copies with status (borrowable/readable/limited/unavailable)

Sub-commands:
  isbn   Look up by ISBN (10 or 13 digits)
  lccn   Look up by Library of Congress Control Number
  oclc   Look up by OCLC / WorldCat control number
  olid   Look up by Open Library edition OLID (OL<N>M)
  batch  Look up multiple identifiers in a single request",
    after_help = "\
EXAMPLES
  olib volume isbn 0451450523
  olib volume lccn 2004046975
  olib volume oclc 45883427
  olib volume olid OL7408846M
  olib volume batch isbn/0451450523 oclc/45883427
  olib --json volume isbn 0451450523 | jq '.items[].status'
  olib --json volume isbn 0451450523 | jq '.records | keys'",
)]
struct VolumeArgs {
    #[command(subcommand)]
    cmd: VolumeCmd,
}

#[derive(Subcommand)]
enum VolumeCmd {
    /// Look up a volume by ISBN-10 or ISBN-13
    #[command(after_help = "EXAMPLES\n  olib volume isbn 0451450523\n  olib volume isbn 9780451450524")]
    Isbn {
        /// ISBN value (10 or 13 digits; hyphens ignored)
        value: String,
    },
    /// Look up a volume by Library of Congress Control Number
    #[command(after_help = "EXAMPLE\n  olib volume lccn 2004046975")]
    Lccn {
        /// LCCN value
        value: String,
    },
    /// Look up a volume by OCLC / WorldCat control number
    #[command(after_help = "EXAMPLE\n  olib volume oclc 45883427")]
    Oclc {
        /// OCLC number
        value: String,
    },
    /// Look up a volume by Open Library edition OLID (format: OL<N>M)
    #[command(after_help = "EXAMPLE\n  olib volume olid OL7408846M")]
    Olid {
        /// Edition OLID, e.g. OL7408846M
        value: String,
    },
    /// Look up multiple volumes in a single request
    ///
    /// Each argument is a "type/value" pair, e.g. isbn/0451450523 or oclc/45883427.
    /// Valid types: isbn | lccn | oclc | olid
    #[command(
        after_help = "\
EXAMPLES
  olib volume batch isbn/0451450523 oclc/45883427
  olib volume batch isbn/0451450523 isbn/9780140328724 lccn/2004046975
  olib --json volume batch isbn/0451450523 oclc/45883427 | jq '.records | keys'",
    )]
    Batch {
        /// One or more type/value pairs (e.g. isbn/0451450523 oclc/45883427)
        requests: Vec<String>,
    },
}

// ── Books (bibkey) ────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Look up books by bibliographic key via /api/books",
    long_about = "\
The /api/books endpoint accepts one or more bibliographic keys and returns
structured data for each matched book.

BIBKEY FORMAT
  <PREFIX>:<VALUE>   e.g. ISBN:9780451450524

VALID PREFIXES
  ISBN    International Standard Book Number (10 or 13 digits)
  OCLC    OCLC / WorldCat control number
  LCCN    Library of Congress Control Number
  OLID    Open Library edition identifier (OL<N>M)
  ID      Internal Open Library cover / record ID

JSCMD VALUES
  data     (default) Full bibliographic data bundle per book
  details  Structured details including subjects, excerpts, and identifiers
  viewapi  Preview URLs and read-online / borrow links",
    after_help = "\
EXAMPLES
  olib books ISBN:9780451450524
  olib books ISBN:0451450523 OCLC:45883427
  olib books ISBN:0451450523 OCLC:45883427 LCCN:2004046975
  olib books OLID:OL7408846M ID:5428012
  olib books ISBN:0451450523 --jscmd details
  olib books ISBN:0451450523 --jscmd viewapi
  olib --json books ISBN:0451450523 | jq '.'",
)]
struct BooksCliArgs {
    /// One or more bibliographic keys (format: PREFIX:VALUE)
    bibkeys: Vec<String>,
    /// What data to return: data (default) | details | viewapi
    #[arg(long, default_value = "data", value_name = "CMD")]
    jscmd: String,
}

// ── Query ─────────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Query any Open Library object type via /query.json",
    long_about = "\
The /query.json endpoint lets you filter any Open Library object type by
field values. It is a low-level building block useful for lookups not covered
by the dedicated endpoints.

OBJECT TYPES (--type)
  /type/work       Works (books as abstract creative entities)
  /type/edition    Editions (specific printings)
  /type/author     Author records
  /type/subject    Subject records
  /type/list       User-created lists
  /type/user       User accounts

FIELD FILTERS (--field)
  Pass one or more key=value pairs. All filters are AND-ed.
  Field names match the JSON keys in the object's schema.",
    after_help = "\
EXAMPLES
  olib query --type /type/edition --field isbn=0451450523
  olib query --type /type/work --field title=Dune
  olib query --type /type/edition --field publishers=Penguin
  olib query --type /type/edition --field publish_date=1988 --limit 5
  olib --json query --type /type/edition --field isbn=0451450523 | jq '.result'",
)]
struct QueryCliArgs {
    /// Open Library object type path, e.g. /type/edition
    #[arg(long, value_name = "TYPE")]
    r#type: String,
    /// Field filter as key=value (repeat for multiple filters)
    #[arg(long, value_name = "KEY=VALUE")]
    field: Vec<String>,
    /// Number of results to return (1–1000)
    #[arg(long, default_value = "20", value_name = "N")]
    limit: u32,
    /// Number of results to skip (for pagination)
    #[arg(long, default_value = "0", value_name = "N")]
    offset: u32,
}

// ── History ───────────────────────────────────────────────────────────────────

#[derive(Args)]
#[command(
    about = "Fetch the full revision history of an Open Library resource",
    long_about = "\
Appends ?m=history to any Open Library resource key and returns the full list
of revisions, each with a timestamp, editor, and optional edit comment.

The key is an Open Library path starting with /works/, /books/, or /authors/.",
    after_help = "\
EXAMPLES
  olib history /works/OL45804W
  olib history /books/OL7353617M
  olib history /authors/OL23919A
  olib --json history /works/OL45804W | jq '.[0] | {revision, timestamp, comment}'
  olib --json history /works/OL45804W | jq 'length'",
)]
struct HistoryArgs {
    /// Open Library resource path, e.g. /works/OL45804W or /books/OL7353617M
    key: String,
}

// ═════════════════════════════════════════════════════════════════════════════
// Entry point
// ═════════════════════════════════════════════════════════════════════════════

#[tokio::main]
async fn main() {
    let cli = Cli::parse();

    let client = match build_client(&cli) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: {e}");
            process::exit(1);
        }
    };

    if let Err(e) = dispatch(&cli, &client).await {
        eprintln!("error: {e}");
        process::exit(1);
    }
}

fn build_client(cli: &Cli) -> Result<OpenLibraryClient> {
    let mut builder = OpenLibraryClient::builder().rate_limit(cli.rate_limit);
    if let Some(email) = &cli.email {
        builder = builder.contact_email(email.as_str())?;
    }
    if let Some(url) = &cli.base_url {
        builder = builder.base_url(url.as_str());
    }
    if let Some(url) = &cli.covers_url {
        builder = builder.covers_url(url.as_str());
    }
    builder.build()
}

async fn dispatch(cli: &Cli, client: &OpenLibraryClient) -> Result<()> {
    let json = cli.json;
    match &cli.command {
        Cmd::Work(a) => handle_work(json, client, &a.cmd).await,
        Cmd::Edition(a) => handle_edition(json, client, &a.cmd).await,
        Cmd::Author(a) => handle_author(json, client, &a.cmd).await,
        Cmd::Search(a) => handle_search(json, client, &a.cmd).await,
        Cmd::Subject(a) => handle_subject(json, client, a).await,
        Cmd::Cover(a) => handle_cover(json, client, &a.cmd).await,
        Cmd::List(a) => handle_list(json, client, &a.cmd).await,
        Cmd::Reading(a) => handle_reading(json, client, &a.cmd).await,
        Cmd::Changes(a) => handle_changes(json, client, a).await,
        Cmd::Volume(a) => handle_volume(json, client, &a.cmd).await,
        Cmd::Books(a) => handle_books(json, client, a).await,
        Cmd::Query(a) => handle_query(json, client, a).await,
        Cmd::History(a) => handle_history(json, client, a).await,
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// Handlers
// ═════════════════════════════════════════════════════════════════════════════

async fn handle_work(json: bool, client: &OpenLibraryClient, cmd: &WorkCmd) -> Result<()> {
    match cmd {
        WorkCmd::Get { id } => {
            let v = client.get_work(id).await?;
            if json { print_json(&v) } else { print_work(&v) }
        }
        WorkCmd::Editions { id, limit, offset } => {
            let v = client.get_work_editions(id, *limit, *offset).await?;
            if json { print_json(&v) } else { print_work_editions(&v) }
        }
        WorkCmd::Ratings { id } => {
            let v = client.get_work_ratings(id).await?;
            if json { print_json(&v) } else { print_work_ratings(&v) }
        }
        WorkCmd::Bookshelves { id } => {
            let v = client.get_work_bookshelves(id).await?;
            if json { print_json(&v) } else { print_work_bookshelves(&v) }
        }
    }
    Ok(())
}

async fn handle_edition(json: bool, client: &OpenLibraryClient, cmd: &EditionCmd) -> Result<()> {
    match cmd {
        EditionCmd::Get { id } => {
            let v = client.get_edition(id).await?;
            if json { print_json(&v) } else { print_edition(&v) }
        }
        EditionCmd::Isbn { isbn } => {
            let v = client.get_edition_by_isbn(isbn).await?;
            if json { print_json(&v) } else { print_edition(&v) }
        }
    }
    Ok(())
}

async fn handle_author(json: bool, client: &OpenLibraryClient, cmd: &AuthorCmd) -> Result<()> {
    match cmd {
        AuthorCmd::Get { id } => {
            let v = client.get_author(id).await?;
            if json { print_json(&v) } else { print_author(&v) }
        }
        AuthorCmd::Works { id, limit, offset } => {
            let v = client.get_author_works(id, *limit, *offset).await?;
            if json { print_json(&v) } else { print_author_works(&v) }
        }
    }
    Ok(())
}

async fn handle_search(json: bool, client: &OpenLibraryClient, cmd: &SearchCmd) -> Result<()> {
    match cmd {
        SearchCmd::Books {
            q, title, author, isbn, subject, place, person, language,
            limit, offset, sort,
        } => {
            let params = SearchParams {
                q: q.clone(),
                title: title.clone(),
                author: author.clone(),
                isbn: isbn.clone(),
                subject: subject.clone(),
                place: place.clone(),
                person: person.clone(),
                language: language.clone(),
                limit: Some(*limit),
                offset: Some(*offset),
                sort: sort.clone(),
                ..Default::default()
            };
            let v = client.search(params).await?;
            if json { print_json(&v) } else { print_search_books(&v) }
        }
        SearchCmd::Authors { q, limit, offset } => {
            let params = AuthorSearchParams {
                q: Some(q.clone()),
                limit: Some(*limit),
                offset: Some(*offset),
            };
            let v = client.search_authors(params).await?;
            if json { print_json(&v) } else { print_search_authors(&v) }
        }
        SearchCmd::Subjects { query } => {
            let v = client.search_subjects(query).await?;
            if json { print_json(&v) } else { print_search_subjects(&v) }
        }
        SearchCmd::Lists { query, limit } => {
            let v = client.search_lists(query, Some(*limit)).await?;
            if json { print_json(&v) } else { print_search_lists(&v) }
        }
        SearchCmd::Inside { query, limit } => {
            let v = client.search_inside(query, Some(*limit)).await?;
            if json { print_json(&v) } else { print_search_inside(&v) }
        }
    }
    Ok(())
}

async fn handle_subject(json: bool, client: &OpenLibraryClient, a: &SubjectCliArgs) -> Result<()> {
    let params = SubjectParams {
        details: if a.details { Some(true) } else { None },
        ebooks: if a.ebooks { Some(true) } else { None },
        published_in: a.published_in.clone(),
        limit: Some(a.limit),
        offset: Some(a.offset),
    };
    let v = client.get_subject(&a.slug, params).await?;
    if json { print_json(&v) } else { print_subject(&v) }
    Ok(())
}

async fn handle_cover(json: bool, client: &OpenLibraryClient, cmd: &CoverCmd) -> Result<()> {
    match cmd {
        CoverCmd::Url { key, value, size } => {
            let ck = parse_cover_key(key)?;
            let sz = parse_image_size(size)?;
            let url = client.cover_url(ck, value, sz);
            println!("{url}");
        }
        CoverCmd::Meta { key, value } => {
            let ck = parse_cover_key(key)?;
            let v = client.cover_meta(ck, value).await?;
            if json { print_json(&v) } else { print_cover_meta(&v) }
        }
        CoverCmd::Photo { olid, size } => {
            let sz = parse_image_size(size)?;
            let url = client.author_photo_url(olid, sz)?;
            println!("{url}");
        }
    }
    Ok(())
}

async fn handle_list(json: bool, client: &OpenLibraryClient, cmd: &ListCmd) -> Result<()> {
    match cmd {
        ListCmd::User { username, limit, offset } => {
            let v = client.get_user_lists(username, *limit, *offset).await?;
            if json { print_json(&v) } else { print_user_lists(&v) }
        }
        ListCmd::Show { username, list_id } => {
            let v = client.get_list(username, list_id).await?;
            if json { print_json(&v) } else { print_list(&v) }
        }
        ListCmd::Editions { username, list_id, limit, offset } => {
            let v = client.get_list_editions(username, list_id, *limit, *offset).await?;
            if json { print_json(&v) } else { print_list_editions(&v) }
        }
        ListCmd::Subjects { username, list_id } => {
            let v = client.get_list_subjects(username, list_id).await?;
            if json { print_json(&v) } else { print_list_subjects(&v) }
        }
        ListCmd::Seeds { username, list_id } => {
            let v = client.get_list_seeds(username, list_id).await?;
            if json { print_json(&v) } else { print_list_seeds(&v) }
        }
    }
    Ok(())
}

async fn handle_reading(json: bool, client: &OpenLibraryClient, cmd: &ReadingCmd) -> Result<()> {
    let (v, username) = match cmd {
        ReadingCmd::WantToRead { username } => (client.get_want_to_read(username).await?, username),
        ReadingCmd::CurrentlyReading { username } => {
            (client.get_currently_reading(username).await?, username)
        }
        ReadingCmd::AlreadyRead { username } => (client.get_already_read(username).await?, username),
    };
    if json { print_json(&v) } else { print_reading_log(username, &v) }
    Ok(())
}

async fn handle_changes(json: bool, client: &OpenLibraryClient, a: &ChangesCliArgs) -> Result<()> {
    let params = ChangesParams {
        limit: Some(a.limit),
        offset: Some(a.offset),
        bot: a.bot,
    };
    let v = match (&a.date, &a.kind) {
        (Some(date), Some(kind)) => {
            let ck = parse_change_kind(kind)?;
            client.get_changes_by_date_and_kind(date, &ck, params).await?
        }
        (Some(date), None) => client.get_changes_by_date(date, params).await?,
        (None, Some(kind)) => {
            let ck = parse_change_kind(kind)?;
            client.get_changes_by_kind(&ck, params).await?
        }
        (None, None) => client.get_recent_changes(params).await?,
    };
    if json { print_json(&v) } else { print_changes(&v) }
    Ok(())
}

async fn handle_volume(json: bool, client: &OpenLibraryClient, cmd: &VolumeCmd) -> Result<()> {
    let v = match cmd {
        VolumeCmd::Isbn { value } => client.read_volume(VolumeIdType::Isbn, value).await?,
        VolumeCmd::Lccn { value } => client.read_volume(VolumeIdType::Lccn, value).await?,
        VolumeCmd::Oclc { value } => client.read_volume(VolumeIdType::Oclc, value).await?,
        VolumeCmd::Olid { value } => client.read_volume(VolumeIdType::Olid, value).await?,
        VolumeCmd::Batch { requests } => client.read_volumes_batch(requests).await?,
    };
    if json { print_json(&v) } else { print_volumes(&v) }
    Ok(())
}

async fn handle_books(
    json: bool,
    client: &OpenLibraryClient,
    a: &BooksCliArgs,
) -> Result<()> {
    let jscmd = match a.jscmd.as_str() {
        "details" => BooksJsCmd::Details,
        "viewapi" => BooksJsCmd::ViewApi,
        _ => BooksJsCmd::Data,
    };
    let v = client.get_books(&a.bibkeys, jscmd).await?;
    if json {
        print_json(&v);
    } else {
        for (key, entry) in &v {
            show("Bibkey", key);
            if let Some(u) = &entry.info_url { show("URL", u); }
            if let Some(p) = &entry.preview { show("Preview", p); }
            if let Some(t) = &entry.thumbnail_url { show("Thumbnail", t); }
            println!();
        }
    }
    Ok(())
}

async fn handle_query(json: bool, client: &OpenLibraryClient, a: &QueryCliArgs) -> Result<()> {
    let mut fields: HashMap<String, String> = HashMap::new();
    for f in &a.field {
        if let Some((k, v)) = f.split_once('=') {
            fields.insert(k.to_string(), v.to_string());
        } else {
            eprintln!("warning: ignoring malformed --field value (expected key=value): {f}");
        }
    }
    let v = client.query(&a.r#type, &fields, a.limit, a.offset).await?;
    if json {
        print_json(&v);
    } else {
        print_query_results(&v);
    }
    Ok(())
}

async fn handle_history(json: bool, client: &OpenLibraryClient, a: &HistoryArgs) -> Result<()> {
    let v = client.get_resource_history(&a.key).await?;
    if json { print_json(&v) } else { print_history(&v) }
    Ok(())
}

// ═════════════════════════════════════════════════════════════════════════════
// Print helpers — human-readable output
// ═════════════════════════════════════════════════════════════════════════════

fn print_json(v: &impl serde::Serialize) {
    match serde_json::to_string_pretty(v) {
        Ok(s) => println!("{s}"),
        Err(e) => eprintln!("error: failed to serialize response: {e}"),
    }
}

fn show(label: &str, value: &str) {
    println!("{:<22} {}", format!("{label}:"), value);
}

fn print_work(w: &Work) {
    show("Key", &w.key);
    if let Some(t) = &w.title { show("Title", t); }
    if let Some(s) = &w.subtitle { show("Subtitle", s); }
    if let Some(d) = &w.description { show("Description", d.as_str()); }
    if let Some(a) = &w.authors {
        let keys: Vec<_> = a.iter().map(|r| r.author.key.as_str()).collect();
        show("Authors", &keys.join(", "));
    }
    if let Some(s) = &w.subjects { show("Subjects", &s.join(", ")); }
    if let Some(p) = &w.subject_places { show("Places", &p.join(", ")); }
    if let Some(p) = &w.subject_people { show("People", &p.join(", ")); }
    if let Some(t) = &w.subject_times { show("Times", &t.join(", ")); }
    if let Some(d) = &w.first_publish_date { show("First Published", d); }
    if let Some(c) = &w.covers {
        let ids: Vec<_> = c.iter().map(|n| n.to_string()).collect();
        show("Covers", &ids.join(", "));
    }
    if let Some(r) = &w.latest_revision { show("Revision", &r.to_string()); }
}

fn print_work_editions(we: &WorkEditions) {
    let count = we.size.unwrap_or(we.entries.len() as u64);
    println!("Editions ({count} total):");
    for (i, e) in we.entries.iter().enumerate() {
        let title = e.title.as_deref().unwrap_or("(no title)");
        let year = e.publish_date.as_deref().unwrap_or("?");
        println!("  [{:>3}] {}{} ({})", i + 1, e.key, title, year);
    }
}

fn print_work_ratings(r: &WorkRatings) {
    if let Some(s) = &r.summary {
        if let Some(avg) = s.average { show("Average", &format!("{avg:.2}")); }
        if let Some(n) = s.count { show("Ratings", &n.to_string()); }
    }
    if let Some(c) = &r.counts {
        println!("Distribution:");
        for (stars, n) in [
            (5, c.five), (4, c.four), (3, c.three), (2, c.two), (1, c.one),
        ] {
            let n = n.unwrap_or(0);
            println!("  {stars}{n}");
        }
    }
}

fn print_work_bookshelves(b: &WorkBookshelves) {
    if let Some(c) = &b.counts {
        show("Want to Read",      &c.want_to_read.unwrap_or(0).to_string());
        show("Currently Reading", &c.currently_reading.unwrap_or(0).to_string());
        show("Already Read",      &c.already_read.unwrap_or(0).to_string());
    }
}

fn print_edition(e: &Edition) {
    show("Key", &e.key);
    if let Some(t) = &e.title { show("Title", t); }
    if let Some(s) = &e.subtitle { show("Subtitle", s); }
    if let Some(p) = &e.publishers { show("Publishers", &p.join(", ")); }
    if let Some(d) = &e.publish_date { show("Published", d); }
    if let Some(n) = e.number_of_pages { show("Pages", &n.to_string()); }
    if let Some(l) = &e.languages {
        let keys: Vec<_> = l.iter().map(|k| k.key.as_str()).collect();
        show("Languages", &keys.join(", "));
    }
    if let Some(v) = &e.isbn_13 { show("ISBN-13", &v.join(", ")); }
    if let Some(v) = &e.isbn_10 { show("ISBN-10", &v.join(", ")); }
    if let Some(v) = &e.lccn { show("LCCN", &v.join(", ")); }
    if let Some(v) = &e.oclc_numbers { show("OCLC", &v.join(", ")); }
    if let Some(f) = &e.physical_format { show("Format", f); }
    if let Some(w) = &e.weight { show("Weight", w); }
    if let Some(c) = &e.covers {
        let ids: Vec<_> = c.iter().map(|n| n.to_string()).collect();
        show("Covers", &ids.join(", "));
    }
}

fn print_author(a: &Author) {
    show("Key", &a.key);
    if let Some(n) = &a.name { show("Name", n); }
    if let Some(p) = &a.personal_name { show("Personal Name", p); }
    if let Some(alt) = &a.alternate_names { show("Also Known As", &alt.join(", ")); }
    if let Some(b) = &a.birth_date { show("Born", b); }
    if let Some(d) = &a.death_date { show("Died", d); }
    if let Some(bio) = &a.bio { show("Bio", bio.as_str()); }
    if let Some(w) = &a.wikipedia { show("Wikipedia", w); }
    if let Some(p) = &a.photos {
        let ids: Vec<_> = p.iter().map(|n| n.to_string()).collect();
        show("Photos", &ids.join(", "));
    }
}

fn print_author_works(aw: &AuthorWorks) {
    println!("Works ({} shown):", aw.entries.len());
    for (i, e) in aw.entries.iter().enumerate() {
        let title = e.title.as_deref().unwrap_or("(no title)");
        println!("  [{:>3}] {}{}", i + 1, e.key, title);
    }
}

fn print_search_books(r: &SearchResponse<BookDoc>) {
    println!("Found {} result{} (showing {}):",
        r.num_found,
        if r.num_found == 1 { "" } else { "s" },
        r.docs.len());
    println!();
    for (i, doc) in r.docs.iter().enumerate() {
        let title = doc.title.as_deref().unwrap_or("(no title)");
        println!("[{}] {}", i + 1, title);
        println!("    Key:      {}", doc.key);
        if let Some(authors) = &doc.author_name {
            println!("    Authors:  {}", authors.join(", "));
        }
        if let Some(year) = doc.first_publish_year {
            println!("    Year:     {year}");
        }
        println!("    Editions: {}", doc.edition_count);
        println!();
    }
}

fn print_search_authors(r: &SearchResponse<AuthorDoc>) {
    println!("Found {} author{} (showing {}):",
        r.num_found,
        if r.num_found == 1 { "" } else { "s" },
        r.docs.len());
    println!();
    for (i, doc) in r.docs.iter().enumerate() {
        let name = doc.name.as_deref().unwrap_or("(no name)");
        println!("[{}] {}{}", i + 1, name, doc.key);
        if let Some(b) = &doc.birth_date { println!("    Born: {b}"); }
        if let Some(n) = doc.work_count { println!("    Works: {n}"); }
        println!();
    }
}

fn print_search_subjects(r: &SearchResponse<SubjectDoc>) {
    println!("Found {} subject{} (showing {}):",
        r.num_found,
        if r.num_found == 1 { "" } else { "s" },
        r.docs.len());
    for doc in &r.docs {
        let name = doc.name.as_deref().unwrap_or("(no name)");
        let count = doc.work_count.unwrap_or(0);
        println!("  {} ({count} works) — {}", name, doc.key);
    }
}

fn print_search_lists(r: &SearchResponse<ListDoc>) {
    println!("Found {} list{} (showing {}):",
        r.num_found,
        if r.num_found == 1 { "" } else { "s" },
        r.docs.len());
    for doc in &r.docs {
        let name = doc.name.as_deref().unwrap_or("(unnamed)");
        println!("  {}{}", name, doc.key);
    }
}

fn print_search_inside(r: &SearchResponse<InsideDoc>) {
    println!("Found {} result{} (showing {}):",
        r.num_found,
        if r.num_found == 1 { "" } else { "s" },
        r.docs.len());
    for (i, doc) in r.docs.iter().enumerate() {
        let title = doc.title.as_deref().unwrap_or("(no title)");
        println!("[{}] {}", i + 1, title);
        if let Some(a) = &doc.author { println!("    Author: {a}"); }
        if let Some(t) = &doc.text { println!("    Excerpt: {}", &t[..t.len().min(120)]); }
        println!();
    }
}

fn print_subject(s: &Subject) {
    show("Key", &s.key);
    if let Some(n) = &s.name { show("Name", n); }
    if let Some(k) = &s.subject_type { show("Type", k); }
    if let Some(c) = s.work_count { show("Work Count", &c.to_string()); }
    println!();
    if !s.works.is_empty() {
        println!("Works ({} shown):", s.works.len());
        for (i, w) in s.works.iter().enumerate() {
            let title = w.title.as_deref().unwrap_or("(no title)");
            println!("  [{:>3}] {}{}", i + 1, w.key, title);
        }
    }
    if let Some(authors) = &s.authors {
        println!();
        println!("Authors:");
        for a in authors {
            let name = a.name.as_deref().unwrap_or("(unknown)");
            println!("  {}{}", name, a.key);
        }
    }
    if let Some(rel) = &s.related_subjects {
        println!();
        println!("Related Subjects:");
        for r in rel {
            println!("  {}", r.name);
        }
    }
}

fn print_cover_meta(metas: &[CoverMeta]) {
    if metas.is_empty() {
        println!("No cover metadata found.");
        return;
    }
    for m in metas {
        if let Some(id) = m.id { show("Cover ID", &id.to_string()); }
        if let Some(s) = &m.size { show("Size", s); }
        if let Some(u) = &m.url { show("URL", u); }
        println!();
    }
}

fn print_user_lists(ul: &UserLists) {
    let total = ul.size.unwrap_or(ul.lists.len() as u64);
    println!("Lists ({total} total, {} shown):", ul.lists.len());
    for l in &ul.lists {
        let name = l.name.as_deref().unwrap_or("(unnamed)");
        let seeds = l.seed_count.unwrap_or(0);
        println!("  {}{} ({seeds} seeds)", name, l.key);
    }
}

fn print_list(l: &List) {
    show("Key", &l.key);
    if let Some(n) = &l.name { show("Name", n); }
    if let Some(d) = &l.description { show("Description", d); }
    if let Some(t) = &l.tags { show("Tags", &t.join(", ")); }
    if let Some(s) = l.seed_count { show("Seeds", &s.to_string()); }
    if let Some(e) = l.edition_count { show("Editions", &e.to_string()); }
    if let Some(u) = &l.last_update { show("Last Updated", u); }
}

fn print_list_editions(le: &ListEditions) {
    let total = le.size.unwrap_or(le.entries.len() as u64);
    println!("Editions ({total} total, {} shown):", le.entries.len());
    for (i, e) in le.entries.iter().enumerate() {
        let title = e.title.as_deref().unwrap_or("(no title)");
        let date = e.publish_date.as_deref().unwrap_or("?");
        println!("  [{:>3}] {}{} ({})", i + 1, e.key, title, date);
    }
}

fn print_list_subjects(ls: &ListSubjects) {
    if !ls.subjects.is_empty() {
        println!("Subjects:");
        for s in &ls.subjects {
            println!("  {} ({})", s.name, s.count.unwrap_or(0));
        }
    }
    if !ls.places.is_empty() {
        println!("Places:");
        for s in &ls.places {
            println!("  {} ({})", s.name, s.count.unwrap_or(0));
        }
    }
    if !ls.people.is_empty() {
        println!("People:");
        for s in &ls.people {
            println!("  {} ({})", s.name, s.count.unwrap_or(0));
        }
    }
    if !ls.times.is_empty() {
        println!("Times:");
        for s in &ls.times {
            println!("  {} ({})", s.name, s.count.unwrap_or(0));
        }
    }
}

fn print_list_seeds(ls: &ListSeeds) {
    let total = ls.size.unwrap_or(ls.entries.len() as u64);
    println!("Seeds ({total} total, {} shown):", ls.entries.len());
    for seed in &ls.entries {
        match seed {
            ListSeed::Key(k) => println!("  {}", k.key),
            ListSeed::Subject { url, title } => println!("  {title}{url}"),
        }
    }
}

fn print_reading_log(username: &str, log: &ReadingLog) {
    println!("{}'s reading log ({} entries):", username, log.reading_log_entries.len());
    println!();
    for (i, entry) in log.reading_log_entries.iter().enumerate() {
        if let Some(work) = &entry.work {
            let title = work.title.as_deref().unwrap_or("(no title)");
            println!("[{}] {}{}", i + 1, title, work.key);
            if let Some(authors) = &work.author_names {
                println!("    Authors: {}", authors.join(", "));
            }
            if let Some(d) = &entry.logged_date {
                println!("    Logged:  {d}");
            }
            println!();
        }
    }
}

fn print_changes(changes: &[RecentChange]) {
    println!("{} change{}:", changes.len(), if changes.len() == 1 { "" } else { "s" });
    println!();
    for c in changes {
        let kind = c.kind.as_ref().map(|k| k.as_str()).unwrap_or("?");
        let key = c.key.as_deref().unwrap_or("?");
        let ts = c.timestamp.as_deref().unwrap_or("?");
        let comment = c.comment.as_deref().unwrap_or("");
        println!("  [{kind}] {key}");
        println!("          {ts}  {comment}");
    }
}

fn print_volumes(v: &VolumesResponse) {
    if v.records.is_empty() && v.items.is_empty() {
        println!("No volumes found.");
        return;
    }
    println!("Records ({}):", v.records.len());
    for (key, rec) in &v.records {
        println!("  {key}");
        if let Some(title) = &rec.title { println!("    Title: {title}"); }
        if let Some(url) = &rec.url { println!("    URL:   {url}"); }
    }
    println!();
    println!("Items ({}):", v.items.len());
    for item in &v.items {
        let status = item.status.as_ref().map(|s| format!("{s:?}")).unwrap_or_default();
        let url = item.url.as_deref().unwrap_or("?");
        println!("  [{status}] {url}");
    }
}

fn print_query_results(q: &QueryResponse) {
    println!("{} result{}:", q.result.len(), if q.result.len() == 1 { "" } else { "s" });
    for r in &q.result {
        println!("  {r}");
    }
}

fn print_history(entries: &[HistoryEntry]) {
    println!("{} revision{}:", entries.len(), if entries.len() == 1 { "" } else { "s" });
    println!();
    for e in entries {
        let rev = e.revision.unwrap_or(0);
        let ts = e.timestamp.as_deref().unwrap_or("?");
        let comment = e.comment.as_deref().unwrap_or("");
        println!("  r{rev}  {ts}  {comment}");
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// Parsers for enum CLI arguments
// ═════════════════════════════════════════════════════════════════════════════

fn parse_cover_key(s: &str) -> Result<CoverKey> {
    Ok(match s.to_lowercase().as_str() {
        "id" => CoverKey::Id,
        "isbn" => CoverKey::Isbn,
        "oclc" => CoverKey::Oclc,
        "lccn" => CoverKey::Lccn,
        "olid" => CoverKey::Olid,
        _ => return Err(open_library_api_rs::Error::InvalidInput(
            format!("unknown cover key type '{s}': expected id|isbn|oclc|lccn|olid")
        )),
    })
}

fn parse_image_size(s: &str) -> Result<ImageSize> {
    Ok(match s.to_lowercase().as_str() {
        "s" | "small" => ImageSize::Small,
        "m" | "medium" => ImageSize::Medium,
        "l" | "large" => ImageSize::Large,
        _ => return Err(open_library_api_rs::Error::InvalidInput(
            format!("unknown image size '{s}': expected small|medium|large (or s|m|l)")
        )),
    })
}

fn parse_change_kind(s: &str) -> Result<ChangeKind> {
    Ok(match s {
        "add-cover" => ChangeKind::AddCover,
        "add-book" => ChangeKind::AddBook,
        "edit-book" => ChangeKind::EditBook,
        "merge-authors" => ChangeKind::MergeAuthors,
        "update" => ChangeKind::Update,
        "revert" => ChangeKind::Revert,
        "new-account" => ChangeKind::NewAccount,
        "register" => ChangeKind::Register,
        "lists" => ChangeKind::Lists,
        _ => return Err(open_library_api_rs::Error::InvalidInput(
            format!("unknown change kind '{s}'")
        )),
    })
}