File size: 32,406 Bytes
cf5bcd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import csv
import html
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Set, Tuple

from capt_validation_schema import ensure_directory


NOT_ON_LIST_RANK = 16
CHART_WIDTH = 1120
CHART_HEIGHT = 420
CHART_LEFT = 68
CHART_TOP = 28
CHART_RIGHT = 24
CHART_BOTTOM = 68
RANK_MAX = 15
LINE_COLORS = [
    "#163a5f",
    "#9d2c00",
    "#46734b",
    "#6b4f9f",
    "#b26a00",
    "#3d6f8e",
    "#8d3d57",
    "#557a95",
    "#6a7f3a",
    "#9a5d56",
]
SVG_STYLE_BLOCK = """

    <style>

        .chart-bg { fill: #fffdfa; }

        .grid { stroke: #d9d3c9; stroke-width: 1; stroke-dasharray: 3 5; }

        .date-grid { stroke: #ebe5da; stroke-width: 1; }

        .axis-line { stroke: #98918a; stroke-width: 1.2; }

        .axis-label { fill: #615a52; font-size: 12px; font-family: system-ui, sans-serif; }

        .date-label { text-anchor: middle; }

        .rank-label { text-anchor: end; }

        .axis-title { fill: #36312d; font-size: 15px; font-family: system-ui, sans-serif; }

        .band-label { fill: #f3eee7; font-size: 16px; font-family: system-ui, sans-serif; font-weight: 600; text-anchor: middle; }

        .not-on-list-band { fill: #6b6865; opacity: 0.96; }

        .series-line { fill: none; stroke-width: 3.6; stroke-linecap: round; stroke-linejoin: round; opacity: 0.95; }

    </style>

"""


@dataclass
class AmazonCandidate:
    title: str
    author: str


@dataclass
class NytSeries:
    title: str
    author: str
    list_slug: str
    list_title: str
    ranks_by_date: Dict[str, int]
    page_dates: Set[str]
    best_rank: int
    amazon_title: str = ""
    amazon_match_score: float = 0.0

    @property
    def observed_weeks(self) -> int:
        return len(self.page_dates)

    @property
    def label(self) -> str:
        return f"{self.title} ({self.list_title})"


def read_rows(path: str | Path) -> List[Dict[str, str]]:
    with Path(path).open("r", newline="", encoding="utf-8") as handle:
        return list(csv.DictReader(handle))


def parse_int(value: str) -> Optional[int]:
    text = str(value).strip().replace(",", "")
    if not text:
        return None
    try:
        return int(float(text))
    except ValueError:
        return None


def normalize_text(value: str) -> str:
    text = str(value or "").lower().replace("&", " and ")
    text = re.sub(r"\bby\b", " ", text)
    text = re.sub(r"[^a-z0-9]+", " ", text)
    return " ".join(text.split())


def title_variants(title: str) -> Set[str]:
    normalized = normalize_text(title)
    variants = {normalized}
    for separator in (":", "(", "["):
        head = title.split(separator, 1)[0]
        normalized_head = normalize_text(head)
        if len(normalized_head.split()) >= 2:
            variants.add(normalized_head)
    return {variant for variant in variants if variant}


def author_tokens(author: str) -> Set[str]:
    normalized = normalize_text(author)
    return {token for token in normalized.split() if len(token) >= 3 and token not in {"with", "and", "the"}}


def overlap_ratio(left: Set[str], right: Set[str]) -> float:
    if not left or not right:
        return 0.0
    return len(left & right) / min(len(left), len(right))


