a
File size: 82,567 Bytes
d41428b
 
0fcb5c2
 
be73249
d41428b
 
0fcb5c2
 
0c21886
5283e2c
0fcb5c2
 
 
bc0c819
 
 
a839913
7f36b83
f0e0245
 
a839913
f0e0245
41b3b51
a839913
7f36b83
0fcb5c2
0c21886
4612e64
 
 
65c3047
4612e64
 
 
0c21886
fbc8659
0b7bef2
b8d53ae
bc616c9
c165e10
b8d53ae
6db0b76
 
5283e2c
 
d41428b
2774836
 
 
 
 
 
b8d53ae
 
4256175
 
4612e64
 
0c21886
 
4612e64
 
 
 
 
 
0c21886
fbc8659
f0e0245
 
7f36b83
c165e10
8762688
6db0b76
5283e2c
d41428b
2774836
 
4b9bf53
2774836
4256175
4612e64
fbc8659
 
 
4256175
 
 
fbc8659
 
2774836
0c21886
fbc8659
2774836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc8659
 
 
 
2774836
0fcb5c2
 
 
 
 
d41428b
 
 
 
 
 
 
 
 
 
54e4063
 
 
 
5283e2c
54e4063
 
 
 
bc0c819
 
 
 
 
 
 
 
 
54e4063
 
 
41b3b51
70cc48f
 
 
 
 
 
 
2774836
 
 
41b3b51
2774836
f0e0245
2774836
f0e0245
 
8762688
41b3b51
70cc48f
41b3b51
70cc48f
f0e0245
58dc9a1
8762688
 
 
 
41b3b51
 
8762688
 
70cc48f
8762688
70cc48f
8762688
 
 
f0e0245
 
 
 
 
8762688
 
 
f0e0245
8762688
f0e0245
 
2774836
f0e0245
 
 
41b3b51
70cc48f
 
 
 
 
2774836
 
 
 
41b3b51
2774836
8762688
 
 
2774836
8762688
 
41b3b51
70cc48f
41b3b51
70cc48f
8762688
58dc9a1
8762688
 
 
 
41b3b51
 
8762688
 
 
2774836
 
8762688
 
70cc48f
8762688
70cc48f
8762688
 
 
 
 
 
 
 
2774836
8762688
 
 
 
be73249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5283e2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c63b398
54e4063
 
 
 
0b7bef2
b8d53ae
bc616c9
c165e10
b8d53ae
2774836
 
b8d53ae
6db0b76
5283e2c
54e4063
9052d8e
 
6387a43
be73249
fbc8659
5283e2c
 
 
0fcb5c2
 
b8d53ae
c165e10
b8d53ae
c165e10
f0e0245
 
6db0b76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8762688
6db0b76
0fcb5c2
 
 
 
 
 
 
 
 
 
 
 
 
6db0b76
 
 
 
 
 
 
 
 
 
 
 
70cc48f
6db0b76
70cc48f
6db0b76
 
 
0d4041b
 
 
 
 
 
 
 
 
0786ba9
0d4041b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5bc115
 
 
 
 
 
 
 
 
b8d53ae
bc616c9
c165e10
2774836
 
a5bc115
9052d8e
 
6387a43
be73249
a5bc115
2774836
 
a5bc115
2774836
a5bc115
 
 
 
 
 
0d4041b
a5bc115
 
 
 
 
 
 
 
 
 
 
 
0d4041b
 
 
2774836
 
 
 
b8d53ae
 
 
f0e0245
c165e10
f0e0245
 
7f36b83
f0e0245
7f36b83
2774836
f0e0245
7f36b83
 
 
 
2774836
7f36b83
 
 
 
0d4041b
 
f0e0245
 
 
 
 
 
0d4041b
7f36b83
 
2774836
7f36b83
2774836
7f36b83
 
 
 
 
2774836
7f36b83
f0e0245
 
 
 
 
 
 
 
 
 
 
 
 
b8d53ae
 
c165e10
f0e0245
 
 
 
2774836
f0e0245
 
 
 
 
 
2774836
f0e0245
 
 
 
0d4041b
 
f0e0245
 
 
 
 
 
 
 
0d4041b
f0e0245
 
2774836
f0e0245
2774836
f0e0245
 
 
 
2774836
f0e0245
 
a5bc115
f0e0245
 
 
 
 
 
 
 
 
 
 
 
a5bc115
 
 
 
 
 
b8d53ae
bc616c9
c165e10
d41428b
2774836
 
a5bc115
d41428b
 
 
 
 
 
 
 
c165e10
a5bc115
d41428b
 
 
 
a5bc115
 
 
 
 
 
 
41b3b51
b8d53ae
bc616c9
c165e10
41b3b51
2774836
 
41b3b51
70cc48f
 
a5bc115
9052d8e
 
6387a43
be73249
a5bc115
2774836
 
a5bc115
2774836
a5bc115
 
 
 
 
 
 
b8d53ae
c165e10
b8d53ae
c165e10
f0e0245
a5bc115
70cc48f
 
 
8946944
 
 
 
70cc48f
 
 
41b3b51
70cc48f
41b3b51
 
70cc48f
a5bc115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41b3b51
b8d53ae
bc616c9
c165e10
41b3b51
d41428b
2774836
 
41b3b51
70cc48f
 
a5bc115
d41428b
 
 
 
 
 
 
 
70cc48f
a5bc115
d41428b
 
 
 
a5bc115
 
76b8a0b
 
 
 
 
 
 
 
 
 
c165e10
76b8a0b
 
 
 
 
 
9052d8e
 
6387a43
76b8a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
76b8a0b
c165e10
76b8a0b
 
 
70cc48f
76b8a0b
 
 
 
 
 
 
 
 
70cc48f
76b8a0b
 
 
 
 
 
 
 
 
 
 
 
2c8ae4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5283e2c
2c8ae4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5283e2c
2c8ae4e
 
 
 
 
 
 
 
5283e2c
2c8ae4e
 
a5bc115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
a5bc115
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
a5bc115
 
 
 
9052d8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5bc115
 
 
 
 
c165e10
a5bc115
 
 
 
 
 
 
 
c165e10
a5bc115
 
 
 
 
 
 
70cc48f
a5bc115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70cc48f
a5bc115
 
 
 
 
 
 
 
 
 
70cc48f
a5bc115
 
 
 
 
 
 
 
70cc48f
a5bc115
 
f0e0245
41b3b51
 
 
 
 
 
 
 
 
 
70cc48f
41b3b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70cc48f
41b3b51
 
 
 
 
 
 
 
 
 
 
 
 
 
70cc48f
41b3b51
 
 
 
 
70cc48f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76b8a0b
 
 
 
 
 
c165e10
76b8a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
76b8a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
76b8a0b
 
 
 
 
 
 
 
 
c165e10
76b8a0b
 
 
 
 
 
 
 
c165e10
76b8a0b
 
 
f0e0245
 
 
 
 
 
 
 
 
 
 
 
5283e2c
f0e0245
 
 
 
0b7bef2
 
f0e0245
 
 
 
 
 
 
 
 
 
 
 
5283e2c
f0e0245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5283e2c
7f36b83
 
 
 
 
 
 
 
 
 
 
 
 
 
5283e2c
8762688
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5283e2c
8762688
 
 
 
5283e2c
8762688
 
 
 
5283e2c
7f36b83
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
7f36b83
 
 
 
 
 
 
 
 
 
 
 
 
 
70cc48f
bc616c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5283e2c
bc616c9
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
bc616c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70cc48f
7f36b83
f0e0245
 
 
d41428b
 
 
 
 
 
 
 
 
 
 
 
0c21886
d41428b
 
 
 
 
 
 
0c21886
0b7bef2
b8d53ae
bc616c9
c165e10
b8d53ae
6db0b76
5283e2c
d41428b
2774836
 
 
b8d53ae
4256175
d41428b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c21886
d41428b
 
 
 
 
 
 
0c21886
0b7bef2
b8d53ae
bc616c9
c165e10
b8d53ae
6db0b76
5283e2c
d41428b
2774836
 
 
b8d53ae
4256175
d41428b
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
d41428b
 
 
 
 
 
 
 
 
 
 
c165e10
d41428b
 
 
 
 
 
 
 
 
70cc48f
d41428b
 
 
 
 
 
 
 
 
 
 
70cc48f
d41428b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
d41428b
 
 
 
 
 
 
 
 
 
 
 
2774836
 
 
 
 
 
5283e2c
2774836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5283e2c
2774836
 
 
 
4b9bf53
 
 
 
 
 
 
 
 
 
 
5283e2c
4b9bf53
 
 
 
5283e2c
4b9bf53
 
 
 
0b7bef2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c165e10
5283e2c
0b7bef2
 
 
 
 
 
 
 
 
 
c165e10
5283e2c
0b7bef2
 
 
 
 
 
 
 
 
 
c165e10
5283e2c
0b7bef2
 
 
 
 
 
 
 
 
 
c165e10
5283e2c
0b7bef2
 
 
 
 
 
 
 
 
 
c165e10
5283e2c
0b7bef2
 
 
 
 
 
 
 
 
 
c165e10
5283e2c
0b7bef2
 
 
 
 
6db0b76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c45d5f9
5283e2c
6db0b76
 
 
 
 
 
 
c45d5f9
5283e2c
6db0b76
 
 
 
 
 
 
 
 
 
c45d5f9
5283e2c
6db0b76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c45d5f9
5283e2c
6db0b76
 
 
 
 
5283e2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2774836
 
 
 
