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
#!/usr/bin/env python3
"""Generate a book reader index.html inside each directory listed in metadata.json.

Each generated <directory>/index.html provides:
- Full-size page reader using `full/0001.webp` ... `full/NNNN.webp` (plus a toggle for `bw/`).
- Forward / Backward navigation (buttons, click zones, keyboard ArrowLeft/ArrowRight/j/k/Space).
- Page jumper input and progress indicator.
- "All Thumbnails" grid modal/drawer (`thumb/0001.webp` ... `thumb/NNNN.webp` with lazy loading)
  to browse and jump to any page.
- URL state persistence (`?page=N` + `#page=N` support with `history.pushState` and `popstate`)
  so bookmarking, sharing links, reloading, and browser back/forward keep the current page.

Usage:
    python3 generate_readers.py [--metadata metadata.json] [--only SLUG]
"""
from __future__ import annotations

import argparse
import html
import json
import re
import sys
from pathlib import Path
from urllib.parse import quote

import fitz  # PyMuPDF


def clean_display_title(source_path: str) -> str:
    name = Path(source_path).name
    stem = name[:-4] if name.lower().endswith(".pdf") else name
    stem = re.sub(r"\s*\((kann+n?ada|english)\)\s*$", "", stem, flags=re.IGNORECASE)
    return stem.strip()


def get_page_count(entry: dict, base_dir: Path) -> int:
    """Determine page count from extracted images or fallback to the source PDF."""
    out_dir = base_dir / entry["directory"]
    full_dir = out_dir / "full"
    if full_dir.is_dir():
        webps = sorted(full_dir.glob("*.webp"))
        if webps:
            # Also check PDF if available in case only partial pages were extracted so far
            pdf_path = base_dir / entry["source"]
            if pdf_path.is_file():
                try:
                    with fitz.open(pdf_path) as doc:
                        return max(len(webps), len(doc))
                except Exception:  # noqa: BLE001
                    pass
            return len(webps)

    pdf_path = base_dir / entry["source"]
    if pdf_path.is_file():
        try:
            with fitz.open(pdf_path) as doc:
                return len(doc)
        except Exception:  # noqa: BLE001
            return 0
    return 0