def match_score(nyt_title: str, nyt_author: str, amazon_title: str, amazon_author: str) -> float:
    nyt_variants = title_variants(nyt_title)
    amazon_variants = title_variants(amazon_title)
    if nyt_variants & amazon_variants:
        return 1.0

    nyt_full = max(nyt_variants, key=len, default="")
    amazon_full = max(amazon_variants, key=len, default="")
    if not nyt_full or not amazon_full:
        return 0.0

    sequence_ratio = similarity_ratio(nyt_full, amazon_full)
    nyt_tokens = set(nyt_full.split())
    amazon_tokens = set(amazon_full.split())
    token_ratio = overlap_ratio(nyt_tokens, amazon_tokens)
    author_overlap = bool(author_tokens(nyt_author) & author_tokens(amazon_author))

    if nyt_full in amazon_full and len(nyt_tokens) >= 2:
        return 0.94
    if amazon_full in nyt_full and len(amazon_tokens) >= 2:
        return 0.94
    if token_ratio == 1.0 and sequence_ratio >= 0.7:
        return 0.9
    if author_overlap and sequence_ratio >= 0.72 and token_ratio >= 0.5:
        return 0.84
    if sequence_ratio >= 0.86 and token_ratio >= 0.6:
        return 0.8
    return 0.0


def similarity_ratio(left: str, right: str) -> float:
    if not left or not right:
        return 0.0
    if left == right:
        return 1.0
    left_bigrams = {left[index:index + 2] for index in range(max(len(left) - 1, 1))}
    right_bigrams = {right[index:index + 2] for index in range(max(len(right) - 1, 1))}
    if not left_bigrams or not right_bigrams:
        return 0.0
    return (2 * len(left_bigrams & right_bigrams)) / (len(left_bigrams) + len(right_bigrams))


def load_nyt_series(paths: Sequence[str | Path]) -> Tuple[List[NytSeries], List[str]]:
    dedupe_keys: Set[Tuple[str, str, str, str, str]] = set()
    by_series: Dict[Tuple[str, str], NytSeries] = {}
    all_dates: Set[str] = set()

    for path in paths:
        for row in read_rows(path):
            page_date = str(row.get("page_date", "")).strip()
            title = str(row.get("title", "")).strip()
            list_slug = str(row.get("list_slug", "")).strip()
            rank = parse_int(row.get("rank", ""))
            if not page_date or not title or not list_slug or rank is None:
                continue

            dedupe_key = (
                page_date,
                list_slug,
                str(row.get("isbn13", "")).strip(),
                title,
                str(rank),
            )
            if dedupe_key in dedupe_keys:
                continue
            dedupe_keys.add(dedupe_key)
            all_dates.add(page_date)

            series_key = (title, list_slug)
            if series_key not in by_series:
                by_series[series_key] = NytSeries(
                    title=title,
                    author=str(row.get("author", "")).strip(),
                    list_slug=list_slug,
                    list_title=str(row.get("list_title", list_slug)).strip() or list_slug,
                    ranks_by_date={},
                    page_dates=set(),
                    best_rank=rank,
                )

            series = by_series[series_key]
            existing_rank = series.ranks_by_date.get(page_date)
            if existing_rank is None or rank < existing_rank:
                series.ranks_by_date[page_date] = rank
            series.page_dates.add(page_date)
            series.best_rank = min(series.best_rank, rank)

    sorted_dates = sorted(all_dates)
    sorted_series = sorted(by_series.values(), key=lambda item: (-item.observed_weeks, item.best_rank, item.title, item.list_slug))
    return sorted_series, sorted_dates


def load_amazon_candidates(path: str | Path) -> List[AmazonCandidate]:
    deduped: Dict[Tuple[str, str], AmazonCandidate] = {}
    for row in read_rows(path):
        title = str(row.get("title", "")).strip()
        author = str(row.get("author", "")).strip()
        if not title:
            continue
        key = (normalize_text(title), normalize_text(author))
        deduped[key] = AmazonCandidate(title=title, author=author)
    return list(deduped.values())


def classify_series(series_list: Sequence[NytSeries], amazon_candidates: Sequence[AmazonCandidate]) -> Tuple[List[NytSeries], List[NytSeries]]:
    matched: List[NytSeries] = []
    unmatched: List[NytSeries] = []
    for series in series_list:
        best_score = 0.0
        best_candidate: Optional[AmazonCandidate] = None
        for candidate in amazon_candidates:
            score = match_score(series.title, series.author, candidate.title, candidate.author)
            if score > best_score:
                best_score = score
                best_candidate = candidate
        if best_candidate and best_score >= 0.8:
            series.amazon_title = best_candidate.title
            series.amazon_match_score = best_score
            matched.append(series)
        else:
            unmatched.append(series)
    return matched, unmatched