c165e10
2774836
 
 
 
 
 
 
 
70cc48f
2774836
 
 
 
2c8ae4e
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
use std::sync::Arc;

use ab_glyph::FontArc;
use image::codecs::jpeg::JpegEncoder;
use image::{imageops, DynamicImage, ImageDecoder, ImageReader, Limits, RgbaImage};
use tokio::sync::Semaphore;

use crate::cache;
use crate::error::AppError;
use crate::image::badge;
use crate::services::db::{BadgeAppearance, BadgeDirection, BadgeSize, BadgeStyle, LabelStyle, BadgePosition, PosterFit};
use crate::services::ratings::RatingBadge;
use crate::services::tmdb::TmdbClient;

/// Threshold (ms) above which render is logged as slow.
const SLOW_RENDER_MS: u64 = 2000;

const BADGE_SPACING: u32 = 10;
const BADGE_BOTTOM_MARGIN: u32 = 10;
const BADGE_TOP_MARGIN: u32 = 20;
const BADGE_SIDE_MARGIN: u32 = 15;
const BADGE_ROW_SPACING: u32 = 7;
const BADGE_VERT_SPACING: u32 = 7;
const BACKDROP_SIDE_MARGIN: u32 = 20;
const MAX_BADGES_PER_ROW: usize = 3;
const MAX_VERT_BADGES_PER_ROW: usize = 5;

pub struct ImageParams<'a> {
    pub poster_path: &'a str,
    pub badges: &'a [RatingBadge],
    pub tmdb: &'a TmdbClient,

    pub font: &'a FontArc,
    pub quality: u8,
    pub cache_dir: &'a str,
    pub image_stale_secs: u64,
    pub poster_bytes_override: Option<Vec<u8>>,
    pub poster_position: BadgePosition,
    pub badge_style: BadgeStyle,
    pub label_style: LabelStyle,
    pub badge_appearance: BadgeAppearance,
    pub badge_direction: BadgeDirection,
    /// When true, split the badges across two opposite sides of the poster.
    pub poster_badge_split: bool,
    /// How a non-2:3 poster is fit to the standard 2:3 output frame.
    pub poster_fit: PosterFit,
    pub render_semaphore: Arc<Semaphore>,
    /// Target width for the output image. Defaults to 500 for posters.
    pub target_width: u32,
    /// Badge scale factor (1.0 = default size).
    pub badge_scale: f32,
    /// TMDB CDN size string (e.g. "w500", "w780", "original").
    pub tmdb_size: Arc<str>,
    /// Badge size — used to adjust max badges per row.
    pub badge_size: BadgeSize,
    /// When true, skip writing base poster images to disk (CDN handles caching).
    pub external_cache_only: bool,
}

pub async fn generate_poster(params: ImageParams<'_>) -> Result<Vec<u8>, AppError> {
    let ImageParams {
        poster_path,
        badges,
        tmdb,
        font,
        quality,
        cache_dir,
        image_stale_secs,
        poster_bytes_override,
        poster_position,
        badge_style,
        label_style,
        badge_appearance,
        badge_direction,
        poster_badge_split,
        poster_fit,
        render_semaphore,
        target_width,
        badge_scale,
        badge_size,
        tmdb_size,
        external_cache_only,
    } = params;

    let poster_bytes = if let Some(bytes) = poster_bytes_override {
        bytes
    } else if external_cache_only {
        // No filesystem cache — always fetch from TMDB
        tmdb.fetch_poster_bytes(poster_path, &tmdb_size).await?
    } else {
        // Fetch base poster from TMDB, using cache
        let poster_cache = cache::base_poster_path(cache_dir, poster_path, &tmdb_size)?;
        if let Some(entry) = cache::read(&poster_cache, image_stale_secs).await {
            if entry.is_stale {
                // Conditional fetch — send If-Modified-Since to avoid re-downloading unchanged images
                let modified = tokio::fs::metadata(&poster_cache).await.ok()
                    .and_then(|m| m.modified().ok());
                match tmdb.fetch_poster_bytes_conditional(poster_path, &tmdb_size, modified).await? {
                    Some(fresh_bytes) => {
                        cache::write(&poster_cache, &fresh_bytes).await?;
                        fresh_bytes
                    }
                    None => {
                        // 304 Not Modified — touch mtime without rewriting the file
                        if let Ok(f) = tokio::fs::File::open(&poster_cache).await {
                            let _ = f.into_std().await.set_modified(std::time::SystemTime::now());
                        }
                        entry.bytes
                    }
                }
            } else {
                entry.bytes
            }
        } else {
            let bytes = tmdb.fetch_poster_bytes(poster_path, &tmdb_size).await?;
            cache::write(&poster_cache, &bytes).await?;
            bytes
        }
    };

    // Acquire render permit before CPU-bound work — also bounds queue depth
    // so tasks waiting for a blocking thread still count against the limit.
    if render_semaphore.available_permits() == 0 {
        tracing::debug!("render queue full, waiting for permit");
    }
    let _permit = render_semaphore.acquire().await
        .map_err(|_| AppError::Other("render queue closed".into()))?;
    tracing::debug!("poster render started");
    let start = std::time::Instant::now();

    // Move CPU-bound image processing to a blocking thread
    let badges = badges.to_vec();
    let font = font.clone();
    let buf = tokio::task::spawn_blocking(move || {
        render_poster_sync(&poster_bytes, &badges, &font, quality, poster_position, badge_style, label_style, badge_appearance, badge_direction, target_width, badge_scale, badge_size, poster_badge_split, poster_fit)
    })
    .await
    .map_err(|e| AppError::Other(e.to_string()))??;

    let render_ms = start.elapsed().as_millis() as u64;
    tracing::debug!(elapsed_ms = render_ms, "poster render complete");
    if render_ms > SLOW_RENDER_MS {
        tracing::warn!(
            poster_path,
            render_ms,
            "slow generate_poster"
        );
    }
    Ok(buf)
}

/// Overlay badges in a vertical column, positioned according to `position`.
///
/// `extra_x` / `extra_y` are additional edge insets in pixels (already resolved
/// for this canvas) that push the badges further from the anchored edge. They
/// only take effect on the edge the position anchors to: `extra_y` on top/bottom
/// anchors, `extra_x` on left/right anchors. Centered axes ignore their inset.
/// Callers that don't want insets pass `0, 0`.
fn overlay_vertical_stack(canvas: &mut RgbaImage, badge_images: &[RgbaImage], position: BadgePosition, badge_scale: f32, side_margin_base: u32, extra_x: u32, extra_y: u32) {
    let vert_spacing = (BADGE_VERT_SPACING as f32 * badge_scale).round() as u32;
    let top_margin = (BADGE_TOP_MARGIN as f32 * badge_scale).round() as u32;
    let bottom_margin = (BADGE_BOTTOM_MARGIN as f32 * badge_scale).round() as u32;
    let side_margin = (side_margin_base as f32 * badge_scale).round() as u32;

    let total_badge_height: u32 = badge_images.iter().map(|b| b.height()).sum::<u32>()
        + vert_spacing * (badge_images.len() as u32).saturating_sub(1);
    let max_badge_width: u32 = badge_images.iter().map(|b| b.width()).max().unwrap_or(0);

    // Vertical anchor
    let start_y = if position.is_top() {
        top_margin + extra_y
    } else if position.is_bottom() {
        canvas.height().saturating_sub(total_badge_height + bottom_margin + extra_y)
    } else {
        // "l", "r" — vertically centered
        (canvas.height().saturating_sub(total_badge_height)) / 2
    };

    // Horizontal anchor
    let is_left = position.is_left();
    let is_right = position.is_right();

    let base_x = if is_left {
        side_margin + extra_x
    } else if is_right {
        canvas.width().saturating_sub(max_badge_width + side_margin + extra_x)
    } else {
        // center
        (canvas.width().saturating_sub(max_badge_width)) / 2
    };

    let mut y = start_y;
    for badge_img in badge_images {
        let bx = if is_left {
            base_x
        } else if is_right {
            base_x + max_badge_width.saturating_sub(badge_img.width())
        } else {
            base_x + (max_badge_width.saturating_sub(badge_img.width())) / 2
        };
        imageops::overlay(canvas, badge_img, bx as i64, y as i64);
        y += badge_img.height() + vert_spacing;
    }
}