def build_reader_html(entry: dict, page_count: int) -> str:
    source = entry["source"]
    en_title = clean_display_title(source)
    kn_title = entry.get("kannada")
    pdf_href = "../" + "/".join(quote(part) for part in Path(source).parts)

    if kn_title:
        page_title = f"{kn_title} — {en_title}"
        header_title_html = (
            f'<span class="title-kn">{html.escape(kn_title)}</span>'
            f'<span class="title-en">{html.escape(en_title)}</span>'
        )
    else:
        page_title = en_title
        header_title_html = f'<span class="title-main">{html.escape(en_title)}</span>'

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{html.escape(page_title)} — Reader</title>
<style>
  :root {{
    --maroon: #72211f;
    --maroon-dark: #571915;
    --gold: #c9a227;
    --bg: #1e1b18;
    --panel: #2a2521;
    --ink: #f5efe6;
    --muted: #b8aca0;
    --line: #3d352e;
  }}
  * {{ box-sizing: border-box; }}
  body {{
    margin: 0;
    padding: 0;
    background: var(--bg);
    color: var(--ink);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Georgia, sans-serif;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }}
  header {{
    position: sticky;
    top: 0;
    z-index: 30;
    background: var(--maroon);
    color: #f7ecd4;
    border-bottom: 3px solid var(--gold);
    padding: 0.55rem 1rem;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 0.6rem;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.45);
  }}
  .brand {{
    display: flex;
    align-items: center;
    gap: 0.75rem;
    min-width: 0;
  }}
  .back-link {{
    color: #ffe9b0;
    text-decoration: none;
    font-size: 0.88rem;
    padding: 0.3rem 0.65rem;
    border: 1px solid rgba(255, 233, 176, 0.45);
    border-radius: 6px;
    white-space: nowrap;
  }}
  .back-link:hover {{ background: var(--maroon-dark); }}
  .book-title {{
    display: flex;
    flex-direction: column;
    min-width: 0;
  }}
  .title-kn {{
    font-size: 1.05rem;
    font-weight: 600;
    line-height: 1.25;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }}
  .title-en {{
    font-size: 0.8rem;
    color: #ecd9ae;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }}
  .title-main {{
    font-size: 1.02rem;
    font-weight: 600;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }}
  .toolbar {{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 0.4rem;
  }}
  button, .btn-link, select {{
    font-family: inherit;
    font-size: 0.85rem;
    color: #fff;
    background: rgba(0, 0, 0, 0.28);
    border: 1px solid rgba(255, 233, 176, 0.4);
    border-radius: 6px;
    padding: 0.35rem 0.7rem;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.3rem;
  }}
  button:hover:not(:disabled), .btn-link:hover, select:hover {{
    background: var(--maroon-dark);
  }}
  button:disabled {{
    opacity: 0.4;
    cursor: not-allowed;
  }}
  button.active {{
    background: var(--gold);
    color: #1e1b18;
    border-color: var(--gold);
    font-weight: 600;
  }}
  .page-jump {{
    display: inline-flex;
    align-items: center;
    gap: 0.3rem;
    font-size: 0.85rem;
  }}
  #page-input {{
    width: 4.2rem;
    text-align: center;
    padding: 0.3rem 0.35rem;
    border-radius: 6px;
    border: 1px solid rgba(255, 233, 176, 0.5);
    background: rgba(0, 0, 0, 0.35);
    color: #fff;
    font-size: 0.85rem;
  }}
  main {{
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    padding: 1rem 0.5rem 2.5rem;
  }}
  .stage {{
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    max-width: 100%;
  }}
  #page-img {{
    display: block;
    background: #fff;
    box-shadow: 0 6px 28px rgba(0, 0, 0, 0.65);
    border-radius: 2px;
    user-select: none;
    max-width: min(1000px, 96vw);
    height: auto;
  }}
  body.fit-height #page-img {{
    max-height: calc(100vh - 96px);
    width: auto;
    max-width: 96vw;
  }}
  body.fit-original #page-img {{
    max-width: none;
    max-height: none;
  }}
  .nav-zone {{
    position: fixed;
    top: 64px;
    bottom: 48px;
    width: 12vw;
    min-width: 44px;
    max-width: 140px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 10;
    opacity: 0;
    transition: opacity 0.15s ease;
    user-select: none;
  }}
  .nav-zone:hover {{ opacity: 1; }}
  .nav-zone.prev {{ left: 0; }}
  .nav-zone.next {{ right: 0; }}
  .nav-pill {{
    background: rgba(114, 33, 31, 0.88);
    color: #fff;
    border: 1px solid var(--gold);
    border-radius: 999px;
    padding: 0.6rem 0.9rem;
    font-size: 1.1rem;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
  }}
  .bottom-bar {{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 25;
    background: rgba(42, 37, 33, 0.95);
    border-top: 1px solid var(--line);
    padding: 0.4rem 1rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.6rem;
    font-size: 0.82rem;
    color: var(--muted);
    backdrop-filter: blur(6px);
  }}
  #scrubber {{
    width: min(420px, 55vw);
    accent-color: var(--gold);
    cursor: pointer;
  }}
  /* Thumbnails Drawer / Modal */
  #thumbs-overlay {{
    position: fixed;
    inset: 0;
    z-index: 50;
    background: rgba(18, 15, 13, 0.94);
    display: none;
    flex-direction: column;
  }}
  #thumbs-overlay.open {{
    display: flex;
  }}
  .thumbs-header {{
    background: var(--panel);
    border-bottom: 1px solid var(--line);
    padding: 0.75rem 1.2rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }}
  .thumbs-grid {{
    flex: 1;
    overflow-y: auto;
    padding: 1.2rem;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 1rem;
    align-content: start;
  }}
  .thumb-card {{
    background: var(--panel);
    border: 2px solid transparent;
    border-radius: 6px;
    padding: 0.4rem;
    text-align: center;
    cursor: pointer;
    color: var(--ink);
    text-decoration: none;
    transition: transform 0.12s ease, border-color 0.12s ease;
  }}
  .thumb-card:hover {{
    transform: translateY(-2px);
    border-color: rgba(201, 162, 39, 0.6);
  }}
  .thumb-card.current {{
    border-color: var(--gold);
    background: rgba(201, 162, 39, 0.16);
  }}
  .thumb-card img {{
    width: 100%;
    aspect-ratio: 1 / 1.42;
    object-fit: contain;
    background: #fff;
    border-radius: 3px;
    display: block;
  }}
  .thumb-label {{
    margin-top: 0.35rem;
    font-size: 0.78rem;
    color: var(--muted);
  }}
  .thumb-card.current .thumb-label {{
    color: var(--gold);
    font-weight: 600;
  }}
  .status-msg {{
    margin-top: 1rem;
    color: var(--muted);
    font-size: 0.9rem;
    text-align: center;
  }}