def series_values(series: NytSeries, page_dates: Sequence[str]) -> List[int]:
    return [series.ranks_by_date.get(page_date, NOT_ON_LIST_RANK) for page_date in page_dates]


def rank_to_y(rank_value: int) -> float:
    inner_height = CHART_HEIGHT - CHART_TOP - CHART_BOTTOM
    y_min = CHART_TOP
    y_max = CHART_HEIGHT - CHART_BOTTOM
    return y_min + ((rank_value - 1) / (NOT_ON_LIST_RANK - 1)) * inner_height


def step_path(values: Sequence[int]) -> str:
    if not values:
        return ""
    inner_width = CHART_WIDTH - CHART_LEFT - CHART_RIGHT
    x_step = inner_width / max(len(values) - 1, 1)
    commands: List[str] = []
    last_x = CHART_LEFT
    last_y = rank_to_y(values[0])
    commands.append(f"M {last_x:.1f} {last_y:.1f}")
    for index, value in enumerate(values[1:], start=1):
        x_value = CHART_LEFT + (index * x_step)
        current_y = rank_to_y(value)
        commands.append(f"L {x_value:.1f} {last_y:.1f}")
        commands.append(f"L {x_value:.1f} {current_y:.1f}")
        last_x = x_value
        last_y = current_y
    return " ".join(commands)


def build_chart_svg(series_list: Sequence[NytSeries], page_dates: Sequence[str]) -> str:
    chart_bottom_y = CHART_HEIGHT - CHART_BOTTOM
    band_top = rank_to_y(RANK_MAX + 0.2)
    grid_lines = []
    for rank in range(1, RANK_MAX + 1):
        y_value = rank_to_y(rank)
        grid_lines.append(
            f'<line x1="{CHART_LEFT}" y1="{y_value:.1f}" x2="{CHART_WIDTH - CHART_RIGHT}" y2="{y_value:.1f}" class="grid" />'
            f'<text x="{CHART_LEFT - 12}" y="{y_value + 4:.1f}" class="axis-label rank-label">{rank}</text>'
        )

    inner_width = CHART_WIDTH - CHART_LEFT - CHART_RIGHT
    x_step = inner_width / max(len(page_dates) - 1, 1)
    date_labels = []
    for index, page_date in enumerate(page_dates):
        x_value = CHART_LEFT + (index * x_step)
        date_labels.append(f'<line x1="{x_value:.1f}" y1="{CHART_TOP}" x2="{x_value:.1f}" y2="{chart_bottom_y}" class="date-grid" />')
        date_labels.append(f'<text x="{x_value:.1f}" y="{CHART_HEIGHT - 20}" class="axis-label date-label">{html.escape(page_date)}</text>')

    paths = []
    for index, series in enumerate(series_list):
        values = series_values(series, page_dates)
        final_x = CHART_LEFT + ((len(page_dates) - 1) * x_step if page_dates else 0)
        final_y = rank_to_y(values[-1]) if values else rank_to_y(NOT_ON_LIST_RANK)
        color = LINE_COLORS[index % len(LINE_COLORS)]
        paths.append(
            f'<path d="{step_path(values)}" class="series-line" style="stroke:{color}" />'
            f'<circle cx="{final_x:.1f}" cy="{final_y:.1f}" r="4" style="fill:{color}" />'
        )

    return f'''

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {CHART_WIDTH} {CHART_HEIGHT}" class="trajectory-chart" role="img" aria-label="NYT rank trajectory chart">

      {SVG_STYLE_BLOCK}

      <rect x="0" y="0" width="{CHART_WIDTH}" height="{CHART_HEIGHT}" class="chart-bg" />

      <rect x="{CHART_LEFT}" y="{band_top:.1f}" width="{CHART_WIDTH - CHART_LEFT - CHART_RIGHT}" height="{chart_bottom_y - band_top:.1f}" class="not-on-list-band" />

      {''.join(grid_lines)}

      {''.join(date_labels)}

      <line x1="{CHART_LEFT}" y1="{chart_bottom_y}" x2="{CHART_WIDTH - CHART_RIGHT}" y2="{chart_bottom_y}" class="axis-line" />

      <text x="20" y="{(CHART_TOP + chart_bottom_y) / 2:.1f}" class="axis-title axis-title-y" transform="rotate(-90, 20, {(CHART_TOP + chart_bottom_y) / 2:.1f})">Position on NYT list</text>

      <text x="{CHART_WIDTH / 2:.1f}" y="{band_top + 28:.1f}" class="band-label">Not on list</text>

      {''.join(paths)}

    </svg>

    '''