/// Overlay badges in horizontal rows, positioned according to `position`.
///
/// `extra_x` / `extra_y` behave as in [`overlay_vertical_stack`]: edge insets in
/// resolved pixels that only apply to the anchored edge (centered axes ignore
/// them). Callers that don't want insets pass `0, 0`.
fn overlay_horizontal_rows(canvas: &mut RgbaImage, badge_images: &[RgbaImage], position: BadgePosition, max_per_row: usize, badge_scale: f32, side_margin_base: u32, extra_x: u32, extra_y: u32) {
    let spacing = (BADGE_SPACING as f32 * badge_scale).round() as u32;
    let row_spacing = (BADGE_ROW_SPACING as f32 * badge_scale).round() as u32;
    let top_margin = (BADGE_TOP_MARGIN as f32 * badge_scale).round() as u32;
    let bottom_margin = (BADGE_BOTTOM_MARGIN as f32 * badge_scale).round() as u32;
    let side_margin = (side_margin_base as f32 * badge_scale).round() as u32;

    let rows: Vec<&[RgbaImage]> = badge_images.chunks(max_per_row).collect();
    let badge_height = badge_images.iter().map(|b| b.height()).max().unwrap_or(0);
    let total_height = badge_height * rows.len() as u32
        + row_spacing * (rows.len() as u32).saturating_sub(1);

    // Vertical anchor
    let base_y = if position.is_top() {
        top_margin + extra_y
    } else if position.is_bottom() {
        canvas.height().saturating_sub(total_height + bottom_margin + extra_y)
    } else {
        // "l", "r" — vertically centered
        (canvas.height().saturating_sub(total_height)) / 2
    };

    // Horizontal alignment
    let is_left = position.is_left();
    let is_right = position.is_right();

    for (row_idx, row) in rows.iter().enumerate() {
        let row_width: u32 = row.iter().map(|b| b.width()).sum::<u32>()
            + spacing * (row.len() as u32).saturating_sub(1);
        let y = base_y + row_idx as u32 * (badge_height + row_spacing);

        let start_x = if is_left {
            side_margin + extra_x
        } else if is_right {
            canvas.width().saturating_sub(row_width + side_margin + extra_x)
        } else {
            (canvas.width().saturating_sub(row_width)) / 2
        };

        let mut x = start_x;
        for badge_img in *row {
            let by = y + (badge_height.saturating_sub(badge_img.height())) / 2;
            imageops::overlay(canvas, badge_img, x as i64, by as i64);
            x += badge_img.width() + spacing;
        }
    }
}

/// Maximum total pixels allowed for a decoded source image (width * height).
/// 8192x8192 = 67M pixels (~256 MB as RGBA) is generous for poster/backdrop art
/// while preventing OOM from crafted images with extreme dimensions.
const MAX_IMAGE_PIXELS: u64 = 8192 * 8192;

/// Decode an image from bytes, rejecting oversized images *before* full decode
/// to avoid OOM from crafted inputs (e.g. PNG bombs).
fn load_image_with_limits(bytes: &[u8]) -> Result<image::DynamicImage, AppError> {
    let reader = ImageReader::new(std::io::Cursor::new(bytes))
        .with_guessed_format()
        .map_err(|e| AppError::Other(format!("image format detection failed: {e}")))?;

    let mut limits = Limits::default();
    limits.max_alloc = Some(MAX_IMAGE_PIXELS * 4); // RGBA = 4 bytes/pixel
    let mut decoder = reader.into_decoder().map_err(AppError::Image)?;
    decoder.set_limits(limits).map_err(AppError::Image)?;

    image::DynamicImage::from_decoder(decoder).map_err(AppError::Image)
}

/// Standard movie-poster aspect ratio is 2:3 (width:height), so the output
/// height for a given width is `width * 3 / 2`.
fn poster_target_height(target_width: u32) -> u32 {
    ((target_width as f64) * 1.5).round() as u32
}

/// Blur strength for `PosterFit::Blur` scales with output width so the effect
/// looks consistent across image sizes. `fast_blur` approximates a Gaussian
/// blur cheaply enough for the largest (2000px) posters.
const BLUR_SIGMA_DIVISOR: f32 = 32.0;

/// Normalize a decoded source poster to the output frame per `fit`, returning
/// the RGBA canvas the badges are then composited onto.
///
/// Every mode except `Native` produces an exact 2:3 frame
/// (`target_width × target_width*3/2`) so downstream apps that place posters in
/// fixed 2:3 containers never crop the art (issue #15).
fn fit_poster(base: DynamicImage, target_width: u32, fit: PosterFit) -> RgbaImage {
    use image::imageops::FilterType::Lanczos3;
    match fit {
        // Preserve the source aspect ratio: scale to target_width only.
        PosterFit::Native => {
            if base.width() == target_width {
                base.to_rgba8()
            } else {
                let scale = target_width as f64 / base.width() as f64;
                let target_height = ((base.height() as f64 * scale).round() as u32).max(1);
                base.resize_exact(target_width, target_height, Lanczos3).to_rgba8()
            }
        }
        // Scale to fill the 2:3 frame, center-cropping the overflow.
        PosterFit::Cover => {
            let th = poster_target_height(target_width);
            base.resize_to_fill(target_width, th, Lanczos3).to_rgba8()
        }
        // Fit the whole poster inside 2:3, padding with solid black bars.
        PosterFit::Pad => {
            let th = poster_target_height(target_width);
            let fitted = base.resize(target_width, th, Lanczos3).to_rgba8();
            let mut canvas = RgbaImage::from_pixel(target_width, th, image::Rgba([0, 0, 0, 255]));
            let x = ((target_width.saturating_sub(fitted.width())) / 2) as i64;
            let y = ((th.saturating_sub(fitted.height())) / 2) as i64;
            imageops::overlay(&mut canvas, &fitted, x, y);
            canvas
        }
        // Fit the whole poster inside 2:3, filling the bars with a blurred,
        // zoomed copy of the poster.
        PosterFit::Blur => {
            let th = poster_target_height(target_width);
            let bg = base.resize_to_fill(target_width, th, Lanczos3).to_rgba8();
            let sigma = (target_width as f32 / BLUR_SIGMA_DIVISOR).max(1.0);
            let mut canvas = imageops::fast_blur(&bg, sigma);
            let fitted = base.resize(target_width, th, Lanczos3).to_rgba8();
            let x = ((target_width.saturating_sub(fitted.width())) / 2) as i64;
            let y = ((th.saturating_sub(fitted.height())) / 2) as i64;
            imageops::overlay(&mut canvas, &fitted, x, y);
            canvas
        }
    }
}

pub fn render_poster_sync(
    poster_bytes: &[u8],
    badges: &[RatingBadge],
    font: &FontArc,
    quality: u8,
    poster_position: BadgePosition,
    badge_style: BadgeStyle,
    label_style: LabelStyle,
    badge_appearance: BadgeAppearance,
    badge_direction: BadgeDirection,
    target_width: u32,
    badge_scale: f32,
    badge_size: BadgeSize,
    poster_badge_split: bool,
    poster_fit: PosterFit,
) -> Result<Vec<u8>, AppError> {
    // A pill is a horizontal lozenge (icon/label left, value right) — never a
    // vertical stacked badge, even when the configured style is vertical.
    let badge_style = badge_style.for_shape(badge_appearance.shape);
    let base = load_image_with_limits(poster_bytes)?;

    // Normalize to the output frame (2:3 for every mode except Native) before
    // overlaying badges, so badges anchor to the final frame corners.
    let mut canvas: RgbaImage = fit_poster(base, target_width, poster_fit);

    if !badges.is_empty() {
        let badge_images: Vec<RgbaImage> = if badge_style.is_vertical() {
            badges.iter().map(|b| badge::render_vertical_badge(b, font, label_style, badge_appearance, badge_scale)).collect()
        } else {
            badge::render_badges_uniform(badges, font, label_style, badge_appearance, badge_scale)
        };

        let max_per_row = match badge_size {
            BadgeSize::Large | BadgeSize::ExtraLarge => {
                if badge_style == BadgeStyle::Horizontal { 2 } else { 4 }
            }
            _ => {
                if badge_style.is_vertical() { MAX_VERT_BADGES_PER_ROW } else { MAX_BADGES_PER_ROW }
            }
        };

        if poster_badge_split && badge_images.len() >= 2 {
            // Split the badges across two opposite sides. A vertical badge layout
            // splits left/right; horizontal rows split top/bottom. The first
            // (higher-priority) half keeps the configured anchor side.
            let split_top_bottom = !badge_direction.is_vertical();
            let (primary, opposite) = poster_position.split_anchors(split_top_bottom);
            let mid = badge_images.len().div_ceil(2);
            let (first, second) = badge_images.split_at(mid);
            overlay_poster_group(&mut canvas, first, primary, badge_direction, max_per_row, badge_scale);
            overlay_poster_group(&mut canvas, second, opposite, badge_direction, max_per_row, badge_scale);
        } else {
            overlay_poster_group(&mut canvas, &badge_images, poster_position, badge_direction, max_per_row, badge_scale);
        }
    }

    // Encode as JPEG
    let dynamic = DynamicImage::ImageRgba8(canvas);
    let rgb = dynamic.to_rgb8();
    let mut buf = Vec::new();
    let encoder = JpegEncoder::new_with_quality(&mut buf, quality);
    rgb.write_with_encoder(encoder)?;

    Ok(buf)
}

/// Overlay one group of poster badges at `position`, using the configured
/// stacking direction. Vertical direction stacks a column; horizontal direction
/// lays out rows of up to `max_per_row` badges.
fn overlay_poster_group(
    canvas: &mut RgbaImage,
    badge_images: &[RgbaImage],
    position: BadgePosition,
    badge_direction: BadgeDirection,
    max_per_row: usize,
    badge_scale: f32,
) {
    if badge_direction.is_vertical() {
        overlay_vertical_stack(canvas, badge_images, position, badge_scale, BADGE_SIDE_MARGIN, 0, 0);
    } else {
        overlay_horizontal_rows(canvas, badge_images, position, max_per_row, badge_scale, BADGE_SIDE_MARGIN, 0, 0);
    }
}

/// Fixed vertical space (px, at badge_scale = 1.0) reserved for the logo artwork.
/// TMDB logo assets vary wildly in native aspect ratio — some are short/wide
/// wordmarks, others are tall vertical scripts. Previously the logo was resized to
/// a fixed *width* only, letting height float with the source shape, which made the
/// total composite a different overall size per title — so Stremio's own image-fit
/// scaling applied a different effective zoom to the embedded badges depending on
/// each logo's shape. Reserving a fixed box and "contain"-fitting every logo into it
/// (centered, never cropped) keeps the composite's overall dimensions — and
/// therefore the badges' on-screen size — constant across all titles.
const LOGO_AREA_HEIGHT: u32 = 150;