</style>
</head>
<body>
  <header>
    <div class="brand">
      <a class="back-link" href="../index.html">&larr; All Books</a>
      <div class="book-title">{header_title_html}</div>
    </div>
    <div class="toolbar">
      <button type="button" id="btn-first" title="First page (Home)">&laquo;</button>
      <button type="button" id="btn-prev" title="Previous page (&larr;)">&lsaquo; Prev</button>
      <form class="page-jump" id="jump-form">
        <input id="page-input" type="number" min="1" max="{page_count}" value="1" aria-label="Page number">
        <span>/ <span id="total-pages">{page_count}</span></span>
      </form>
      <button type="button" id="btn-next" title="Next page (&rarr;)">Next &rsaquo;</button>
      <button type="button" id="btn-last" title="Last page (End)">&raquo;</button>
      <button type="button" id="btn-thumbs" title="View all page thumbnails (G)">Thumbnails</button>
      <select id="mode-select" aria-label="Image mode" title="Switch between Full Resolution and Clean Grayscale/BW">
        <option value="full" selected>Full Resolution</option>
        <option value="bw">Clean / B&amp;W</option>
      </select>
      <select id="fit-select" aria-label="Fit mode" title="Page fit mode">
        <option value="width" selected>Fit Width</option>
        <option value="height">Fit Height</option>
        <option value="original">Actual Size</option>
      </select>
      <a class="btn-link" href="{pdf_href}" download title="Download original PDF">PDF</a>
    </div>
  </header>

  <main>
    <div class="nav-zone prev" id="zone-prev" title="Previous page"><span class="nav-pill">&lsaquo;</span></div>
    <div class="stage">
      <img id="page-img" alt="Page 1" src="full/0001.webp">
    </div>
    <div class=" status-msg" id="status-msg" hidden></div>
    <div class="nav-zone next" id="zone-next" title="Next page"><span class="nav-pill">&rsaquo;</span></div>
  </main>

  <div class="bottom-bar">
    <span id="page-caption">Page 1 of {page_count}</span>
    <input id="scrubber" type="range" min="1" max="{max(1, page_count)}" value="1" aria-label="Page slider">
    <span>Keys: &larr;/&rarr; turn page &middot; G thumbnails &middot; F fit</span>
  </div>

  <div id="thumbs-overlay" role="dialog" aria-modal="true" aria-label="Page Thumbnails">
    <div class="thumbs-header">
      <strong>All Pages ({page_count})</strong>
      <button type="button" id="btn-close-thumbs">Close (Esc)</button>
    </div>
    <div class="thumbs-grid" id="thumbs-grid"></div>
  </div>