def render_series_table(series_list: Sequence[NytSeries], show_amazon_column: bool) -> str:
    header_cells = ["Book", "NYT list", "Observed weeks", "Best rank"]
    if show_amazon_column:
        header_cells.extend(["Matched Amazon title", "Match score"])

    rows = []
    for series in series_list:
        cells = [
            html.escape(series.title),
            html.escape(series.list_title),
            str(series.observed_weeks),
            str(series.best_rank),
        ]
        if show_amazon_column:
            cells.extend([
                html.escape(series.amazon_title or "Not observed"),
                f"{series.amazon_match_score:.2f}" if series.amazon_match_score else "",
            ])
        rows.append("<tr>" + "".join(f"<td>{cell}</td>" for cell in cells) + "</tr>")

    return (
        "<table><thead><tr>"
        + "".join(f"<th>{html.escape(cell)}</th>" for cell in header_cells)
        + "</tr></thead><tbody>"
        + "".join(rows)
        + "</tbody></table>"
    )


def render_section(title: str, description: str, series_list: Sequence[NytSeries], page_dates: Sequence[str], show_amazon_column: bool) -> str:
    if not series_list:
        return f"<section class=\"panel\"><h2>{html.escape(title)}</h2><p>{html.escape(description)}</p><p>No series available with the current inputs.</p></section>"
    return f'''

    <section class="panel">

      <div class="panel-header">

        <div>

          <h2>{html.escape(title)}</h2>

          <p>{html.escape(description)}</p>

        </div>

        <div class="panel-metric">

          <span class="metric-value">{len(series_list)}</span>

          <span class="metric-label">charted titles</span>

        </div>

      </div>

      {build_chart_svg(series_list, page_dates)}

      {render_series_table(series_list, show_amazon_column=show_amazon_column)}

    </section>

    '''


def render_book_card(series: NytSeries, page_dates: Sequence[str], card_title: str, include_amazon_note: bool) -> str:
    values = series_values(series, page_dates)
    visible_dates = [page_date for page_date in page_dates if page_date in series.ranks_by_date]
    summary_bits = [
        f"Observed weeks: {series.observed_weeks}",
        f"Best NYT rank: {series.best_rank}",
        f"List: {series.list_title}",
    ]
    if include_amazon_note and series.amazon_title:
        summary_bits.append(f"Amazon match: {series.amazon_title}")

    return f'''

    <article class="book-card">

      <div class="book-card-header">

        <h3>{html.escape(card_title)}</h3>

        <p>{html.escape(' | '.join(summary_bits))}</p>

      </div>

      {build_chart_svg([series], page_dates)}

      <p class="book-card-dates">Observed NYT page dates: {html.escape(', '.join(visible_dates) if visible_dates else 'None')}</p>

      <div class="book-card-rank-row">{''.join(f'<span class="rank-pill">{html.escape(page_date)}: {value if value < NOT_ON_LIST_RANK else "not on list"}</span>' for page_date, value in zip(page_dates, values))}</div>

    </article>

    '''