/// Resize `img` to fit entirely within `box_width` x `box_height` (preserving aspect
/// ratio, never upscaling, never cropping), then center it on a transparent canvas
/// of exactly `box_width` x `box_height`.
fn fit_and_pad(img: &RgbaImage, box_width: u32, box_height: u32) -> RgbaImage {
    let scale = (box_width as f64 / img.width() as f64)
        .min(box_height as f64 / img.height() as f64);
    let new_w = ((img.width() as f64 * scale).round() as u32).max(1);
    let new_h = ((img.height() as f64 * scale).round() as u32).max(1);

    let resized = if new_w == img.width() && new_h == img.height() {
        img.clone()
    } else {
        imageops::resize(img, new_w, new_h, image::imageops::FilterType::Lanczos3)
    };

    let mut canvas = RgbaImage::new(box_width, box_height);
    let x = (box_width.saturating_sub(new_w)) / 2;
    let y = (box_height.saturating_sub(new_h)) / 2;
    imageops::overlay(&mut canvas, &resized, x as i64, y as i64);
    canvas
}

const LOGO_BADGE_ROW_SPACING: u32 = 7;
const LOGO_BADGE_SPACING: u32 = 10;
const LOGO_MAX_BADGES_PER_ROW: usize = 3;
const LOGO_SPACING_BELOW: u32 = 15;

pub fn render_logo_sync(
    logo_bytes: &[u8],
    badges: &[RatingBadge],
    font: &FontArc,
    badge_style: BadgeStyle,
    label_style: LabelStyle,
    badge_appearance: BadgeAppearance,
    target_width: u32,
    badge_scale: f32,
) -> Result<Vec<u8>, AppError> {
    // A pill is a horizontal lozenge (icon/label left, value right) — never a
    // vertical stacked badge, even when the configured style is vertical.
    let badge_style = badge_style.for_shape(badge_appearance.shape);
    let base = load_image_with_limits(logo_bytes)?;

    let base = if base.width() != target_width {
        let scale = target_width as f64 / base.width() as f64;
        let target_height = (base.height() as f64 * scale).round() as u32;
        base.resize_exact(target_width, target_height, image::imageops::FilterType::Lanczos3)
    } else {
        base
    };

    if badges.is_empty() {
        // No badges — just encode the logo as PNG
        let logo_img = base.to_rgba8();
        let mut buf = Vec::new();
        let encoder = image::codecs::png::PngEncoder::new(&mut buf);
        image::ImageEncoder::write_image(
            encoder,
            logo_img.as_raw(),
            logo_img.width(),
            logo_img.height(),
            image::ExtendedColorType::Rgba8,
        )?;
        return Ok(buf);
    }

    let logo_area_height = (LOGO_AREA_HEIGHT as f32 * badge_scale).round().max(1.0) as u32;
    let logo_img = fit_and_pad(&base.to_rgba8(), target_width, logo_area_height);

    let logo_badge_spacing = (LOGO_BADGE_SPACING as f32 * badge_scale).round() as u32;
    let logo_badge_row_spacing = (LOGO_BADGE_ROW_SPACING as f32 * badge_scale).round() as u32;
    let logo_spacing_below = (LOGO_SPACING_BELOW as f32 * badge_scale).round() as u32;

    if badge_style.is_vertical() {
        // Vertical badge shapes arranged in rows below the logo
        let badge_images: Vec<RgbaImage> = badges
                .iter()
                .map(|b| badge::render_vertical_badge(b, font, label_style, badge_appearance, badge_scale))
                .collect();

            let rows: Vec<&[RgbaImage]> = badge_images.chunks(MAX_VERT_BADGES_PER_ROW).collect();
            let max_badge_height: u32 = badge_images.iter().map(|b| b.height()).max().unwrap_or(0);
            let total_badge_height = max_badge_height * rows.len() as u32
                + logo_badge_row_spacing * (rows.len() as u32).saturating_sub(1);

            let max_row_width: u32 = rows
                .iter()
                .map(|row| {
                    row.iter().map(|b| b.width()).sum::<u32>()
                        + logo_badge_spacing * (row.len() as u32).saturating_sub(1)
                })
                .max()
                .unwrap_or(0);

            let canvas_width = target_width.max(max_row_width);
            let canvas_height = logo_area_height + logo_spacing_below + total_badge_height;

            let mut canvas = RgbaImage::new(canvas_width, canvas_height);

            let logo_x = (canvas_width.saturating_sub(logo_img.width())) / 2;
            imageops::overlay(&mut canvas, &logo_img, logo_x as i64, 0);

            let badges_start_y = logo_area_height + logo_spacing_below;
            for (row_idx, row) in rows.iter().enumerate() {
                let row_width: u32 = row.iter().map(|b| b.width()).sum::<u32>()
                    + logo_badge_spacing * (row.len() as u32).saturating_sub(1);
                let start_x = (canvas_width.saturating_sub(row_width)) / 2;
                let y = badges_start_y + row_idx as u32 * (max_badge_height + logo_badge_row_spacing);

                let mut x = start_x;
                for badge_img in *row {
                    let by = y + (max_badge_height.saturating_sub(badge_img.height())) / 2;
                    imageops::overlay(&mut canvas, badge_img, x as i64, by as i64);
                    x += badge_img.width() + logo_badge_spacing;
                }
            }

            // Encode as PNG
            let mut buf = Vec::new();
            let encoder = image::codecs::png::PngEncoder::new(&mut buf);
            image::ImageEncoder::write_image(
                encoder,
                canvas.as_raw(),
                canvas.width(),
                canvas.height(),
                image::ExtendedColorType::Rgba8,
            )?;
            Ok(buf)
    } else {
        // Horizontal badge images (default) — uniform widths, arranged in rows below the logo
            let badge_images = badge::render_badges_uniform(badges, font, label_style, badge_appearance, badge_scale);

            let rows: Vec<&[RgbaImage]> = badge_images.chunks(LOGO_MAX_BADGES_PER_ROW).collect();
            let badge_height = badge_images[0].height();
            let total_badge_height =
                badge_height * rows.len() as u32 + logo_badge_row_spacing * (rows.len() as u32).saturating_sub(1);

            // Compute row widths to determine canvas width
            let max_row_width: u32 = rows
                .iter()
                .map(|row| {
                    row.iter().map(|b| b.width()).sum::<u32>()
                        + logo_badge_spacing * (row.len() as u32).saturating_sub(1)
                })
                .max()
                .unwrap_or(0);

            let canvas_width = target_width.max(max_row_width);
            let canvas_height = logo_area_height + logo_spacing_below + total_badge_height;

            let mut canvas = RgbaImage::new(canvas_width, canvas_height);

            // Center logo at top
            let logo_x = (canvas_width.saturating_sub(logo_img.width())) / 2;
            imageops::overlay(&mut canvas, &logo_img, logo_x as i64, 0);

            // Center badge rows below logo
            let badges_start_y = logo_area_height + logo_spacing_below;
            for (row_idx, row) in rows.iter().enumerate() {
                let row_width: u32 = row.iter().map(|b| b.width()).sum::<u32>()
                    + logo_badge_spacing * (row.len() as u32).saturating_sub(1);
                let start_x = (canvas_width.saturating_sub(row_width)) / 2;
                let y = badges_start_y + row_idx as u32 * (badge_height + logo_badge_row_spacing);

                let mut x = start_x;
                for badge_img in *row {
                    imageops::overlay(&mut canvas, badge_img, x as i64, y as i64);
                    x += badge_img.width() + logo_badge_spacing;
                }
            }

            // Encode as PNG (preserves transparency)
            let mut buf = Vec::new();
            let encoder = image::codecs::png::PngEncoder::new(&mut buf);
            image::ImageEncoder::write_image(
                encoder,
                canvas.as_raw(),
                canvas.width(),
                canvas.height(),
                image::ExtendedColorType::Rgba8,
            )?;
            Ok(buf)
    }
}

pub async fn generate_logo(
    logo_bytes: Vec<u8>,
    badges: Vec<RatingBadge>,
    font: FontArc,
    badge_style: BadgeStyle,
    label_style: LabelStyle,
    badge_appearance: BadgeAppearance,
    render_semaphore: Arc<Semaphore>,
    target_width: u32,
    badge_scale: f32,
) -> Result<Vec<u8>, AppError> {
    if render_semaphore.available_permits() == 0 {
        tracing::debug!("render queue full, waiting for permit");
    }
    let _permit = render_semaphore.acquire().await
        .map_err(|_| AppError::Other("render queue closed".into()))?;
    tracing::debug!("logo render started");
    let start = std::time::Instant::now();

    let buf = tokio::task::spawn_blocking(move || render_logo_sync(&logo_bytes, &badges, &font, badge_style, label_style, badge_appearance, target_width, badge_scale))
        .await
        .map_err(|e| AppError::Other(e.to_string()))??;

    tracing::debug!(elapsed_ms = start.elapsed().as_millis() as u64, "logo render complete");
    Ok(buf)
}