<script>
(function () {{
  var TOTAL = {page_count};
  var currentPage = 1;
  var currentMode = 'full';
  var thumbsBuilt = false;

  var imgEl = document.getElementById('page-img');
  var inputEl = document.getElementById('page-input');
  var scrubberEl = document.getElementById('scrubber');
  var captionEl = document.getElementById('page-caption');
  var statusEl = document.getElementById('status-msg');
  var btnFirst = document.getElementById('btn-first');
  var btnPrev = document.getElementById('btn-prev');
  var btnNext = document.getElementById('btn-next');
  var btnLast = document.getElementById('btn-last');
  var btnThumbs = document.getElementById('btn-thumbs');
  var btnCloseThumbs = document.getElementById('btn-close-thumbs');
  var overlayEl = document.getElementById('thumbs-overlay');
  var gridEl = document.getElementById('thumbs-grid');
  var modeSelect = document.getElementById('mode-select');
  var fitSelect = document.getElementById('fit-select');

  function pad4(n) {{
    return String(n).padStart(4, '0');
  }}

  function pageUrl(page, mode) {{
    return (mode || currentMode) + '/' + pad4(page) + '.webp';
  }}

  function thumbUrl(page) {{
    return 'thumb/' + pad4(page) + '.webp';
  }}

  function readStateFromUrl() {{
    var params = new URLSearchParams(window.location.search);
    var p = parseInt(params.get('page'), 10);
    if (!p && window.location.hash) {{
      var m = window.location.hash.match(/page=(\\d+)/);
      if (m) p = parseInt(m[1], 10);
    }}
    if (isNaN(p) || p < 1) p = 1;
    if (TOTAL > 0 && p > TOTAL) p = TOTAL;

    var mode = params.get('mode');
    if (mode === 'bw' || mode === 'full') {{
      currentMode = mode;
      modeSelect.value = mode;
    }}
    return p;
  }}

  function writeStateToUrl(replace) {{
    var url = new URL(window.location.href);
    url.searchParams.set('page', String(currentPage));
    if (currentMode !== 'full') {{
      url.searchParams.set('mode', currentMode);
    }} else {{
      url.searchParams.delete('mode');
    }}
    try {{
      if (replace) {{
        window.history.replaceState({{ page: currentPage, mode: currentMode }}, '', url);
      }} else {{
        window.history.pushState({{ page: currentPage, mode: currentMode }}, '', url);
      }}
    }} catch (e) {{
      window.location.hash = 'page=' + currentPage;
    }}
  }}

  function preload(page) {{
    if (page < 1 || page > TOTAL) return;
    var pre = new Image();
    pre.src = pageUrl(page, currentMode);
  }}

  function updateHighlightInThumbs() {{
    if (!thumbsBuilt) return;
    var prev = gridEl.querySelector('.thumb-card.current');
    if (prev) prev.classList.remove('current');
    var next = gridEl.querySelector('[data-page="' + currentPage + '"]');
    if (next) next.classList.add('current');
  }}

  function goToPage(page, opts) {{
    opts = opts || {{}};
    if (TOTAL < 1) return;
    var target = Math.max(1, Math.min(TOTAL, parseInt(page, 10) || 1));
    currentPage = target;

    statusEl.hidden = true;
    imgEl.src = pageUrl(currentPage, currentMode);
    imgEl.alt = 'Page ' + currentPage;
    inputEl.value = String(currentPage);
    scrubberEl.value = String(currentPage);
    captionEl.textContent = 'Page ' + currentPage + ' of ' + TOTAL;

    btnFirst.disabled = currentPage <= 1;
    btnPrev.disabled = currentPage <= 1;
    btnNext.disabled = currentPage >= TOTAL;
    btnLast.disabled = currentPage >= TOTAL;

    if (!opts.skipUrl) {{
      writeStateToUrl(Boolean(opts.replaceUrl));
    }}
    updateHighlightInThumbs();
    preload(currentPage + 1);
    preload(currentPage - 1);
    if (!opts.keepScroll) {{
      window.scrollTo({{ top: 0, behavior: 'instant' }});
    }}
  }}

  imgEl.addEventListener('error', function () {{
    statusEl.hidden = false;
    statusEl.textContent = 'Page image ' + pageUrl(currentPage, currentMode) + ' has not been generated yet. Run convert_pages.py to extract pages.';
  }});

  function buildThumbs() {{
    if (thumbsBuilt) return;
    var frag = document.createDocumentFragment();
    for (var i = 1; i <= TOTAL; i++) {{
      var a = document.createElement('a');
      a.className = 'thumb-card' + (i === currentPage ? ' current' : '');
      a.dataset.page = String(i);
      a.href = '?page=' + i;
      var im = document.createElement('img');
      im.loading = 'lazy';
      im.src = thumbUrl(i);
      im.alt = 'Page ' + i;
      var lbl = document.createElement('div');
      lbl.className = 'thumb-label';
      lbl.textContent = 'Page ' + i;
      a.appendChild(im);
      a.appendChild(lbl);
      a.addEventListener('click', function (ev) {{
        ev.preventDefault();
        var p = parseInt(this.dataset.page, 10);
        closeThumbs();
        goToPage(p);
      }});
      frag.appendChild(a);
    }}
    gridEl.appendChild(frag);
    thumbsBuilt = true;
  }}

  function openThumbs() {{
    buildThumbs();
    updateHighlightInThumbs();
    overlayEl.classList.add('open');
    btnThumbs.classList.add('active');
    var cur = gridEl.querySelector('.thumb-card.current');
    if (cur) cur.scrollIntoView({{ block: 'center' }});
  }}

  function closeThumbs() {{
    overlayEl.classList.remove('open');
    btnThumbs.classList.remove('active');
  }}

  function toggleThumbs() {{
    if (overlayEl.classList.contains('open')) closeThumbs();
    else openThumbs();
  }}

  btnFirst.addEventListener('click', function () {{ goToPage(1); }});
  btnPrev.addEventListener('click', function () {{ goToPage(currentPage - 1); }});
  btnNext.addEventListener('click', function () {{ goToPage(currentPage + 1); }});
  btnLast.addEventListener('click', function () {{ goToPage(TOTAL); }});
  document.getElementById('zone-prev').addEventListener('click', function () {{ goToPage(currentPage - 1); }});
  document.getElementById('zone-next').addEventListener('click', function () {{ goToPage(currentPage + 1); }});

  document.getElementById('jump-form').addEventListener('submit', function (e) {{
    e.preventDefault();
    goToPage(inputEl.value);
  }});
  inputEl.addEventListener('change', function () {{
    goToPage(inputEl.value);
  }});
  scrubberEl.addEventListener('input', function () {{
    captionEl.textContent = 'Page ' + scrubberEl.value + ' of ' + TOTAL;
  }});
  scrubberEl.addEventListener('change', function () {{
    goToPage(scrubberEl.value);
  }});

  btnThumbs.addEventListener('click', toggleThumbs);
  btnCloseThumbs.addEventListener('click', closeThumbs);
  overlayEl.addEventListener('click', function (e) {{
    if (e.target === overlayEl) closeThumbs();
  }});

  modeSelect.addEventListener('change', function () {{
    currentMode = modeSelect.value;
    goToPage(currentPage, {{ keepScroll: true }});
  }});

  fitSelect.addEventListener('change', function () {{
    document.body.classList.remove('fit-height', 'fit-original');
    if (fitSelect.value === 'height') document.body.classList.add('fit-height');
    else if (fitSelect.value === 'original') document.body.classList.add('fit-original');
  }});

  window.addEventListener('popstate', function () {{
    goToPage(readStateFromUrl(), {{ skipUrl: true }});
  }});
  window.addEventListener('hashchange', function () {{
    goToPage(readStateFromUrl(), {{ skipUrl: true }});
  }});

  window.addEventListener('keydown', function (e) {{
    if (e.target === inputEl || e.target === modeSelect || e.target === fitSelect) return;
    if (e.key === 'Escape' && overlayEl.classList.contains('open')) {{
      closeThumbs();
      return;
    }}
    if (e.key === 'g' || e.key === 'G') {{
      e.preventDefault();
      toggleThumbs();
      return;
    }}
    if (overlayEl.classList.contains('open')) return;
    if (e.key === 'ArrowRight' || e.key === 'j' || e.key === 'PageDown') {{
      e.preventDefault();
      goToPage(currentPage + 1);
    }} else if (e.key === 'ArrowLeft' || e.key === 'k' || e.key === 'PageUp') {{
      e.preventDefault();
      goToPage(currentPage - 1);
    }} else if (e.key === 'Home') {{
      e.preventDefault();
      goToPage(1);
    }} else if (e.key === 'End') {{
      e.preventDefault();
      goToPage(TOTAL);
    }} else if (e.key === 'f' || e.key === 'F') {{
      e.preventDefault();
      var order = ['width', 'height', 'original'];
      var nextFit = order[(order.indexOf(fitSelect.value) + 1) % order.length];
      fitSelect.value = nextFit;
      fitSelect.dispatchEvent(new Event('change'));
    }}
  }});

  goToPage(readStateFromUrl(), {{ replaceUrl: true }});
}})();
</script>
</body>
</html>
"""


def main() -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--metadata", type=Path, default=Path("metadata.json"), help="Path to metadata.json")
    p.add_argument("--only", type=str, default=None, help="Only generate reader for matching directory slug")
    args = p.parse_args()

    meta_path = args.metadata.resolve()
    base_dir = meta_path.parent
    entries = json.loads(meta_path.read_text(encoding="utf-8"))
    if args.only:
        entries = [e for e in entries if args.only in e["directory"] or args.only in e["source"]]

    written = 0
    for entry in entries:
        out_dir = base_dir / entry["directory"]
        out_dir.mkdir(parents=True, exist_ok=True)
        pages = get_page_count(entry, base_dir)
        reader_html = build_reader_html(entry, pages)
        (out_dir / "index.html").write_text(reader_html, encoding="utf-8")
        written += 1

    print(f"Generated index.html in {written} director{'y' if written == 1 else 'ies'}.")
    return 0


if __name__ == "__main__":
    sys.exit(main())