def render_book_card_section(title: str, description: str, series_list: Sequence[NytSeries], page_dates: Sequence[str], include_amazon_note: bool) -> str:
    if not series_list:
        return ""
    cards = []
    for series in series_list:
        cards.append(
            render_book_card(
                series,
                page_dates,
                card_title=f"How {series.title} ranked over time",
                include_amazon_note=include_amazon_note,
            )
        )
    return f'''

    <section class="panel panel-cards">

      <div class="panel-header">

        <div>

          <h2>{html.escape(title)}</h2>

          <p>{html.escape(description)}</p>

        </div>

      </div>

      <div class="book-card-list">

        {''.join(cards)}

      </div>

    </section>

    '''


def build_html(

    matched: Sequence[NytSeries],

    unmatched: Sequence[NytSeries],

    page_dates: Sequence[str],

    top_matched: int,

    top_unmatched: int,

    include_matched: bool = True,

    include_unmatched: bool = True,

    include_book_cards: bool = True,

    page_title: str = "NYT vs Amazon Comparison Charts",

    lead_text: str = "",

) -> str:
    matched_series = list(matched)[:top_matched] if include_matched else []
    unmatched_series = list(unmatched)[:top_unmatched] if include_unmatched else []
    lead = lead_text or (
        "These comparison charts use the NYT public archive and weekly snapshots you already collected, then split the trajectories into two groups: books also observed in the tracked Amazon bestseller categories and books not observed there. A missing NYT week is shown in the gray band at the bottom as ‘Not on list,’ matching the visual logic of the reference chart."
    )
    return f'''<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

    <title>{html.escape(page_title)}</title>

  <style>

    :root {{

      --paper: #f6f0e6;

      --panel: #fffdf9;

      --ink: #171717;

      --muted: #645f58;

      --line: #d7d0c4;

      --grid: #d9d3c9;

      --band: #6b6865;

      --band-text: #f3eee7;

      --shadow: rgba(34, 28, 19, 0.08);

    }}

    * {{ box-sizing: border-box; }}

    body {{ margin: 0; font-family: Georgia, "Times New Roman", serif; background: radial-gradient(circle at top, #fcfaf5 0%, var(--paper) 62%, #ece4d7 100%); color: var(--ink); }}

    main {{ max-width: 1240px; margin: 0 auto; padding: 32px 24px 48px; }}

    h1 {{ font-size: 48px; line-height: 0.95; margin: 0 0 10px; letter-spacing: -0.04em; }}

    .lead {{ max-width: 860px; color: var(--muted); font-size: 17px; line-height: 1.55; margin-bottom: 24px; }}

    .panel {{ background: var(--panel); border: 1px solid var(--line); border-radius: 22px; padding: 22px; margin-bottom: 22px; box-shadow: 0 18px 45px var(--shadow); }}

    .panel-header {{ display: flex; justify-content: space-between; gap: 18px; align-items: end; margin-bottom: 14px; }}

    h2 {{ margin: 0 0 6px; font-size: 26px; line-height: 1.05; }}

    p {{ margin: 0; color: var(--muted); line-height: 1.5; }}

    .panel-metric {{ min-width: 120px; padding: 12px 14px; border-radius: 16px; background: #f0eadf; text-align: center; }}

    .metric-value {{ display: block; font-size: 28px; font-weight: bold; color: #163a5f; }}

    .metric-label {{ display: block; color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: 0.08em; }}

    .trajectory-chart {{ width: 100%; height: auto; display: block; border-radius: 16px; overflow: hidden; margin: 8px 0 18px; }}

    .chart-bg {{ fill: #fffdfa; }}

    .grid {{ stroke: var(--grid); stroke-width: 1; stroke-dasharray: 3 5; }}

    .date-grid {{ stroke: #ebe5da; stroke-width: 1; }}

    .axis-line {{ stroke: #98918a; stroke-width: 1.2; }}

    .axis-label {{ fill: #615a52; font-size: 12px; font-family: system-ui, sans-serif; }}

    .date-label {{ text-anchor: middle; }}

    .rank-label {{ text-anchor: end; }}

    .axis-title {{ fill: #36312d; font-size: 15px; font-family: system-ui, sans-serif; }}

    .band-label {{ fill: var(--band-text); font-size: 16px; font-family: system-ui, sans-serif; font-weight: 600; text-anchor: middle; }}

    .not-on-list-band {{ fill: var(--band); opacity: 0.96; }}

    .series-line {{ fill: none; stroke-width: 3.6; stroke-linecap: round; stroke-linejoin: round; opacity: 0.95; }}

    table {{ width: 100%; border-collapse: collapse; font-family: system-ui, sans-serif; font-size: 14px; }}

    th, td {{ text-align: left; padding: 10px 12px; border-top: 1px solid #ece5d9; vertical-align: top; }}

    th {{ font-size: 12px; color: #6f675f; text-transform: uppercase; letter-spacing: 0.05em; }}

        .panel-cards {{ padding-top: 18px; }}

        .book-card-list {{ display: grid; grid-template-columns: 1fr; gap: 18px; }}

        .book-card {{ background: #fcfaf4; border: 1px solid #e5ddcf; border-radius: 18px; padding: 18px; }}

        .book-card-header h3 {{ margin: 0 0 6px; font-size: 24px; line-height: 1.02; letter-spacing: -0.03em; }}

        .book-card-header p {{ margin-bottom: 10px; }}

        .book-card-dates {{ font-family: system-ui, sans-serif; font-size: 13px; color: #6b645d; margin-top: -4px; }}

        .book-card-rank-row {{ display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }}

        .rank-pill {{ font-family: system-ui, sans-serif; font-size: 12px; color: #48423c; background: #efe7db; border-radius: 999px; padding: 6px 10px; }}

    @media (max-width: 920px) {{

      h1 {{ font-size: 36px; }}

      .panel-header {{ flex-direction: column; align-items: start; }}

      main {{ padding: 22px 14px 36px; }}

    }}

  </style>

</head>

<body>

  <main>

    <h1>{html.escape(page_title)}</h1>

    <p class="lead">{html.escape(lead)}</p>

    {render_section(

        title="NYT books also observed in tracked Amazon categories",

        description="Matched conservatively by normalized title, subtitle trimming, and author-aware fuzzy checks. These are the clearest cross-surface overlaps in the current tracked categories.",

        series_list=matched_series,

        page_dates=page_dates,

        show_amazon_column=True,

    ) if include_matched else ''}

    {render_section(

        title="NYT books not observed in tracked Amazon categories",

        description="These books appeared in the NYT inputs but were not found in the Amazon public history you are currently tracking. This is category-limited absence, not global Amazon absence.",

        series_list=unmatched_series,

        page_dates=page_dates,

        show_amazon_column=False,

    ) if include_unmatched else ''}

    {render_book_card_section(

        title="Standalone per-book charts for NYT books also observed on Amazon",

        description="Each card isolates one title so you can inspect the exact weekly NYT trajectory without line overlap.",

        series_list=matched_series,

        page_dates=page_dates,

        include_amazon_note=True,

    ) if include_book_cards and include_matched else ''}

    {render_book_card_section(

        title="Standalone per-book charts for NYT books not observed in tracked Amazon categories",

        description="These cards show the same NYT trajectories for the unmatched group, one book at a time.",

        series_list=unmatched_series,

        page_dates=page_dates,

        include_amazon_note=False,

    ) if include_book_cards and include_unmatched else ''}

  </main>

</body>

</html>

'''