pub fn render_backdrop_sync(
    backdrop_bytes: &[u8],
    badges: &[RatingBadge],
    font: &FontArc,
    quality: u8,
    position: BadgePosition,
    badge_style: BadgeStyle,
    label_style: LabelStyle,
    badge_appearance: BadgeAppearance,
    badge_direction: BadgeDirection,
    target_width: u32,
    badge_scale: f32,
    _badge_size: BadgeSize,
    edge_inset_x: i32,
    edge_inset_y: i32,
) -> Result<Vec<u8>, AppError> {
    // A pill is a horizontal lozenge (icon/label left, value right) — never a
    // vertical stacked badge, even when the configured style is vertical.
    let badge_style = badge_style.for_shape(badge_appearance.shape);
    let base = load_image_with_limits(backdrop_bytes)?;

    let base = if base.width() != target_width {
        let scale = target_width as f64 / base.width() as f64;
        let target_height = (base.height() as f64 * scale).round() as u32;
        base.resize_exact(target_width, target_height, image::imageops::FilterType::Lanczos3)
    } else {
        base
    };

    let mut canvas: RgbaImage = base.to_rgba8();

    if !badges.is_empty() {
        let badge_images: Vec<RgbaImage> = if badge_style.is_vertical() {
            badges.iter().map(|b| badge::render_vertical_badge(b, font, label_style, badge_appearance, badge_scale)).collect()
        } else {
            badge::render_badges_uniform(badges, font, label_style, badge_appearance, badge_scale)
        };

        // Edge insets are a percentage of the canvas dimension, so they stay
        // proportional across image sizes (small/medium/large). The overlay
        // functions only apply each axis on the edge the position anchors to.
        // Clamp to the same MAX_EDGE_INSET the settings/cache-key paths use so the
        // rendered inset can never diverge from the value baked into the cache key.
        let inset_pct_x = crate::services::db::clamp_edge_inset(edge_inset_x) as f32 / 100.0;
        let inset_pct_y = crate::services::db::clamp_edge_inset(edge_inset_y) as f32 / 100.0;
        let extra_x = (canvas.width() as f32 * inset_pct_x).round() as u32;
        let extra_y = (canvas.height() as f32 * inset_pct_y).round() as u32;

        if badge_direction.is_vertical() {
            overlay_vertical_stack(&mut canvas, &badge_images, position, badge_scale, BACKDROP_SIDE_MARGIN, extra_x, extra_y);
        } else {
            // Backdrops are wide (16:9) so all badges fit in a single row
            overlay_horizontal_rows(&mut canvas, &badge_images, position, badge_images.len(), badge_scale, BACKDROP_SIDE_MARGIN, extra_x, extra_y);
        }
    }

    // Encode as JPEG
    let dynamic = DynamicImage::ImageRgba8(canvas);
    let rgb = dynamic.to_rgb8();
    let mut buf = Vec::new();
    let encoder = JpegEncoder::new_with_quality(&mut buf, quality);
    rgb.write_with_encoder(encoder)?;
    Ok(buf)
}

pub async fn generate_backdrop(
    backdrop_bytes: Vec<u8>,
    badges: Vec<RatingBadge>,
    font: FontArc,
    quality: u8,
    position: BadgePosition,
    badge_style: BadgeStyle,
    label_style: LabelStyle,
    badge_appearance: BadgeAppearance,
    badge_direction: BadgeDirection,
    render_semaphore: Arc<Semaphore>,
    target_width: u32,
    badge_scale: f32,
    badge_size: BadgeSize,
    edge_inset_x: i32,
    edge_inset_y: i32,
) -> Result<Vec<u8>, AppError> {
    if render_semaphore.available_permits() == 0 {
        tracing::debug!("render queue full, waiting for permit");
    }
    let _permit = render_semaphore.acquire().await
        .map_err(|_| AppError::Other("render queue closed".into()))?;
    tracing::debug!("backdrop render started");
    let start = std::time::Instant::now();

    let buf = tokio::task::spawn_blocking(move || render_backdrop_sync(&backdrop_bytes, &badges, &font, quality, position, badge_style, label_style, badge_appearance, badge_direction, target_width, badge_scale, badge_size, edge_inset_x, edge_inset_y))
        .await
        .map_err(|e| AppError::Other(e.to_string()))??;

    tracing::debug!(elapsed_ms = start.elapsed().as_millis() as u64, "backdrop render complete");
    Ok(buf)
}