def sibling_output_path(output_path: Path, suffix: str) -> Path:
    return output_path.with_name(f"{output_path.stem}_{suffix}{output_path.suffix}")


def sibling_output_dir(output_path: Path, suffix: str) -> Path:
    return output_path.with_name(f"{output_path.stem}_{suffix}")


def write_html(path: Path, content: str) -> Path:
    ensure_directory(path.parent)
    path.write_text(content, encoding="utf-8")
    return path


def write_text(path: Path, content: str) -> Path:
    ensure_directory(path.parent)
    path.write_text(content, encoding="utf-8")
    return path


def slugify(value: str) -> str:
    slug = normalize_text(value).replace(" ", "_")
    return slug[:80] or "untitled"


def choose_paper_series(series_list: Sequence[NytSeries], explicit_titles: Sequence[str], count: int) -> List[NytSeries]:
    if explicit_titles:
        desired = {normalize_text(title) for title in explicit_titles}
        selected = [series for series in series_list if normalize_text(series.title) in desired]
        return selected[:count] if count > 0 else selected
    return list(series_list)[:count]


def export_svg_figures(

    figure_dir: Path,

    matched_series: Sequence[NytSeries],

    unmatched_series: Sequence[NytSeries],

    page_dates: Sequence[str],

) -> List[Path]:
    svg_paths: List[Path] = []
    panels_dir = figure_dir / "panels"
    matched_books_dir = figure_dir / "matched_books"
    unmatched_books_dir = figure_dir / "unmatched_books"

    panel_specs = [
        (panels_dir / "matched_panel.svg", matched_series),
        (panels_dir / "unmatched_panel.svg", unmatched_series),
    ]
    for path, series_list in panel_specs:
        if not series_list:
            continue
        svg_paths.append(write_text(path, build_chart_svg(series_list, page_dates)))

    for index, series in enumerate(matched_series, start=1):
        path = matched_books_dir / f"{index:02d}_{slugify(series.title)}.svg"
        svg_paths.append(write_text(path, build_chart_svg([series], page_dates)))

    for index, series in enumerate(unmatched_series, start=1):
        path = unmatched_books_dir / f"{index:02d}_{slugify(series.title)}.svg"
        svg_paths.append(write_text(path, build_chart_svg([series], page_dates)))

    return svg_paths