/// Episode still rendering with configurable position, direction, and optional blur.
/// Reuses the poster badge overlay functions but with episode-specific settings.
pub fn render_episode_sync(
    image_bytes: &[u8],
    badges: &[RatingBadge],
    font: &FontArc,
    quality: u8,
    position: BadgePosition,
    badge_style: BadgeStyle,
    label_style: LabelStyle,
    badge_appearance: BadgeAppearance,
    badge_direction: BadgeDirection,
    target_width: u32,
    badge_scale: f32,
    badge_size: BadgeSize,
    blur: bool,
) -> Result<Vec<u8>, AppError> {
    // A pill is a horizontal lozenge (icon/label left, value right) — never a
    // vertical stacked badge, even when the configured style is vertical.
    let badge_style = badge_style.for_shape(badge_appearance.shape);
    let base = image::load_from_memory(image_bytes)
        .map_err(AppError::Image)?;

    let base = if base.width() != target_width {
        let scale = target_width as f64 / base.width() as f64;
        let target_height = (base.height() as f64 * scale).round() as u32;
        base.resize_exact(target_width, target_height, image::imageops::FilterType::Lanczos3)
    } else {
        base
    };

    let mut canvas: RgbaImage = base.to_rgba8();

    // Apply blur for spoiler protection (before badge overlay).
    // Downscale → small blur → upscale is much faster than a large-radius Gaussian
    // and visually equivalent for spoiler hiding.
    if blur && canvas.width() >= 8 && canvas.height() >= 8 {
        let (w, h) = (canvas.width(), canvas.height());
        let small = image::imageops::resize(&canvas, w / 8, h / 8, image::imageops::FilterType::Triangle);
        let small = imageproc::filter::gaussian_blur_f32(&small, 3.0);
        canvas = image::imageops::resize(&small, w, h, image::imageops::FilterType::Triangle);
    }

    if !badges.is_empty() {
        let badge_images: Vec<RgbaImage> = if badge_style.is_vertical() {
            badges.iter().map(|b| badge::render_vertical_badge(b, font, label_style, badge_appearance, badge_scale)).collect()
        } else {
            badge::render_badges_uniform(badges, font, label_style, badge_appearance, badge_scale)
        };

        if badge_direction.is_vertical() {
            overlay_vertical_stack(&mut canvas, &badge_images, position, badge_scale, BADGE_SIDE_MARGIN, 0, 0);
        } else {
            let max_per_row = match badge_size {
                BadgeSize::Large | BadgeSize::ExtraLarge => {
                    if badge_style == BadgeStyle::Horizontal { 2 } else { 4 }
                }
                _ => {
                    if badge_style.is_vertical() { MAX_VERT_BADGES_PER_ROW } else { MAX_BADGES_PER_ROW }
                }
            };
            overlay_horizontal_rows(&mut canvas, &badge_images, position, max_per_row, badge_scale, BADGE_SIDE_MARGIN, 0, 0);
        }
    }

    // Encode as JPEG
    let dynamic = DynamicImage::ImageRgba8(canvas);
    let rgb = dynamic.to_rgb8();
    let mut buf = Vec::new();
    let encoder = JpegEncoder::new_with_quality(&mut buf, quality);
    rgb.write_with_encoder(encoder)?;
    Ok(buf)
}

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

    #[test]
    fn render_poster_no_badges() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        // Create a minimal valid PNG in memory
        let img = image::RgbaImage::from_pixel(100, 150, image::Rgba([128, 128, 128, 255]));
        let mut png_bytes = Vec::new();
        let encoder = image::codecs::png::PngEncoder::new(&mut png_bytes);
        image::ImageEncoder::write_image(
            encoder,
            img.as_raw(),
            100,
            150,
            image::ExtendedColorType::Rgba8,
        )
        .unwrap();

        let result = render_poster_sync(&png_bytes, &[], &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert!(!result.is_empty());
        // Should be valid JPEG
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_poster_with_badges() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let img = image::RgbaImage::from_pixel(500, 750, image::Rgba([128, 128, 128, 255]));
        let mut png_bytes = Vec::new();
        let encoder = image::codecs::png::PngEncoder::new(&mut png_bytes);
        image::ImageEncoder::write_image(
            encoder,
            img.as_raw(),
            500,
            750,
            image::ExtendedColorType::Rgba8,
        )
        .unwrap();

        let badges = vec![
            RatingBadge {
                source: RatingSource::Imdb,
                value: "8.5".to_string(),
            },
            RatingBadge {
                source: RatingSource::Tmdb,
                value: "85%".to_string(),
            },
            RatingBadge {
                source: RatingSource::Rt,
                value: "92%".to_string(),
            },
            RatingBadge {
                source: RatingSource::Metacritic,
                value: "78".to_string(),
            },
        ];

        let result = render_poster_sync(&png_bytes, &badges, &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_poster_invalid_image_bytes() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_poster_sync(b"not an image", &[], &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native);
        assert!(result.is_err());
    }

    /// Helper: create a minimal PNG in memory.
    fn test_png(width: u32, height: u32) -> Vec<u8> {
        let img = image::RgbaImage::from_pixel(width, height, image::Rgba([128, 128, 128, 255]));
        let mut buf = Vec::new();
        let encoder = image::codecs::png::PngEncoder::new(&mut buf);
        image::ImageEncoder::write_image(
            encoder,
            img.as_raw(),
            width,
            height,
            image::ExtendedColorType::Rgba8,
        )
        .unwrap();
        buf
    }

    #[test]
    fn render_logo_no_badges() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(200, 80);
        let result = render_logo_sync(&png, &[], &font, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), 500, 1.0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(&result[..4], &[0x89, b'P', b'N', b'G']);
    }

    #[test]
    fn render_logo_with_badges() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(400, 100);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Tmdb, value: "85%".to_string() },
        ];
        let result = render_logo_sync(&png, &badges, &font, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), 500, 1.0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(&result[..4], &[0x89, b'P', b'N', b'G']);
    }

    #[test]
    fn pill_renders_horizontally_regardless_of_style() {
        use crate::services::db::{BadgeBackground, BadgeShape};
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(400, 100);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Tmdb, value: "85%".to_string() },
        ];
        let pill = BadgeAppearance { shape: BadgeShape::Pill, background: BadgeBackground::Default };
        let rounded = BadgeAppearance::default();

        // A pill ignores the vertical style and always renders horizontally, so
        // vertical+pill and horizontal+pill produce identical output.
        let v_pill = render_logo_sync(&png, &badges, &font, BadgeStyle::Vertical, LabelStyle::Official, pill, 500, 1.0).unwrap();
        let h_pill = render_logo_sync(&png, &badges, &font, BadgeStyle::Horizontal, LabelStyle::Official, pill, 500, 1.0).unwrap();
        assert_eq!(v_pill, h_pill, "pill should render horizontally even when the style is vertical");

        // Rounded badges still honour the style, so the two layouts differ.
        let v_round = render_logo_sync(&png, &badges, &font, BadgeStyle::Vertical, LabelStyle::Official, rounded, 500, 1.0).unwrap();
        let h_round = render_logo_sync(&png, &badges, &font, BadgeStyle::Horizontal, LabelStyle::Official, rounded, 500, 1.0).unwrap();
        assert_ne!(v_round, h_round, "rounded badges should still differ between vertical and horizontal styles");
    }

    #[test]
    fn render_logo_downscales_wide_image() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        // Create a logo wider than TARGET_WIDTH (500)
        let png = test_png(1000, 200);
        let result = render_logo_sync(&png, &[], &font, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), 500, 1.0).unwrap();
        assert!(!result.is_empty());
        // Verify the output is valid PNG and was produced (implicitly downscaled)
        assert_eq!(&result[..4], &[0x89, b'P', b'N', b'G']);
    }

    #[test]
    fn render_logo_invalid_bytes() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_logo_sync(b"not an image", &[], &font, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), 500, 1.0);
        assert!(result.is_err());
    }

    #[test]
    fn render_backdrop_no_badges() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(640, 360);
        let result = render_backdrop_sync(&png, &[], &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, 1280, 1.0, BadgeSize::Medium, 0, 0).unwrap();
        assert!(!result.is_empty());
        // Backdrop outputs JPEG
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_backdrop_with_badges() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(1280, 720);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "9.0".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "95%".to_string() },
        ];
        let result = render_backdrop_sync(&png, &badges, &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, 1280, 1.0, BadgeSize::Medium, 0, 0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_backdrop_downscales_wide_image() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        // Create a backdrop wider than TARGET_WIDTH (1280)
        let png = test_png(2560, 1440);
        let result = render_backdrop_sync(&png, &[], &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, 1280, 1.0, BadgeSize::Medium, 0, 0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_backdrop_invalid_bytes() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_backdrop_sync(b"not an image", &[], &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, 1280, 1.0, BadgeSize::Medium, 0, 0);
        assert!(result.is_err());
    }

    #[test]
    fn render_backdrop_horizontal_bottom_center() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(1280, 720);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "9.0".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "95%".to_string() },
        ];
        let result = render_backdrop_sync(&png, &badges, &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 1280, 1.0, BadgeSize::Medium, 0, 0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_backdrop_horizontal_large_badges() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(1280, 720);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "9.0".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "95%".to_string() },
            RatingBadge { source: RatingSource::RtAudience, value: "80%".to_string() },
        ];
        // Large + Horizontal style — all badges in a single row on wide backdrop
        let result = render_backdrop_sync(&png, &badges, &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 1280, 1.0, BadgeSize::Large, 0, 0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_backdrop_vertical_bottom_left() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(1280, 720);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
        ];
        let result = render_backdrop_sync(&png, &badges, &font, 85, BadgePosition::BottomLeft, BadgeStyle::Vertical, LabelStyle::Icon, BadgeAppearance::default(), BadgeDirection::Vertical, 1280, 1.0, BadgeSize::Medium, 0, 0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_backdrop_edge_inset_shifts_only_active_axis() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(1280, 720);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "9.0".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "95%".to_string() },
        ];
        let render = |pos: BadgePosition, x: i32, y: i32| {
            render_backdrop_sync(&png, &badges, &font, 85, pos, BadgeStyle::Vertical, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, 1280, 1.0, BadgeSize::Medium, x, y).unwrap()
        };

        // TopRight anchors to both a horizontal and vertical edge, so both insets
        // move the badges (the JPEG encoder is deterministic, so bytes differ).
        assert_ne!(render(BadgePosition::TopRight, 0, 0), render(BadgePosition::TopRight, 10, 0));
        assert_ne!(render(BadgePosition::TopRight, 0, 0), render(BadgePosition::TopRight, 0, 10));

        // TopCenter is horizontally centered → the horizontal inset is a no-op,
        // but the vertical inset still applies.
        assert_eq!(render(BadgePosition::TopCenter, 0, 0), render(BadgePosition::TopCenter, 10, 0));
        assert_ne!(render(BadgePosition::TopCenter, 0, 0), render(BadgePosition::TopCenter, 0, 10));

        // Right is vertically centered → the vertical inset is a no-op, but the
        // horizontal inset still applies.
        assert_eq!(render(BadgePosition::Right, 0, 0), render(BadgePosition::Right, 0, 10));
        assert_ne!(render(BadgePosition::Right, 0, 0), render(BadgePosition::Right, 10, 0));
    }

    // --- Episode rendering tests ---

    #[test]
    fn render_episode_no_badges() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(780, 439);
        let result = render_episode_sync(&png, &[], &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Official, BadgeAppearance::default(), BadgeDirection::Vertical, 780, 1.0, BadgeSize::Large, false).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_episode_with_badges() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(780, 439);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Tmdb, value: "85%".to_string() },
        ];
        let result = render_episode_sync(&png, &badges, &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Official, BadgeAppearance::default(), BadgeDirection::Vertical, 780, 1.0, BadgeSize::Large, false).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_episode_with_blur() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(780, 439);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
        ];
        let result = render_episode_sync(&png, &badges, &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Official, BadgeAppearance::default(), BadgeDirection::Vertical, 780, 1.0, BadgeSize::Large, true).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_episode_downscales_wide_image() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(1920, 1080);
        let result = render_episode_sync(&png, &[], &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Official, BadgeAppearance::default(), BadgeDirection::Vertical, 780, 1.0, BadgeSize::Large, false).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_episode_invalid_bytes() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_episode_sync(b"not an image", &[], &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Official, BadgeAppearance::default(), BadgeDirection::Vertical, 780, 1.0, BadgeSize::Large, false);
        assert!(result.is_err());
    }

    #[test]
    fn render_poster_top_center_produces_valid_jpeg() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png_bytes = test_png(500, 750);
        let badges = vec![
            RatingBadge {
                source: RatingSource::Imdb,
                value: "8.5".to_string(),
            },
        ];
        let result = render_poster_sync(&png_bytes, &badges, &font, 85, BadgePosition::TopCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }



    #[test]
    fn render_poster_left_position_produces_valid_jpeg() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png_bytes = test_png(500, 750);
        let badges = vec![
            RatingBadge {
                source: RatingSource::Imdb,
                value: "8.5".to_string(),
            },
        ];
        let result = render_poster_sync(&png_bytes, &badges, &font, 85, BadgePosition::Left, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_poster_right_position_produces_valid_jpeg() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png_bytes = test_png(500, 750);
        let badges = vec![
            RatingBadge {
                source: RatingSource::Imdb,
                value: "8.5".to_string(),
            },
        ];
        let result = render_poster_sync(&png_bytes, &badges, &font, 85, BadgePosition::Right, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_poster_with_icon_label_style() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png_bytes = test_png(500, 750);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "92%".to_string() },
        ];
        let result = render_poster_sync(&png_bytes, &badges, &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Icon, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_poster_vertical_badge_direction() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png_bytes = test_png(500, 750);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "92%".to_string() },
        ];
        // vertical direction at bottom-center
        let result = render_poster_sync(&png_bytes, &badges, &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);

        // vertical direction at top-left corner
        let result = render_poster_sync(&png_bytes, &badges, &font, 85, BadgePosition::TopLeft, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);

        // vertical direction at bottom-right corner
        let result = render_poster_sync(&png_bytes, &badges, &font, 85, BadgePosition::BottomRight, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_logo_with_icon_label_style() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(400, 100);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Tmdb, value: "85%".to_string() },
        ];
        let result = render_logo_sync(&png, &badges, &font, BadgeStyle::Horizontal, LabelStyle::Icon, BadgeAppearance::default(), 500, 1.0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(&result[..4], &[0x89, b'P', b'N', b'G']);
    }

    #[test]
    fn render_backdrop_with_icon_label_style() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(1280, 720);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "9.0".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "95%".to_string() },
        ];
        let result = render_backdrop_sync(&png, &badges, &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Icon, BadgeAppearance::default(), BadgeDirection::Vertical, 1280, 1.0, BadgeSize::Medium, 0, 0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_poster_with_official_label_style() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png_bytes = test_png(500, 750);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "92%".to_string() },
            RatingBadge { source: RatingSource::RtAudience, value: "45%".to_string() },
        ];
        let result = render_poster_sync(&png_bytes, &badges, &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Official, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    #[test]
    fn render_logo_with_official_label_style() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(400, 100);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Tmdb, value: "85%".to_string() },
        ];
        let result = render_logo_sync(&png, &badges, &font, BadgeStyle::Horizontal, LabelStyle::Official, BadgeAppearance::default(), 500, 1.0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(&result[..4], &[0x89, b'P', b'N', b'G']);
    }

    #[test]
    fn render_backdrop_with_official_label_style() {
        use crate::services::ratings::{RatingBadge, RatingSource};

        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(1280, 720);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "9.0".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "95%".to_string() },
            RatingBadge { source: RatingSource::RtAudience, value: "40%".to_string() },
        ];
        let result = render_backdrop_sync(&png, &badges, &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Official, BadgeAppearance::default(), BadgeDirection::Vertical, 1280, 1.0, BadgeSize::Medium, 0, 0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    fn dummy_tmdb() -> crate::services::tmdb::TmdbClient {
        crate::services::tmdb::TmdbClient::new("test".to_string(), reqwest::Client::new())
    }

    #[tokio::test]
    async fn generate_poster_acquires_semaphore() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(100, 150);
        let sem = Arc::new(Semaphore::new(2));
        let tmdb = dummy_tmdb();

        let result = generate_poster(ImageParams {
            poster_bytes_override: Some(png),
            poster_path: "",
            badges: &[],
            tmdb: &tmdb,
            font: &font,
            quality: 85,
            cache_dir: "/tmp",
            image_stale_secs: 3600,
            poster_position: BadgePosition::BottomCenter,
            badge_style: BadgeStyle::Horizontal,
            label_style: LabelStyle::Text,
            badge_appearance: BadgeAppearance::default(),
            badge_direction: BadgeDirection::Horizontal,
            poster_badge_split: false,
            poster_fit: PosterFit::Native,
            render_semaphore: sem.clone(),
            target_width: 500,
            badge_scale: 1.0,
            tmdb_size: Arc::from("w500"),
            badge_size: BadgeSize::Medium,
            external_cache_only: false,
        })
        .await;

        assert!(result.is_ok());
        // Permit should be released after render
        assert_eq!(sem.available_permits(), 2);
    }

    #[tokio::test]
    async fn generate_poster_closed_semaphore_returns_error() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(100, 150);
        let sem = Arc::new(Semaphore::new(1));
        sem.close();
        let tmdb = dummy_tmdb();

        let result = generate_poster(ImageParams {
            poster_bytes_override: Some(png),
            poster_path: "",
            badges: &[],
            tmdb: &tmdb,
            font: &font,
            quality: 85,
            cache_dir: "/tmp",
            image_stale_secs: 3600,
            poster_position: BadgePosition::BottomCenter,
            badge_style: BadgeStyle::Horizontal,
            label_style: LabelStyle::Text,
            badge_appearance: BadgeAppearance::default(),
            badge_direction: BadgeDirection::Horizontal,
            poster_badge_split: false,
            poster_fit: PosterFit::Native,
            render_semaphore: sem,
            target_width: 500,
            badge_scale: 1.0,
            tmdb_size: Arc::from("w500"),
            badge_size: BadgeSize::Medium,
            external_cache_only: false,
        })
        .await;

        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("render queue closed"), "expected 'render queue closed', got: {err_msg}");
    }

    #[tokio::test]
    async fn generate_logo_acquires_and_releases_semaphore() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(200, 80);
        let sem = Arc::new(Semaphore::new(1));

        let result = generate_logo(png, vec![], font, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), sem.clone(), 500, 1.0).await;
        assert!(result.is_ok());
        assert_eq!(sem.available_permits(), 1);
    }

    #[tokio::test]
    async fn generate_logo_closed_semaphore_returns_error() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(200, 80);
        let sem = Arc::new(Semaphore::new(1));
        sem.close();

        let result = generate_logo(png, vec![], font, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), sem, 500, 1.0).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn generate_backdrop_acquires_and_releases_semaphore() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(640, 360);
        let sem = Arc::new(Semaphore::new(1));

        let result = generate_backdrop(png, vec![], font, 85, BadgePosition::TopRight, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, sem.clone(), 1280, 1.0, BadgeSize::Medium, 0, 0).await;
        assert!(result.is_ok());
        assert_eq!(sem.available_permits(), 1);
    }

    #[tokio::test]
    async fn generate_backdrop_closed_semaphore_returns_error() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(640, 360);
        let sem = Arc::new(Semaphore::new(1));
        sem.close();

        let result = generate_backdrop(png, vec![], font, 85, BadgePosition::TopRight, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, sem, 1280, 1.0, BadgeSize::Medium, 0, 0).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn semaphore_bounds_concurrent_logo_renders() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let sem = Arc::new(Semaphore::new(1));

        // Acquire the only permit
        let permit = sem.clone().acquire_owned().await.unwrap();

        let png = test_png(200, 80);
        let sem2 = sem.clone();
        let font2 = font.clone();

        // Spawn a render that should block waiting for the permit
        let handle = tokio::spawn(async move {
            generate_logo(png, vec![], font2, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), sem2, 500, 1.0).await
        });

        // Give the task a moment to start and block
        tokio::task::yield_now().await;
        assert_eq!(sem.available_permits(), 0, "permit should still be held");

        // Release the permit so the render can proceed
        drop(permit);
        let result = handle.await.unwrap();
        assert!(result.is_ok());
        assert_eq!(sem.available_permits(), 1);
    }

    #[test]
    fn render_poster_at_large_target_width() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(500, 750);
        // Render at large size (1280 width, ~2.2x badge scale)
        let result = render_poster_sync(&png, &[], &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 1280, 2.2, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
        // Verify the output is wider than a default-size render
        let img = image::load_from_memory(&result).unwrap();
        assert_eq!(img.width(), 1280);
    }

    #[test]
    fn render_poster_with_badges_at_large_scale() {
        use crate::services::ratings::{RatingBadge, RatingSource};
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(500, 750);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "92%".to_string() },
        ];
        let result = render_poster_sync(&png, &badges, &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 1280, 2.2, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        let img = image::load_from_memory(&result).unwrap();
        assert_eq!(img.width(), 1280);
    }

    #[test]
    fn render_poster_with_large_badge_size() {
        use crate::services::ratings::{RatingBadge, RatingSource};
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(500, 750);
        let badges = vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "92%".to_string() },
            RatingBadge { source: RatingSource::Tmdb, value: "85%".to_string() },
        ];
        // Large badge size with horizontal style — should use max 2 per row
        let result = render_poster_sync(&png, &badges, &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Large, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);

        // Extra-large badge size with vertical style — should use max 4 per row
        let result = render_poster_sync(&png, &badges, &font, 85, BadgePosition::BottomCenter, BadgeStyle::Vertical, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal, 500, 1.0, BadgeSize::ExtraLarge, false, PosterFit::Native).unwrap();
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }

    /// Compute the centroid (center of mass) of non-background pixels in a
    /// rendered poster JPEG. The base image is uniform gray (128,128,128), so
    /// any pixel that deviates significantly is part of a badge overlay.
    /// Returns (centroid_x, centroid_y) as fractions of image dimensions (0.0–1.0).
    fn badge_centroid(jpeg_bytes: &[u8]) -> (f64, f64) {
        let img = image::load_from_memory(jpeg_bytes).unwrap().to_rgba8();
        let (w, h) = (img.width() as f64, img.height() as f64);
        let (mut sx, mut sy, mut count) = (0u64, 0u64, 0u64);
        for (x, y, px) in img.enumerate_pixels() {
            // JPEG compression blurs edges, so use a generous threshold
            let diff = (px[0] as i32 - 128).abs()
                .max((px[1] as i32 - 128).abs())
                .max((px[2] as i32 - 128).abs());
            if diff > 20 {
                sx += x as u64;
                sy += y as u64;
                count += 1;
            }
        }
        assert!(count > 0, "no badge pixels found");
        (sx as f64 / count as f64 / w, sy as f64 / count as f64 / h)
    }

    fn position_test_badges() -> Vec<crate::services::ratings::RatingBadge> {
        use crate::services::ratings::{RatingBadge, RatingSource};
        vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Tmdb, value: "85%".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "92%".to_string() },
        ]
    }

    #[test]
    fn badge_position_top_center_places_badges_in_top_region() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_poster_sync(&test_png(500, 750), &position_test_badges(), &font, 85,
            BadgePosition::TopCenter, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        let (cx, cy) = badge_centroid(&result);
        assert!(cy < 0.33, "TopCenter: badge y-centroid {cy:.2} should be in top third");
        assert!(cx > 0.3 && cx < 0.7, "TopCenter: badge x-centroid {cx:.2} should be centered");
    }

    #[test]
    fn badge_position_bottom_center_places_badges_in_bottom_region() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_poster_sync(&test_png(500, 750), &position_test_badges(), &font, 85,
            BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        let (cx, cy) = badge_centroid(&result);
        assert!(cy > 0.67, "BottomCenter: badge y-centroid {cy:.2} should be in bottom third");
        assert!(cx > 0.3 && cx < 0.7, "BottomCenter: badge x-centroid {cx:.2} should be centered");
    }

    #[test]
    fn badge_position_left_places_badges_on_left_side() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_poster_sync(&test_png(500, 750), &position_test_badges(), &font, 85,
            BadgePosition::Left, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Vertical, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        let (cx, cy) = badge_centroid(&result);
        assert!(cx < 0.5, "Left: badge x-centroid {cx:.2} should be in left half");
        assert!(cy > 0.25 && cy < 0.75, "Left: badge y-centroid {cy:.2} should be vertically centered");
    }

    #[test]
    fn badge_position_right_places_badges_on_right_side() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_poster_sync(&test_png(500, 750), &position_test_badges(), &font, 85,
            BadgePosition::Right, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Vertical, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        let (cx, cy) = badge_centroid(&result);
        assert!(cx > 0.5, "Right: badge x-centroid {cx:.2} should be in right half");
        assert!(cy > 0.25 && cy < 0.75, "Right: badge y-centroid {cy:.2} should be vertically centered");
    }

    #[test]
    fn badge_position_top_left_places_badges_in_top_left_quadrant() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_poster_sync(&test_png(500, 750), &position_test_badges(), &font, 85,
            BadgePosition::TopLeft, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Vertical, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        let (cx, cy) = badge_centroid(&result);
        assert!(cx < 0.5, "TopLeft: badge x-centroid {cx:.2} should be in left half");
        assert!(cy < 0.5, "TopLeft: badge y-centroid {cy:.2} should be in top half");
    }

    #[test]
    fn badge_position_bottom_right_places_badges_in_bottom_right_quadrant() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let result = render_poster_sync(&test_png(500, 750), &position_test_badges(), &font, 85,
            BadgePosition::BottomRight, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Vertical, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        let (cx, cy) = badge_centroid(&result);
        assert!(cx > 0.5, "BottomRight: badge x-centroid {cx:.2} should be in right half");
        assert!(cy > 0.5, "BottomRight: badge y-centroid {cy:.2} should be in bottom half");
    }

    /// Count non-background badge pixels in each half of a rendered poster.
    /// Returns (top, bottom, left, right) counts. Base art is uniform gray.
    fn badge_pixel_halves(jpeg_bytes: &[u8]) -> (u64, u64, u64, u64) {
        let img = image::load_from_memory(jpeg_bytes).unwrap().to_rgba8();
        let (w, h) = (img.width(), img.height());
        let (mut top, mut bottom, mut left, mut right) = (0u64, 0u64, 0u64, 0u64);
        for (x, y, px) in img.enumerate_pixels() {
            let diff = (px[0] as i32 - 128).abs()
                .max((px[1] as i32 - 128).abs())
                .max((px[2] as i32 - 128).abs());
            if diff > 20 {
                if y < h / 2 { top += 1; } else { bottom += 1; }
                if x < w / 2 { left += 1; } else { right += 1; }
            }
        }
        (top, bottom, left, right)
    }

    fn split_test_badges() -> Vec<crate::services::ratings::RatingBadge> {
        use crate::services::ratings::{RatingBadge, RatingSource};
        vec![
            RatingBadge { source: RatingSource::Imdb, value: "8.5".to_string() },
            RatingBadge { source: RatingSource::Tmdb, value: "85%".to_string() },
            RatingBadge { source: RatingSource::Rt, value: "92%".to_string() },
            RatingBadge { source: RatingSource::Metacritic, value: "78".to_string() },
        ]
    }

    #[test]
    fn split_horizontal_places_badges_top_and_bottom() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        // Horizontal rows at bottom-center, split on → half top, half bottom.
        let result = render_poster_sync(&test_png(500, 750), &split_test_badges(), &font, 85,
            BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, true, PosterFit::Native).unwrap();
        let (top, bottom, _l, _r) = badge_pixel_halves(&result);
        assert!(top > 0, "split: expected badge pixels in the top half, got {top}");
        assert!(bottom > 0, "split: expected badge pixels in the bottom half, got {bottom}");

        // Without split, the same config keeps every badge in the bottom half.
        let unsplit = render_poster_sync(&test_png(500, 750), &split_test_badges(), &font, 85,
            BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, false, PosterFit::Native).unwrap();
        let (top_u, _b, _l, _r) = badge_pixel_halves(&unsplit);
        assert_eq!(top_u, 0, "no-split: expected no badge pixels in the top half, got {top_u}");
    }

    #[test]
    fn split_vertical_places_badges_left_and_right() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        // Vertical column, split on → half left, half right.
        let result = render_poster_sync(&test_png(500, 750), &split_test_badges(), &font, 85,
            BadgePosition::Left, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Vertical, 500, 1.0, BadgeSize::Medium, true, PosterFit::Native).unwrap();
        let (_t, _b, left, right) = badge_pixel_halves(&result);
        assert!(left > 0, "split: expected badge pixels in the left half, got {left}");
        assert!(right > 0, "split: expected badge pixels in the right half, got {right}");
    }

    #[test]
    fn split_single_badge_does_not_split() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let badges = vec![crate::services::ratings::RatingBadge {
            source: crate::services::ratings::RatingSource::Imdb,
            value: "8.5".to_string(),
        }];
        // Split requested but only one badge → behaves like no split (bottom only).
        let result = render_poster_sync(&test_png(500, 750), &badges, &font, 85,
            BadgePosition::BottomCenter, BadgeStyle::Horizontal, LabelStyle::Text,
            BadgeAppearance::default(),
            BadgeDirection::Horizontal, 500, 1.0, BadgeSize::Medium, true, PosterFit::Native).unwrap();
        let (top, bottom, _l, _r) = badge_pixel_halves(&result);
        assert_eq!(top, 0, "single badge: nothing should move to the top half, got {top}");
        assert!(bottom > 0, "single badge: badge should remain in the bottom half, got {bottom}");
    }

    /// Decode a rendered poster and return its (width, height).
    fn rendered_dims(bytes: &[u8]) -> (u32, u32) {
        let img = image::load_from_memory(bytes).unwrap();
        (img.width(), img.height())
    }

    fn render_with_fit(src: &[u8], target_width: u32, fit: PosterFit) -> Vec<u8> {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        render_poster_sync(
            src, &[], &font, 85, BadgePosition::BottomCenter, BadgeStyle::Horizontal,
            LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Horizontal,
            target_width, 1.0, BadgeSize::Medium, false, fit,
        )
        .unwrap()
    }

    #[test]
    fn poster_fit_cover_normalizes_non_2_3_to_2_3() {
        // A square (1:1) source is the kind of art that downstream apps crop.
        let out = render_with_fit(&test_png(600, 600), 580, PosterFit::Cover);
        assert_eq!(rendered_dims(&out), (580, 870), "cover must produce an exact 2:3 frame");
    }

    #[test]
    fn poster_fit_pad_normalizes_non_2_3_to_2_3() {
        let out = render_with_fit(&test_png(900, 600), 580, PosterFit::Pad);
        assert_eq!(rendered_dims(&out), (580, 870), "pad must produce an exact 2:3 frame");
    }

    #[test]
    fn poster_fit_blur_normalizes_non_2_3_to_2_3() {
        let out = render_with_fit(&test_png(600, 600), 580, PosterFit::Blur);
        assert_eq!(rendered_dims(&out), (580, 870), "blur must produce an exact 2:3 frame");
    }

    #[test]
    fn poster_fit_native_preserves_source_ratio() {
        // Native keeps the legacy behavior: scale to width, keep the source ratio.
        let square = render_with_fit(&test_png(600, 600), 580, PosterFit::Native);
        assert_eq!(rendered_dims(&square), (580, 580), "native keeps a 1:1 source 1:1");
        let wide = render_with_fit(&test_png(900, 600), 580, PosterFit::Native);
        // round(600 * 580 / 900) = 387
        assert_eq!(rendered_dims(&wide), (580, 387), "native keeps a 3:2 source ratio");
    }

    #[test]
    fn poster_fit_already_2_3_unchanged_dims_across_modes() {
        for fit in [PosterFit::Native, PosterFit::Cover, PosterFit::Pad, PosterFit::Blur] {
            let out = render_with_fit(&test_png(500, 750), 580, fit);
            assert_eq!(rendered_dims(&out), (580, 870), "2:3 source stays 2:3 for {fit:?}");
        }
    }

    #[test]
    fn render_logo_at_large_target_width() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(200, 80);
        let result = render_logo_sync(&png, &[], &font, BadgeStyle::Horizontal, LabelStyle::Text, BadgeAppearance::default(), 1722, 2.2).unwrap();
        assert!(!result.is_empty());
        assert_eq!(&result[..4], &[0x89, b'P', b'N', b'G']);
    }

    #[test]
    fn render_backdrop_at_large_target_width() {
        let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
        let png = test_png(640, 360);
        let result = render_backdrop_sync(&png, &[], &font, 85, BadgePosition::TopRight, BadgeStyle::Vertical, LabelStyle::Text, BadgeAppearance::default(), BadgeDirection::Vertical, 3840, 2.0, BadgeSize::Medium, 0, 0).unwrap();
        assert!(!result.is_empty());
        assert_eq!(result[0], 0xFF);
        assert_eq!(result[1], 0xD8);
    }
}