def export_paper_ready_figures(

    figure_dir: Path,

    paper_series: Sequence[NytSeries],

    page_dates: Sequence[str],

) -> List[Path]:
    svg_paths: List[Path] = []
    panels_dir = figure_dir / "panels"
    matched_books_dir = figure_dir / "matched_books"
    if paper_series:
        svg_paths.append(write_text(panels_dir / "paper_matched_panel.svg", build_chart_svg(paper_series, page_dates)))
    for index, series in enumerate(paper_series, start=1):
        path = matched_books_dir / f"{index:02d}_{slugify(series.title)}.svg"
        svg_paths.append(write_text(path, build_chart_svg([series], page_dates)))
    return svg_paths


def export_png_figures(svg_paths: Sequence[Path]) -> List[Path]:
    from playwright.sync_api import sync_playwright

    png_paths: List[Path] = []
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch()
        page = browser.new_page(viewport={"width": CHART_WIDTH + 32, "height": CHART_HEIGHT + 32}, device_scale_factor=2)
        for svg_path in svg_paths:
            page.goto(svg_path.resolve().as_uri())
            page.locator("svg").first.screenshot(path=str(svg_path.with_suffix(".png")))
            png_paths.append(svg_path.with_suffix(".png"))
        browser.close()
    return png_paths


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Render NYT-style comparison charts for NYT titles with and without Amazon-category overlap.")
    parser.add_argument(
        "--nyt-inputs",
        nargs="+",
        default=[
            "validation_data/nyt_public_hardcover_nonfiction_archive_2026Q2.csv",
            "validation_data/nyt_public_weekly_history.csv",
        ],
        help="NYT public history CSV inputs.",
    )
    parser.add_argument("--amazon-input", default="validation_data/amazon_public_history.csv", help="Amazon public history CSV input.")
    parser.add_argument("--output", default="validation_results/nyt_amazon_comparison_charts.html", help="Output HTML path.")
    parser.add_argument("--matched-output", default="", help="Optional matched-only HTML path. Defaults beside --output.")
    parser.add_argument("--unmatched-output", default="", help="Optional unmatched-only HTML path. Defaults beside --output.")
    parser.add_argument("--figures-dir", default="", help="Optional directory for standalone SVG and PNG chart exports. Defaults beside --output.")
    parser.add_argument("--paper-html-output", default="", help="Optional paper-ready matched-subset HTML path. Defaults beside --output.")
    parser.add_argument("--paper-figures-dir", default="", help="Optional paper-ready SVG and PNG figure directory. Defaults beside --output.")
    parser.add_argument("--paper-top-matched", type=int, default=6, help="Number of matched titles to include in the paper-ready subset export.")
    parser.add_argument("--paper-titles", nargs="*", default=[], help="Optional explicit matched NYT titles to use for the paper-ready subset export.")
    parser.add_argument("--top-matched", type=int, default=12, help="Number of matched NYT series to include.")
    parser.add_argument("--top-unmatched", type=int, default=12, help="Number of unmatched NYT series to include.")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    nyt_series, page_dates = load_nyt_series(args.nyt_inputs)
    amazon_candidates = load_amazon_candidates(args.amazon_input)
    matched, unmatched = classify_series(nyt_series, amazon_candidates)

    output_path = Path(args.output)
    matched_output_path = Path(args.matched_output) if args.matched_output else sibling_output_path(output_path, "matched_only")
    unmatched_output_path = Path(args.unmatched_output) if args.unmatched_output else sibling_output_path(output_path, "unmatched_only")
    figures_dir = Path(args.figures_dir) if args.figures_dir else sibling_output_dir(output_path, "figures")
    paper_html_output_path = Path(args.paper_html_output) if args.paper_html_output else sibling_output_path(output_path, "paper_ready")
    paper_figures_dir = Path(args.paper_figures_dir) if args.paper_figures_dir else sibling_output_dir(output_path, "paper_ready_figures")

    matched_series = list(matched)[: args.top_matched]
    unmatched_series = list(unmatched)[: args.top_unmatched]
    paper_series = choose_paper_series(matched_series, args.paper_titles, args.paper_top_matched)

    content = build_html(
        matched_series,
        unmatched_series,
        page_dates,
        top_matched=args.top_matched,
        top_unmatched=args.top_unmatched,
        page_title="NYT Trajectories vs Amazon Presence",
    )
    matched_content = build_html(
        matched_series,
        unmatched_series,
        page_dates,
        top_matched=args.top_matched,
        top_unmatched=args.top_unmatched,
        include_unmatched=False,
        page_title="NYT Titles Also Observed In Tracked Amazon Categories",
        lead_text="This page isolates the NYT titles that also appear in the tracked Amazon bestseller categories, shown first as a multi-line comparison and then as standalone per-book charts.",
    )
    unmatched_content = build_html(
        matched_series,
        unmatched_series,
        page_dates,
        top_matched=args.top_matched,
        top_unmatched=args.top_unmatched,
        include_matched=False,
        page_title="NYT Titles Not Observed In Tracked Amazon Categories",
        lead_text="This page isolates NYT titles that were not observed in the currently tracked Amazon bestseller categories, shown as a multi-line comparison and standalone per-book charts.",
    )
    paper_content = build_html(
        paper_series,
        [],
        page_dates,
        top_matched=len(paper_series),
        top_unmatched=0,
        include_unmatched=False,
        page_title="Paper-Ready Matched NYT Trajectories",
        lead_text="This page narrows the export to a smaller matched subset intended for paper figures and faster review.",
    )

    write_html(output_path, content)
    write_html(matched_output_path, matched_content)
    write_html(unmatched_output_path, unmatched_content)
    write_html(paper_html_output_path, paper_content)
    svg_paths = export_svg_figures(figures_dir, matched_series, unmatched_series, page_dates)
    png_paths = export_png_figures(svg_paths)
    paper_svg_paths = export_paper_ready_figures(paper_figures_dir, paper_series, page_dates)
    paper_png_paths = export_png_figures(paper_svg_paths)
    print(
        f"Wrote NYT/Amazon comparison charts to {output_path}, {matched_output_path}, and {unmatched_output_path} "
        f"plus paper-ready HTML {paper_html_output_path}, {len(svg_paths)} SVG files and {len(png_paths)} PNG files in {figures_dir}, "
        f"and {len(paper_svg_paths)} paper-ready SVG files and {len(paper_png_paths)} paper-ready PNG files in {paper_figures_dir} "
        f"({len(matched)} matched series, {len(unmatched)} unmatched series, {len(page_dates)} page dates)"
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())