mediaschema 0.2.0

Product-agnostic media-primitive schema (buffa-generated)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
//! Polymorphic `SubtitleCue<Id, D>` — one parsed cue of a `SubtitleTrack`,
//! parameterised by a per-format payload `D` (`SrtData`, `VttData<Id>`,
//! `AssData<Id>`, `LrcData`, …).
//!
//! See `schema/subtitle_cues.md` (rev 5 — polymorphic base) for the
//! design overview and the per-format detail docs
//! (`schema/subtitle_cue_{vtt,ass,lrc}.md`) for the implemented formats.
//!
//! ## Foundation
//!
//! - [`SubtitleCue`]`<Id, D>` — generic base. Carries the format-agnostic
//!   fields (id, parent track id, ordinal, span, plain `text`) and a
//!   format-specific payload `data: D`.
//! - [`SubtitleCueKind`] — closed enum discriminating every format we
//!   plan to support. All 13 variants exist from day one so the
//!   discriminator wire/SQL value is stable; deferred variants land in
//!   issue #56.
//! - Type aliases: [`SrtCue`], [`VttCue`], [`AssCue`], [`LrcCue`].
//! - Per-format `D` data types: [`SrtData`], [`VttData`], [`AssData`],
//!   [`LrcData`].
//! - Per-track aggregate types: [`VttRegion`], [`VttStyleBlock`],
//!   [`AssStyle`], [`LrcMetadata`], [`LrcWord`].
//!
//! ## Identity / invariants
//!
//! `id` and `subtitle_track_id` are validated non-nil at construction
//! (every cue needs a real LanceDB embedding key + a real parent FK).
//! `text` is `LocalizedText` — empty (`""`) is a legal value (an
//! un-OCR'd bitmap cue, or an ASS cue whose `styled_text` carries the
//! display text). The text-presence invariant of the rev-3 design
//! has been **lifted**: a polymorphic cue's content lives in `data`,
//! not always in `text`.

use bytes::Bytes;
use derive_more::{Display, IsVariant};
use mediatime::TimeRange;
use smol_str::SmolStr;

use crate::domain::{vo::LocalizedText, Uuid7};

// ===========================================================================
// SubtitleCueKind — closed discriminator (all 13 formats, day-1 stable)
// ===========================================================================

/// Closed discriminator for [`SubtitleCue`]'s `data` payload.
///
/// Every value in this enum exists from day one so the on-disk / on-wire
/// integer discriminant is stable across releases. Variants flagged
/// **reserved** have no associated `D` data type or row mapping yet —
/// implementation is tracked in GitHub issue #56.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, IsVariant, Display)]
#[display("{}", self.as_str())]
#[non_exhaustive]
#[repr(u8)]
pub enum SubtitleCueKind {
  /// SubRip — line-only text, no detail table.
  Srt = 0,
  /// WebVTT — text + positioning + voice + region/style aggregates.
  Vtt = 1,
  /// Advanced SubStation Alpha / SubStation Alpha — `Dialogue` + Style
  /// aggregate.
  Ass = 2,
  /// MicroDVD — reserved; implementation deferred to issue #56.
  MicroDvd = 3,
  /// SubViewer — reserved; implementation deferred to issue #56.
  SubViewer = 4,
  /// YouTube SBV — reserved; implementation deferred to issue #56.
  Sbv = 5,
  /// LRC / Enhanced LRC — line + word-level lyric timing.
  Lrc = 6,
  /// Timed Text Markup Language — reserved; implementation deferred to
  /// issue #56.
  Ttml = 7,
  /// Synchronized Accessible Media Interchange — reserved; implementation
  /// deferred to issue #56.
  Sami = 8,
  /// DVD VobSub bitmap. Per-cue palette index + bitmap blob; per-track
  /// 16-entry RGB palette aggregate.
  VobSub = 9,
  /// Blu-ray PGS bitmap. Per-cue palette bytes + bitmap blob.
  Pgs = 10,
  /// CEA-608 line-21 captions. The auto-derived predicate would be
  /// `is_cea_608` (digit-snake-case); the hand-written
  /// [`Self::is_cea608`] uses the cleaner name (`Cea608` is the
  /// canonical industry spelling and can't be renamed away from the
  /// digit).
  #[is_variant(ignore)]
  Cea608 = 11,
  /// EBU STL teletext.
  EbuStl = 12,
}

impl SubtitleCueKind {
  /// True iff this is [`Self::Cea608`]. Hand-written to override the
  /// auto-derived `is_cea_608` (digit-snake-case is ugly; `Cea608` is
  /// the canonical industry name and can't be renamed).
  #[inline(always)]
  pub const fn is_cea608(&self) -> bool {
    matches!(self, Self::Cea608)
  }

  /// Numeric discriminant (stable across releases).
  #[inline(always)]
  pub const fn to_u8(self) -> u8 {
    self as u8
  }

  /// Decode the numeric discriminant.
  ///
  /// Returns `None` for an unknown value (the enum is `#[non_exhaustive]`
  /// but the wire value space is bounded by the discriminants reserved
  /// above).
  #[inline(always)]
  pub const fn try_from_u8(v: u8) -> Option<Self> {
    Some(match v {
      0 => Self::Srt,
      1 => Self::Vtt,
      2 => Self::Ass,
      3 => Self::MicroDvd,
      4 => Self::SubViewer,
      5 => Self::Sbv,
      6 => Self::Lrc,
      7 => Self::Ttml,
      8 => Self::Sami,
      9 => Self::VobSub,
      10 => Self::Pgs,
      11 => Self::Cea608,
      12 => Self::EbuStl,
      _ => return None,
    })
  }

  /// True when the kind has been implemented in this revision. All 13
  /// formats are now implemented; the predicate is kept for symmetry
  /// with future additions.
  #[inline(always)]
  pub const fn is_implemented(self) -> bool {
    matches!(
      self,
      Self::Srt
        | Self::Vtt
        | Self::Ass
        | Self::Lrc
        | Self::MicroDvd
        | Self::SubViewer
        | Self::Sbv
        | Self::Ttml
        | Self::Sami
        | Self::VobSub
        | Self::Pgs
        | Self::Cea608
        | Self::EbuStl,
    )
  }

  /// Stable snake_case slug — the canonical string form of every variant.
  ///
  /// Used for `Display`, serde tags, log keys, schema-doc references,
  /// and round-trip tests (`from_str(x.as_str()) == x` via [`from_str`](Self::from_str)).
  /// Slugs are stable across releases — the same wire/storage contract
  /// as [`to_u8`](Self::to_u8). For the two hyphenated standards
  /// (`CEA-608`, `EBU-STL`) the slug uses snake_case (`cea_608`,
  /// `ebu_stl`) for uniformity with the rest of the enum.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Srt => "srt",
      Self::Vtt => "vtt",
      Self::Ass => "ass",
      Self::MicroDvd => "micro_dvd",
      Self::SubViewer => "sub_viewer",
      Self::Sbv => "sbv",
      Self::Lrc => "lrc",
      Self::Ttml => "ttml",
      Self::Sami => "sami",
      Self::VobSub => "vob_sub",
      Self::Pgs => "pgs",
      Self::Cea608 => "cea_608",
      Self::EbuStl => "ebu_stl",
    }
  }

  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "srt" => Self::Srt,
      "vtt" => Self::Vtt,
      "ass" => Self::Ass,
      "micro_dvd" => Self::MicroDvd,
      "sub_viewer" => Self::SubViewer,
      "sbv" => Self::Sbv,
      "lrc" => Self::Lrc,
      "ttml" => Self::Ttml,
      "sami" => Self::Sami,
      "vob_sub" => Self::VobSub,
      "pgs" => Self::Pgs,
      "cea_608" => Self::Cea608,
      "ebu_stl" => Self::EbuStl,
      _ => return None,
    })
  }

  /// Primary file-on-disk extension (without the leading dot —
  /// `"srt"`, `"vtt"`, `"ass"`, …). Distinct from [`as_str`](Self::as_str),
  /// which returns the snake_case enum slug used for serialization /
  /// logging; this returns the conventional extension the format uses
  /// when written to disk as a standalone file:
  ///
  /// | variant | `as_str` | `as_extension` |
  /// |---|---|---|
  /// | `Srt` | `"srt"` | `"srt"` |
  /// | `Vtt` | `"vtt"` | `"vtt"` |
  /// | `Ass` | `"ass"` | `"ass"` |
  /// | `MicroDvd` | `"micro_dvd"` | `"sub"` |
  /// | `SubViewer` | `"sub_viewer"` | `"sub"` |
  /// | `Sbv` | `"sbv"` | `"sbv"` |
  /// | `Lrc` | `"lrc"` | `"lrc"` |
  /// | `Ttml` | `"ttml"` | `"ttml"` |
  /// | `Sami` | `"sami"` | `"smi"` |
  /// | `VobSub` | `"vob_sub"` | `"idx"` (index half of the `.idx`/`.sub` pair) |
  /// | `Pgs` | `"pgs"` | `"sup"` |
  /// | `Cea608` | `"cea_608"` | `""` (broadcast-embedded, no standalone extension) |
  /// | `EbuStl` | `"ebu_stl"` | `"stl"` |
  ///
  /// `MicroDvd` and `SubViewer` legitimately share `"sub"` — both write
  /// to that extension; the format is disambiguated by content sniffing,
  /// not by name. `Cea608` returns `""` because the captions are
  /// container-embedded (in MPEG-TS / line-21 broadcast) with no
  /// standalone disk form.
  #[inline(always)]
  pub const fn as_extension(&self) -> &'static str {
    match self {
      Self::Srt => "srt",
      Self::Vtt => "vtt",
      Self::Ass => "ass",
      Self::MicroDvd => "sub",
      Self::SubViewer => "sub",
      Self::Sbv => "sbv",
      Self::Lrc => "lrc",
      Self::Ttml => "ttml",
      Self::Sami => "smi",
      Self::VobSub => "idx",
      Self::Pgs => "sup",
      Self::Cea608 => "",
      Self::EbuStl => "stl",
    }
  }
}

// ===========================================================================
// CueData — sealed trait linking each `D` to its discriminant
// ===========================================================================

/// Sealed trait every per-format `D` payload implements; carries the
/// stable [`SubtitleCueKind`] discriminant alongside the format-specific
/// data. The sealed marker keeps the variant set closed to the crate so
/// adding a format is an additive change here, not a downstream impl.
pub trait CueData: private::Sealed {
  /// Stable discriminant for this payload.
  const KIND: SubtitleCueKind;
}

mod private {
  /// Sealed marker — only types in this module may impl [`CueData`].
  pub trait Sealed {}
}

// ===========================================================================
// SrtData — unit payload (SubRip line-only)
// ===========================================================================

/// Unit payload for SubRip cues — no per-format detail.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct SrtData;

impl SrtData {
  /// The single empty value.
  #[inline(always)]
  pub const fn new() -> Self {
    Self
  }
}

impl private::Sealed for SrtData {}
impl CueData for SrtData {
  const KIND: SubtitleCueKind = SubtitleCueKind::Srt;
}

// ===========================================================================
// VttData — WebVTT cue settings + region link + voice + styled markup
// ===========================================================================

/// WebVTT vertical direction (`vertical:lr` / `vertical:rl`). Absent
/// when the cue is horizontal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, IsVariant, Display)]
#[display("{}", self.as_str())]
#[non_exhaustive]
#[repr(u8)]
pub enum VttVertical {
  /// `vertical:lr` (left-to-right column writing — Mongolian).
  Lr = 0,
  /// `vertical:rl` (right-to-left column writing — CJK).
  Rl = 1,
}

/// WebVTT line-align value (`line:<value>,<align>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, IsVariant, Display)]
#[display("{}", self.as_str())]
#[non_exhaustive]
#[repr(u8)]
pub enum VttLineAlign {
  Start = 0,
  Center = 1,
  End = 2,
}

/// WebVTT position-align value (`position:<value>,<align>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, IsVariant, Display)]
#[display("{}", self.as_str())]
#[non_exhaustive]
#[repr(u8)]
pub enum VttPositionAlign {
  Start = 0,
  Center = 1,
  End = 2,
  LineLeft = 3,
  LineRight = 4,
}

/// WebVTT text-align (`align:<value>` cue setting).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, IsVariant, Display)]
#[display("{}", self.as_str())]
#[non_exhaustive]
#[repr(u8)]
pub enum VttTextAlign {
  Start = 0,
  Center = 1,
  End = 2,
  Left = 3,
  Right = 4,
}

macro_rules! u8_codec {
  ($name:ident, $($variant:ident = $v:literal),+ $(,)?) => {
    impl $name {
      /// Stable numeric discriminant.
      #[inline(always)]
      pub const fn to_u8(self) -> u8 { self as u8 }
      /// Decode the numeric discriminant. `None` = unknown value.
      #[inline(always)]
      pub const fn try_from_u8(v: u8) -> Option<Self> {
        Some(match v {
          $($v => Self::$variant,)+
          _ => return None,
        })
      }
    }
  };
}

/// Same shape as [`u8_codec!`] for the string slug surface — generates
/// `as_str` (`const fn -> &'static str`) and `from_str` (exact-match
/// inverse, `None` for unknown). Pairs with `#[derive(Display)]` +
/// `#[display("{}", self.as_str())]` on each enum so Display routes
/// through `as_str` per rust-type-conventions §2.
macro_rules! slug_codec {
  ($name:ident, $($variant:ident = $slug:literal),+ $(,)?) => {
    impl $name {
      /// Canonical W3C-/spec-stable slug for this variant.
      #[inline(always)]
      pub const fn as_str(&self) -> &'static str {
        match self {
          $(Self::$variant => $slug,)+
        }
      }
      /// Inverse of [`as_str`](Self::as_str). `None` for any input
      /// that isn't an exact match of one of the slugs.
      #[inline]
      pub fn from_str(s: &str) -> Option<Self> {
        Some(match s {
          $($slug => Self::$variant,)+
          _ => return None,
        })
      }
    }
  };
}

u8_codec!(VttVertical, Lr = 0, Rl = 1);
u8_codec!(VttLineAlign, Start = 0, Center = 1, End = 2);
u8_codec!(
  VttPositionAlign,
  Start = 0,
  Center = 1,
  End = 2,
  LineLeft = 3,
  LineRight = 4
);
u8_codec!(
  VttTextAlign,
  Start = 0,
  Center = 1,
  End = 2,
  Left = 3,
  Right = 4
);

// W3C-canonical slugs for the VTT cue-setting tokens — these match the
// actual VTT syntax (`vertical:lr`, `vertical:rl`, `align:start`, …),
// including the hyphenated `line-left` / `line-right` for
// `VttPositionAlign` per the WebVTT spec.
slug_codec!(VttVertical, Lr = "lr", Rl = "rl");
slug_codec!(
  VttLineAlign,
  Start = "start",
  Center = "center",
  End = "end"
);
slug_codec!(
  VttPositionAlign,
  Start = "start",
  Center = "center",
  End = "end",
  LineLeft = "line-left",
  LineRight = "line-right"
);
slug_codec!(
  VttTextAlign,
  Start = "start",
  Center = "center",
  End = "end",
  Left = "left",
  Right = "right"
);

/// WebVTT per-cue payload — cue settings + voice + styled markup +
/// optional link to a region defined on the parent track.
///
/// `line_value` / `position_value` ride as raw `SmolStr` because the
/// WebVTT spec allows both percentages (`"50%"`) and line numbers
/// (`"-2"`). Empty `""` = absent (per the no-`Option`-for-string rule).
///
/// No `Eq`: `size_value: Option<f32>` is float-typed so structural
/// equality stops at `PartialEq`.
#[derive(Debug, Clone, PartialEq)]
pub struct VttData<Id = Uuid7> {
  cue_identifier: SmolStr,
  vertical: Option<VttVertical>,
  line_value: SmolStr,
  line_align: Option<VttLineAlign>,
  position_value: SmolStr,
  position_align: Option<VttPositionAlign>,
  size_value: Option<f32>,
  text_align: Option<VttTextAlign>,
  region_id: Option<Id>,
  voice: SmolStr,
  styled_text: SmolStr,
}

impl<Id> private::Sealed for VttData<Id> {}
impl<Id> CueData for VttData<Id> {
  const KIND: SubtitleCueKind = SubtitleCueKind::Vtt;
}

impl<Id> Default for VttData<Id> {
  fn default() -> Self {
    Self::new()
  }
}

impl<Id> VttData<Id> {
  /// All-empty / all-absent value.
  #[inline(always)]
  pub const fn new() -> Self {
    Self {
      cue_identifier: SmolStr::new_inline(""),
      vertical: None,
      line_value: SmolStr::new_inline(""),
      line_align: None,
      position_value: SmolStr::new_inline(""),
      position_align: None,
      size_value: None,
      text_align: None,
      region_id: None,
      voice: SmolStr::new_inline(""),
      styled_text: SmolStr::new_inline(""),
    }
  }

  #[inline(always)]
  pub fn cue_identifier(&self) -> &str {
    self.cue_identifier.as_str()
  }
  #[inline(always)]
  pub const fn vertical(&self) -> Option<VttVertical> {
    self.vertical
  }
  #[inline(always)]
  pub fn line_value(&self) -> &str {
    self.line_value.as_str()
  }
  #[inline(always)]
  pub const fn line_align(&self) -> Option<VttLineAlign> {
    self.line_align
  }
  #[inline(always)]
  pub fn position_value(&self) -> &str {
    self.position_value.as_str()
  }
  #[inline(always)]
  pub const fn position_align(&self) -> Option<VttPositionAlign> {
    self.position_align
  }
  #[inline(always)]
  pub const fn size_value(&self) -> Option<f32> {
    self.size_value
  }
  #[inline(always)]
  pub const fn text_align(&self) -> Option<VttTextAlign> {
    self.text_align
  }
  #[inline(always)]
  pub const fn region_id_ref(&self) -> Option<&Id> {
    self.region_id.as_ref()
  }
  #[inline(always)]
  pub fn voice(&self) -> &str {
    self.voice.as_str()
  }
  #[inline(always)]
  pub fn styled_text(&self) -> &str {
    self.styled_text.as_str()
  }

  // Builders (consuming, #[must_use]).

  #[must_use]
  #[inline(always)]
  pub fn with_cue_identifier(mut self, v: impl Into<SmolStr>) -> Self {
    self.cue_identifier = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_vertical(mut self, v: VttVertical) -> Self {
    self.vertical = Some(v);
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_vertical(mut self, v: Option<VttVertical>) -> Self {
    self.vertical = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_line_value(mut self, v: impl Into<SmolStr>) -> Self {
    self.line_value = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_line_align(mut self, v: VttLineAlign) -> Self {
    self.line_align = Some(v);
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_line_align(mut self, v: Option<VttLineAlign>) -> Self {
    self.line_align = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_position_value(mut self, v: impl Into<SmolStr>) -> Self {
    self.position_value = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_position_align(mut self, v: VttPositionAlign) -> Self {
    self.position_align = Some(v);
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_position_align(mut self, v: Option<VttPositionAlign>) -> Self {
    self.position_align = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_size_value(mut self, v: f32) -> Self {
    self.size_value = Some(v);
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_size_value(mut self, v: Option<f32>) -> Self {
    self.size_value = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_text_align(mut self, v: VttTextAlign) -> Self {
    self.text_align = Some(v);
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_text_align(mut self, v: Option<VttTextAlign>) -> Self {
    self.text_align = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_region_id(mut self, v: Id) -> Self {
    self.region_id = Some(v);
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn maybe_region_id(mut self, v: Option<Id>) -> Self {
    self.region_id = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_voice(mut self, v: impl Into<SmolStr>) -> Self {
    self.voice = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_styled_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.styled_text = v.into();
    self
  }
}

// ===========================================================================
// AssData — ASS/SSA Dialogue payload
// ===========================================================================

/// ASS/SSA Dialogue payload. `style_id` is a strict FK to a row of the
/// `subtitle_track_ass_style` aggregate; parsers resolve the Style name
/// → id at parse time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssData<Id = Uuid7> {
  layer: i32,
  style_id: Id,
  name: SmolStr,
  margin_l: i32,
  margin_r: i32,
  margin_v: i32,
  effect: SmolStr,
  styled_text: SmolStr,
}

impl<Id> private::Sealed for AssData<Id> {}
impl<Id> CueData for AssData<Id> {
  const KIND: SubtitleCueKind = SubtitleCueKind::Ass;
}

impl<Id> AssData<Id> {
  /// Construct an `AssData` payload. `style_id` is mandatory — every ASS
  /// `Dialogue` line references exactly one Style. Validation of the FK
  /// is the application's responsibility (see [[validation-responsibility-boundary]]).
  #[inline]
  pub fn new(style_id: Id) -> Self {
    Self {
      layer: 0,
      style_id,
      name: SmolStr::new_inline(""),
      margin_l: 0,
      margin_r: 0,
      margin_v: 0,
      effect: SmolStr::new_inline(""),
      styled_text: SmolStr::new_inline(""),
    }
  }

  #[inline(always)]
  pub const fn layer(&self) -> i32 {
    self.layer
  }
  #[inline(always)]
  pub const fn style_id_ref(&self) -> &Id {
    &self.style_id
  }
  #[inline(always)]
  pub fn name(&self) -> &str {
    self.name.as_str()
  }
  #[inline(always)]
  pub const fn margin_l(&self) -> i32 {
    self.margin_l
  }
  #[inline(always)]
  pub const fn margin_r(&self) -> i32 {
    self.margin_r
  }
  #[inline(always)]
  pub const fn margin_v(&self) -> i32 {
    self.margin_v
  }
  #[inline(always)]
  pub fn effect(&self) -> &str {
    self.effect.as_str()
  }
  #[inline(always)]
  pub fn styled_text(&self) -> &str {
    self.styled_text.as_str()
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_layer(mut self, v: i32) -> Self {
    self.layer = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_style_id(mut self, v: Id) -> Self {
    self.style_id = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_name(mut self, v: impl Into<SmolStr>) -> Self {
    self.name = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_margin_l(mut self, v: i32) -> Self {
    self.margin_l = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_margin_r(mut self, v: i32) -> Self {
    self.margin_r = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_margin_v(mut self, v: i32) -> Self {
    self.margin_v = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_effect(mut self, v: impl Into<SmolStr>) -> Self {
    self.effect = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_styled_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.styled_text = v.into();
    self
  }
}

// ===========================================================================
// LrcData — LRC line + Enhanced word-level flag
// ===========================================================================

/// LRC per-cue payload. `has_word_timing = true` means companion rows
/// exist in `subtitle_cue_lrc_word`; `false` = line-level only.
///
/// The actual word rows live as a separate child aggregate (see
/// [`LrcWord`]); they are not embedded in this payload because a cue
/// may have hundreds of words and SQL projections want them in a
/// dedicated table.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct LrcData {
  has_word_timing: bool,
}

impl private::Sealed for LrcData {}
impl CueData for LrcData {
  const KIND: SubtitleCueKind = SubtitleCueKind::Lrc;
}

impl LrcData {
  /// Line-only LRC cue (`has_word_timing = false`).
  #[inline(always)]
  pub const fn new() -> Self {
    Self {
      has_word_timing: false,
    }
  }

  #[inline(always)]
  pub const fn has_word_timing(&self) -> bool {
    self.has_word_timing
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_word_timing(mut self) -> Self {
    self.has_word_timing = true;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_word_timing(mut self, v: bool) -> Self {
    self.has_word_timing = v;
    self
  }
  #[inline(always)]
  pub const fn set_word_timing(&mut self) -> &mut Self {
    self.has_word_timing = true;
    self
  }
  #[inline(always)]
  pub const fn update_word_timing(&mut self, v: bool) -> &mut Self {
    self.has_word_timing = v;
    self
  }
  #[inline(always)]
  pub const fn clear_word_timing(&mut self) -> &mut Self {
    self.has_word_timing = false;
    self
  }
}

// ===========================================================================
// MicroDvdData — inline `{y:i}` style codes
// ===========================================================================

/// MicroDVD per-cue payload. `styled_text` carries the inline frame-
/// based MicroDVD codes (`{y:i}`, `{c:$00FF00}`, …) verbatim; the
/// plain text rides on the base `SubtitleCue.text`.
///
/// MicroDVD has no per-track aggregate.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct MicroDvdData {
  styled_text: SmolStr,
}

impl private::Sealed for MicroDvdData {}
impl CueData for MicroDvdData {
  const KIND: SubtitleCueKind = SubtitleCueKind::MicroDvd;
}

impl MicroDvdData {
  /// Construct a MicroDVD payload with the given styled-text body
  /// (may be empty).
  #[inline]
  pub fn new(styled_text: impl Into<SmolStr>) -> Self {
    Self {
      styled_text: styled_text.into(),
    }
  }

  #[inline(always)]
  pub fn styled_text(&self) -> &str {
    self.styled_text.as_str()
  }

  #[must_use]
  #[inline(always)]
  pub fn with_styled_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.styled_text = v.into();
    self
  }
}

// ===========================================================================
// SubViewerData — `[br]`/`[b]`/`[i]`/`[u]` inline tags
// ===========================================================================

/// SubViewer per-cue payload. `styled_text` carries the SubViewer
/// inline-tag body (`[br]`, `[b]`, `[i]`, `[u]`, `{y:i}` colour codes)
/// verbatim; plain text rides on the base `SubtitleCue.text`.
///
/// SubViewer has no per-track aggregate.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct SubViewerData {
  styled_text: SmolStr,
}

impl private::Sealed for SubViewerData {}
impl CueData for SubViewerData {
  const KIND: SubtitleCueKind = SubtitleCueKind::SubViewer;
}

impl SubViewerData {
  #[inline]
  pub fn new(styled_text: impl Into<SmolStr>) -> Self {
    Self {
      styled_text: styled_text.into(),
    }
  }

  #[inline(always)]
  pub fn styled_text(&self) -> &str {
    self.styled_text.as_str()
  }

  #[must_use]
  #[inline(always)]
  pub fn with_styled_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.styled_text = v.into();
    self
  }
}

// ===========================================================================
// SbvData — unit marker (YouTube Sbv has no per-format detail)
// ===========================================================================

/// YouTube SBV unit marker payload. Plain text rides on the base
/// `SubtitleCue.text`. Stored as its own row even though empty so the
/// dispatch surface is uniform across formats (per user spec).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct SbvData;

impl SbvData {
  /// The single empty value.
  #[inline(always)]
  pub const fn new() -> Self {
    Self
  }
}

impl private::Sealed for SbvData {}
impl CueData for SbvData {
  const KIND: SubtitleCueKind = SubtitleCueKind::Sbv;
}

// ===========================================================================
// TtmlData — XML-fragment styled text + optional region / style refs
// ===========================================================================

/// TTML (Timed Text Markup Language) per-cue payload. `styled_text`
/// carries the inline XML fragment (`<span>` runs, `<br/>`, …) verbatim;
/// plain text rides on the base `SubtitleCue.text`.
///
/// `region_id` and `style_id` are optional FKs into per-track
/// [`TtmlRegion`] / [`TtmlStyle`] aggregates. `xml_id` is the cue's
/// `xml:id` attribute (the parser's stable cue-identifier handle); `""`
/// = absent (no `Option` per the empty-string-is-absent rule).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TtmlData<Id = Uuid7> {
  region_id: Option<Id>,
  style_id: Option<Id>,
  xml_id: SmolStr,
  styled_text: SmolStr,
}

impl<Id> private::Sealed for TtmlData<Id> {}
impl<Id> CueData for TtmlData<Id> {
  const KIND: SubtitleCueKind = SubtitleCueKind::Ttml;
}

impl<Id> Default for TtmlData<Id> {
  fn default() -> Self {
    Self::new()
  }
}

impl<Id> TtmlData<Id> {
  /// All-empty / all-absent value.
  #[inline]
  pub fn new() -> Self {
    Self {
      region_id: None,
      style_id: None,
      xml_id: SmolStr::new_inline(""),
      styled_text: SmolStr::new_inline(""),
    }
  }

  #[inline(always)]
  pub const fn region_id_ref(&self) -> Option<&Id> {
    self.region_id.as_ref()
  }

  #[inline(always)]
  pub const fn style_id_ref(&self) -> Option<&Id> {
    self.style_id.as_ref()
  }

  #[inline(always)]
  pub fn xml_id(&self) -> &str {
    self.xml_id.as_str()
  }

  #[inline(always)]
  pub fn styled_text(&self) -> &str {
    self.styled_text.as_str()
  }

  #[must_use]
  #[inline]
  pub fn with_region_id(mut self, v: Id) -> Self {
    self.region_id = Some(v);
    self
  }

  #[must_use]
  #[inline]
  pub fn maybe_region_id(mut self, v: Option<Id>) -> Self {
    self.region_id = v;
    self
  }

  #[must_use]
  #[inline]
  pub fn with_style_id(mut self, v: Id) -> Self {
    self.style_id = Some(v);
    self
  }

  #[must_use]
  #[inline]
  pub fn maybe_style_id(mut self, v: Option<Id>) -> Self {
    self.style_id = v;
    self
  }

  #[must_use]
  #[inline]
  pub fn with_xml_id(mut self, v: impl Into<SmolStr>) -> Self {
    self.xml_id = v.into();
    self
  }

  #[must_use]
  #[inline]
  pub fn with_styled_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.styled_text = v.into();
    self
  }
}

// ===========================================================================
// SamiData — HTML-like `<SYNC>`-block payload with per-class styling
// ===========================================================================

/// SAMI (Synchronized Accessible Media Interchange) per-cue payload.
/// `class_name` selects which per-track [`SamiStyle`] applies (e.g.
/// `ENCC` for English captions); `styled_text` carries the inline
/// HTML-like body of the `<SYNC>` block. Plain text rides on the base
/// `SubtitleCue.text`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct SamiData {
  class_name: SmolStr,
  styled_text: SmolStr,
}

impl private::Sealed for SamiData {}
impl CueData for SamiData {
  const KIND: SubtitleCueKind = SubtitleCueKind::Sami;
}

impl SamiData {
  #[inline]
  pub fn new() -> Self {
    Self::default()
  }

  #[inline(always)]
  pub fn class_name(&self) -> &str {
    self.class_name.as_str()
  }

  #[inline(always)]
  pub fn styled_text(&self) -> &str {
    self.styled_text.as_str()
  }

  #[must_use]
  #[inline]
  pub fn with_class_name(mut self, v: impl Into<SmolStr>) -> Self {
    self.class_name = v.into();
    self
  }

  #[must_use]
  #[inline]
  pub fn with_styled_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.styled_text = v.into();
    self
  }
}

// ===========================================================================
// VobSubData — DVD VobSub bitmap payload + per-cue palette/contrast indices
// ===========================================================================

/// DVD VobSub per-cue payload. Carries the rendered bitmap blob plus
/// per-cue rendering metadata (`width`/`height`/origin offset, the
/// 4-entry colour/contrast indices into the per-track palette). The
/// bitmap is run-length-encoded VobSub payload (`Bytes` to keep the
/// raw blob exact; cheap-clone refcount).
///
/// `palette_id` FKs into the per-track [`VobSubPalette`] aggregate
/// (one palette is shared by many cues on the track). The base
/// `SubtitleCue.text` stays `""` until an OCR pipeline writes plain
/// text into it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VobSubData<Id = Uuid7> {
  palette_id: Id,
  bitmap: Bytes,
  width: u32,
  height: u32,
  pos_x: i32,
  pos_y: i32,
  color_indices: [u8; 4],
  contrast_indices: [u8; 4],
}

impl<Id> private::Sealed for VobSubData<Id> {}
impl<Id> CueData for VobSubData<Id> {
  const KIND: SubtitleCueKind = SubtitleCueKind::VobSub;
}

impl<Id> VobSubData<Id> {
  /// All-empty payload with the given (required) palette FK.
  ///
  /// `width`/`height`/`pos_*`/colour-indices default to `0`; the
  /// bitmap blob defaults to empty. Use the builders to fill in.
  #[inline]
  pub fn new(palette_id: Id) -> Self {
    Self {
      palette_id,
      bitmap: Bytes::new(),
      width: 0,
      height: 0,
      pos_x: 0,
      pos_y: 0,
      color_indices: [0; 4],
      contrast_indices: [0; 4],
    }
  }

  #[inline(always)]
  pub const fn palette_id_ref(&self) -> &Id {
    &self.palette_id
  }

  #[inline(always)]
  pub const fn bitmap_ref(&self) -> &Bytes {
    &self.bitmap
  }

  #[inline(always)]
  pub const fn width(&self) -> u32 {
    self.width
  }

  #[inline(always)]
  pub const fn height(&self) -> u32 {
    self.height
  }

  #[inline(always)]
  pub const fn pos_x(&self) -> i32 {
    self.pos_x
  }

  #[inline(always)]
  pub const fn pos_y(&self) -> i32 {
    self.pos_y
  }

  #[inline(always)]
  pub const fn color_indices(&self) -> &[u8; 4] {
    &self.color_indices
  }

  #[inline(always)]
  pub const fn contrast_indices(&self) -> &[u8; 4] {
    &self.contrast_indices
  }

  #[must_use]
  #[inline]
  pub fn with_bitmap(mut self, v: impl Into<Bytes>) -> Self {
    self.bitmap = v.into();
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_width(mut self, v: u32) -> Self {
    self.width = v;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_height(mut self, v: u32) -> Self {
    self.height = v;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_pos(mut self, x: i32, y: i32) -> Self {
    self.pos_x = x;
    self.pos_y = y;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_color_indices(mut self, v: [u8; 4]) -> Self {
    self.color_indices = v;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_contrast_indices(mut self, v: [u8; 4]) -> Self {
    self.contrast_indices = v;
    self
  }
}

// ===========================================================================
// PgsData — Blu-ray PGS bitmap payload + per-cue palette bytes
// ===========================================================================

/// Blu-ray PGS per-cue payload. Unlike VobSub, PGS embeds its palette
/// per-cue (no per-track aggregate). Carries the raw bitmap blob, the
/// per-cue palette bytes (`Y/Cr/Cb/A` quadruples — opaque to the schema
/// layer), the rendered dimensions / origin offset, and the PGS
/// `composition_state` byte (`0x00`/`0x40`/`0x80`).
///
/// The base `SubtitleCue.text` stays `""` until an OCR pipeline writes
/// plain text into it.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PgsData {
  bitmap: Bytes,
  width: u32,
  height: u32,
  pos_x: i32,
  pos_y: i32,
  palette_bytes: Bytes,
  composition_state: u8,
}

impl private::Sealed for PgsData {}
impl CueData for PgsData {
  const KIND: SubtitleCueKind = SubtitleCueKind::Pgs;
}

impl PgsData {
  /// All-empty payload (zero geometry, empty bitmap + palette).
  #[inline]
  pub fn new() -> Self {
    Self::default()
  }

  #[inline(always)]
  pub const fn bitmap_ref(&self) -> &Bytes {
    &self.bitmap
  }

  #[inline(always)]
  pub const fn palette_bytes_ref(&self) -> &Bytes {
    &self.palette_bytes
  }

  #[inline(always)]
  pub const fn width(&self) -> u32 {
    self.width
  }

  #[inline(always)]
  pub const fn height(&self) -> u32 {
    self.height
  }

  #[inline(always)]
  pub const fn pos_x(&self) -> i32 {
    self.pos_x
  }

  #[inline(always)]
  pub const fn pos_y(&self) -> i32 {
    self.pos_y
  }

  #[inline(always)]
  pub const fn composition_state(&self) -> u8 {
    self.composition_state
  }

  #[must_use]
  #[inline]
  pub fn with_bitmap(mut self, v: impl Into<Bytes>) -> Self {
    self.bitmap = v.into();
    self
  }

  #[must_use]
  #[inline]
  pub fn with_palette_bytes(mut self, v: impl Into<Bytes>) -> Self {
    self.palette_bytes = v.into();
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_width(mut self, v: u32) -> Self {
    self.width = v;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_height(mut self, v: u32) -> Self {
    self.height = v;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_pos(mut self, x: i32, y: i32) -> Self {
    self.pos_x = x;
    self.pos_y = y;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_composition_state(mut self, v: u8) -> Self {
    self.composition_state = v;
    self
  }
}

// ===========================================================================
// Cea608Data — CEA-608 line-21 caption payload
// ===========================================================================

/// CEA-608 per-cue payload. `channel` selects the captioning channel
/// (`1..=4` = CC1, CC2, CC3, CC4); `pac_byte_pair` holds the raw
/// Preamble Address Code byte pair (row/colour/underline encoded);
/// `styled_text` carries the decoded line text with any inline
/// CEA-608 style codes preserved.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Cea608Data {
  channel: u8,
  pac_byte_pair: u32,
  styled_text: SmolStr,
}

impl private::Sealed for Cea608Data {}
impl CueData for Cea608Data {
  const KIND: SubtitleCueKind = SubtitleCueKind::Cea608;
}

impl Cea608Data {
  /// Validating constructor. Rejects `channel` outside `1..=4`.
  pub fn try_new(channel: u8) -> Result<Self, SubtitleCueError> {
    if !matches!(channel, 1..=4) {
      return Err(SubtitleCueError::Cea608ChannelOutOfRange(channel));
    }
    Ok(Self {
      channel,
      pac_byte_pair: 0,
      styled_text: SmolStr::new_inline(""),
    })
  }

  #[inline(always)]
  pub const fn channel(&self) -> u8 {
    self.channel
  }

  #[inline(always)]
  pub const fn pac_byte_pair(&self) -> u32 {
    self.pac_byte_pair
  }

  #[inline(always)]
  pub fn styled_text(&self) -> &str {
    self.styled_text.as_str()
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_pac_byte_pair(mut self, v: u32) -> Self {
    self.pac_byte_pair = v;
    self
  }

  #[must_use]
  #[inline]
  pub fn with_styled_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.styled_text = v.into();
    self
  }
}

// ===========================================================================
// EbuStlData — EBU STL teletext payload
// ===========================================================================

/// EBU STL per-cue payload. Mirrors a TTI (Text and Timing
/// Information) block: `subtitle_number` is the SN field, `cumulative`
/// is the Cumulative-Subtitle flag (multi-row stacked subtitles),
/// `vertical_pos` is the VP field (line on screen), `justification`
/// is the JC field (`1` = left, `2` = centre, `3` = right —
/// validated), and `styled_text` carries the decoded line with any
/// inline STL control codes preserved.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EbuStlData {
  subtitle_number: u32,
  cumulative: bool,
  vertical_pos: i32,
  justification: u8,
  styled_text: SmolStr,
}

impl private::Sealed for EbuStlData {}
impl CueData for EbuStlData {
  const KIND: SubtitleCueKind = SubtitleCueKind::EbuStl;
}

impl EbuStlData {
  /// Validating constructor. Rejects `justification` outside `1..=3`.
  pub fn try_new(justification: u8) -> Result<Self, SubtitleCueError> {
    if !matches!(justification, 1..=3) {
      return Err(SubtitleCueError::EbuStlJustificationOutOfRange(
        justification,
      ));
    }
    Ok(Self {
      subtitle_number: 0,
      cumulative: false,
      vertical_pos: 0,
      justification,
      styled_text: SmolStr::new_inline(""),
    })
  }

  #[inline(always)]
  pub const fn subtitle_number(&self) -> u32 {
    self.subtitle_number
  }

  #[inline(always)]
  pub const fn cumulative(&self) -> bool {
    self.cumulative
  }

  #[inline(always)]
  pub const fn vertical_pos(&self) -> i32 {
    self.vertical_pos
  }

  #[inline(always)]
  pub const fn justification(&self) -> u8 {
    self.justification
  }

  #[inline(always)]
  pub fn styled_text(&self) -> &str {
    self.styled_text.as_str()
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_subtitle_number(mut self, v: u32) -> Self {
    self.subtitle_number = v;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_cumulative(mut self) -> Self {
    self.cumulative = true;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn maybe_cumulative(mut self, v: bool) -> Self {
    self.cumulative = v;
    self
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_vertical_pos(mut self, v: i32) -> Self {
    self.vertical_pos = v;
    self
  }

  #[must_use]
  #[inline]
  pub fn with_styled_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.styled_text = v.into();
    self
  }
}

// ===========================================================================
// SubtitleCue<Id, D> — polymorphic base
// ===========================================================================

/// One parsed subtitle cue, parameterised by per-format payload `D`.
///
/// Construct via [`SubtitleCue::try_new`]; for the line-only SRT case
/// see the [`SrtCue::try_new_srt`] convenience constructor through the
/// type alias.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubtitleCue<Id, D> {
  id: Id,
  subtitle_track_id: Id,
  ordinal: u32,
  span: TimeRange,
  text: LocalizedText,
  data: D,
}

/// SubRip cue (no per-format detail).
pub type SrtCue<Id = Uuid7> = SubtitleCue<Id, SrtData>;
/// WebVTT cue.
pub type VttCue<Id = Uuid7> = SubtitleCue<Id, VttData<Id>>;
/// ASS/SSA Dialogue cue.
pub type AssCue<Id = Uuid7> = SubtitleCue<Id, AssData<Id>>;
/// LRC cue (line- or word-level).
pub type LrcCue<Id = Uuid7> = SubtitleCue<Id, LrcData>;
/// MicroDVD cue (frame-based inline `{y:i}` codes).
pub type MicroDvdCue<Id = Uuid7> = SubtitleCue<Id, MicroDvdData>;
/// SubViewer cue (inline `[br]`/`[b]`/`[i]`/`[u]` tags).
pub type SubViewerCue<Id = Uuid7> = SubtitleCue<Id, SubViewerData>;
/// YouTube SBV cue (unit marker, plain-text only).
pub type SbvCue<Id = Uuid7> = SubtitleCue<Id, SbvData>;
/// TTML cue.
pub type TtmlCue<Id = Uuid7> = SubtitleCue<Id, TtmlData<Id>>;
/// SAMI cue.
pub type SamiCue<Id = Uuid7> = SubtitleCue<Id, SamiData>;
/// DVD VobSub bitmap cue.
pub type VobSubCue<Id = Uuid7> = SubtitleCue<Id, VobSubData<Id>>;
/// Blu-ray PGS bitmap cue.
pub type PgsCue<Id = Uuid7> = SubtitleCue<Id, PgsData>;
/// CEA-608 caption cue.
pub type Cea608Cue<Id = Uuid7> = SubtitleCue<Id, Cea608Data>;
/// EBU STL teletext cue.
pub type EbuStlCue<Id = Uuid7> = SubtitleCue<Id, EbuStlData>;

// ===========================================================================
// SubtitleCueDetails<Id> — runtime-tagged union of every implemented payload
// ===========================================================================

/// Runtime-tagged union over every implemented per-format payload.
///
/// `SubtitleCue<Id, D>` is open over `D` so each format keeps its own
/// strongly-typed payload at the type level. Wire / sqlx / mongodb
/// decoders that don't know the format at compile time decode into
/// `SubtitleCue<Id, SubtitleCueDetails<Id>>`; callers `match` on the
/// variant to recover the typed payload.
///
/// Implements [`CueData`] but the [`CueData::KIND`] constant is
/// [`SubtitleCueKind::Srt`] — the constant is a per-type contract and
/// is not consulted for polymorphic cues. Use [`Self::kind`] (or
/// [`SubtitleCue::data_ref`] + [`Self::kind`]) at runtime instead.
#[derive(Debug, Clone, PartialEq, IsVariant)]
#[non_exhaustive]
pub enum SubtitleCueDetails<Id = Uuid7> {
  /// SubRip payload (unit marker).
  Srt(SrtData),
  /// WebVTT payload.
  Vtt(VttData<Id>),
  /// ASS/SSA Dialogue payload.
  Ass(AssData<Id>),
  /// LRC payload (line-level + word-timing flag).
  Lrc(LrcData),
  /// MicroDVD payload.
  MicroDvd(MicroDvdData),
  /// SubViewer payload.
  SubViewer(SubViewerData),
  /// YouTube SBV payload (unit marker).
  Sbv(SbvData),
  /// TTML payload.
  Ttml(TtmlData<Id>),
  /// SAMI payload.
  Sami(SamiData),
  /// DVD VobSub bitmap payload.
  VobSub(VobSubData<Id>),
  /// Blu-ray PGS bitmap payload.
  Pgs(PgsData),
  /// CEA-608 caption payload.
  Cea608(Cea608Data),
  /// EBU STL teletext payload.
  EbuStl(EbuStlData),
}

impl<Id> private::Sealed for SubtitleCueDetails<Id> {}
impl<Id> CueData for SubtitleCueDetails<Id> {
  // Placeholder — see the type-level doc; callers route through
  // `SubtitleCueDetails::kind` at runtime.
  const KIND: SubtitleCueKind = SubtitleCueKind::Srt;
}

impl<Id> SubtitleCueDetails<Id> {
  /// Runtime discriminant for this payload — the one that should be
  /// observed; the trait-level [`CueData::KIND`] is a placeholder for
  /// the polymorphic case (see the type-level doc).
  #[inline(always)]
  pub const fn kind(&self) -> SubtitleCueKind {
    match self {
      Self::Srt(_) => SubtitleCueKind::Srt,
      Self::Vtt(_) => SubtitleCueKind::Vtt,
      Self::Ass(_) => SubtitleCueKind::Ass,
      Self::Lrc(_) => SubtitleCueKind::Lrc,
      Self::MicroDvd(_) => SubtitleCueKind::MicroDvd,
      Self::SubViewer(_) => SubtitleCueKind::SubViewer,
      Self::Sbv(_) => SubtitleCueKind::Sbv,
      Self::Ttml(_) => SubtitleCueKind::Ttml,
      Self::Sami(_) => SubtitleCueKind::Sami,
      Self::VobSub(_) => SubtitleCueKind::VobSub,
      Self::Pgs(_) => SubtitleCueKind::Pgs,
      Self::Cea608(_) => SubtitleCueKind::Cea608,
      Self::EbuStl(_) => SubtitleCueKind::EbuStl,
    }
  }
}

impl<Id> From<MicroDvdData> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: MicroDvdData) -> Self {
    Self::MicroDvd(v)
  }
}

impl<Id> From<SubViewerData> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: SubViewerData) -> Self {
    Self::SubViewer(v)
  }
}

impl<Id> From<SbvData> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: SbvData) -> Self {
    Self::Sbv(v)
  }
}

impl<Id> From<TtmlData<Id>> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: TtmlData<Id>) -> Self {
    Self::Ttml(v)
  }
}

impl<Id> From<SamiData> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: SamiData) -> Self {
    Self::Sami(v)
  }
}

impl<Id> From<SrtData> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: SrtData) -> Self {
    Self::Srt(v)
  }
}

impl<Id> From<VttData<Id>> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: VttData<Id>) -> Self {
    Self::Vtt(v)
  }
}

impl<Id> From<AssData<Id>> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: AssData<Id>) -> Self {
    Self::Ass(v)
  }
}

impl<Id> From<LrcData> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: LrcData) -> Self {
    Self::Lrc(v)
  }
}

impl<Id> From<VobSubData<Id>> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: VobSubData<Id>) -> Self {
    Self::VobSub(v)
  }
}

impl<Id> From<PgsData> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: PgsData) -> Self {
    Self::Pgs(v)
  }
}

impl<Id> From<Cea608Data> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: Cea608Data) -> Self {
    Self::Cea608(v)
  }
}

impl<Id> From<EbuStlData> for SubtitleCueDetails<Id> {
  #[inline]
  fn from(v: EbuStlData) -> Self {
    Self::EbuStl(v)
  }
}

impl<D> SubtitleCue<Uuid7, D> {
  /// Validating constructor for the canonical `Uuid7` identity type.
  ///
  /// Rejects nil `id` and nil `subtitle_track_id`. `text` may be empty
  /// (a bitmap cue pre-OCR, or an ASS cue whose visible text rides in
  /// `data.styled_text()`).
  ///
  /// `mediatime::TimeRange::new` enforces `start <= end` by construction.
  pub fn try_new(
    id: Uuid7,
    subtitle_track_id: Uuid7,
    ordinal: u32,
    span: TimeRange,
    text: LocalizedText,
    data: D,
  ) -> Result<Self, SubtitleCueError> {
    if id.is_nil() {
      return Err(SubtitleCueError::NilId);
    }
    if subtitle_track_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleTrackId);
    }
    Ok(Self {
      id,
      subtitle_track_id,
      ordinal,
      span,
      text,
      data,
    })
  }
}

impl<Id, D> SubtitleCue<Id, D> {
  #[inline(always)]
  pub const fn id_ref(&self) -> &Id {
    &self.id
  }
  #[inline(always)]
  pub const fn subtitle_track_id_ref(&self) -> &Id {
    &self.subtitle_track_id
  }
  #[inline(always)]
  pub const fn ordinal(&self) -> u32 {
    self.ordinal
  }
  #[inline(always)]
  pub const fn span_ref(&self) -> &TimeRange {
    &self.span
  }
  #[inline(always)]
  pub const fn text_ref(&self) -> &LocalizedText {
    &self.text
  }
  #[inline(always)]
  pub const fn data_ref(&self) -> &D {
    &self.data
  }
  #[inline(always)]
  pub const fn data_mut(&mut self) -> &mut D {
    &mut self.data
  }

  /// The stable kind discriminant for this cue's payload type.
  #[inline(always)]
  pub fn kind(&self) -> SubtitleCueKind
  where
    D: CueData,
  {
    D::KIND
  }

  // -------------------------------------------------------------------
  // Builders / setters — invariant-free fields.
  // -------------------------------------------------------------------

  #[must_use]
  #[inline(always)]
  pub const fn with_ordinal(mut self, v: u32) -> Self {
    self.ordinal = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_span(mut self, v: TimeRange) -> Self {
    self.span = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_text(mut self, v: LocalizedText) -> Self {
    self.text = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_data(mut self, v: D) -> Self {
    self.data = v;
    self
  }

  #[inline(always)]
  pub const fn set_ordinal(&mut self, v: u32) -> &mut Self {
    self.ordinal = v;
    self
  }
  #[inline(always)]
  pub const fn set_span(&mut self, v: TimeRange) -> &mut Self {
    self.span = v;
    self
  }
  #[inline(always)]
  pub fn set_text(&mut self, v: LocalizedText) -> &mut Self {
    self.text = v;
    self
  }
  #[inline(always)]
  pub fn set_data(&mut self, v: D) -> &mut Self {
    self.data = v;
    self
  }
}

impl SrtCue<Uuid7> {
  /// Convenience constructor for an SRT cue (no per-format detail).
  #[inline]
  pub fn try_new_srt(
    id: Uuid7,
    subtitle_track_id: Uuid7,
    ordinal: u32,
    span: TimeRange,
    text: LocalizedText,
  ) -> Result<Self, SubtitleCueError> {
    Self::try_new(id, subtitle_track_id, ordinal, span, text, SrtData)
  }
}

// ===========================================================================
// LrcWord — child of an LRC cue (word-level timing)
// ===========================================================================

/// One word of an LRC (Enhanced) cue. `start_pts` is a media-time PTS
/// tick in the parent track's timebase; the per-word end is the next
/// word's start (or the cue's `span.end`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LrcWord<Id = Uuid7> {
  subtitle_cue_id: Id,
  ordinal: u32,
  text: SmolStr,
  start_pts: i64,
}

impl LrcWord<Uuid7> {
  /// Validating constructor.
  ///
  /// Rejects nil `subtitle_cue_id`.
  pub fn try_new(
    subtitle_cue_id: Uuid7,
    ordinal: u32,
    text: impl Into<SmolStr>,
    start_pts: i64,
  ) -> Result<Self, SubtitleCueError> {
    if subtitle_cue_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleCueId);
    }
    Ok(Self {
      subtitle_cue_id,
      ordinal,
      text: text.into(),
      start_pts,
    })
  }
}

impl<Id> LrcWord<Id> {
  #[inline(always)]
  pub const fn subtitle_cue_id_ref(&self) -> &Id {
    &self.subtitle_cue_id
  }
  #[inline(always)]
  pub const fn ordinal(&self) -> u32 {
    self.ordinal
  }
  #[inline(always)]
  pub fn text(&self) -> &str {
    self.text.as_str()
  }
  #[inline(always)]
  pub const fn start_pts(&self) -> i64 {
    self.start_pts
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_ordinal(mut self, v: u32) -> Self {
    self.ordinal = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.text = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_start_pts(mut self, v: i64) -> Self {
    self.start_pts = v;
    self
  }
}

// ===========================================================================
// VttRegion — per-track WebVTT region aggregate
// ===========================================================================

/// WebVTT region — a named viewport area cues can be assigned to via
/// `VttData::region_id`.
#[derive(Debug, Clone, PartialEq)]
pub struct VttRegion<Id = Uuid7> {
  id: Id,
  subtitle_track_id: Id,
  name: SmolStr,
  width: f32,
  lines: u32,
  region_anchor_x: f32,
  region_anchor_y: f32,
  viewport_anchor_x: f32,
  viewport_anchor_y: f32,
  scroll_up: bool,
}

impl VttRegion<Uuid7> {
  /// Validating constructor.
  ///
  /// Rejects nil `id` and nil `subtitle_track_id`.
  pub fn try_new(
    id: Uuid7,
    subtitle_track_id: Uuid7,
    name: impl Into<SmolStr>,
  ) -> Result<Self, SubtitleCueError> {
    if id.is_nil() {
      return Err(SubtitleCueError::NilId);
    }
    if subtitle_track_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleTrackId);
    }
    Ok(Self {
      id,
      subtitle_track_id,
      name: name.into(),
      width: 100.0,
      lines: 3,
      region_anchor_x: 0.0,
      region_anchor_y: 100.0,
      viewport_anchor_x: 0.0,
      viewport_anchor_y: 100.0,
      scroll_up: false,
    })
  }
}

impl<Id> VttRegion<Id> {
  #[inline(always)]
  pub const fn id_ref(&self) -> &Id {
    &self.id
  }
  #[inline(always)]
  pub const fn subtitle_track_id_ref(&self) -> &Id {
    &self.subtitle_track_id
  }
  #[inline(always)]
  pub fn name(&self) -> &str {
    self.name.as_str()
  }
  #[inline(always)]
  pub const fn width(&self) -> f32 {
    self.width
  }
  #[inline(always)]
  pub const fn lines(&self) -> u32 {
    self.lines
  }
  #[inline(always)]
  pub const fn region_anchor_x(&self) -> f32 {
    self.region_anchor_x
  }
  #[inline(always)]
  pub const fn region_anchor_y(&self) -> f32 {
    self.region_anchor_y
  }
  #[inline(always)]
  pub const fn viewport_anchor_x(&self) -> f32 {
    self.viewport_anchor_x
  }
  #[inline(always)]
  pub const fn viewport_anchor_y(&self) -> f32 {
    self.viewport_anchor_y
  }
  #[inline(always)]
  pub const fn scroll_up(&self) -> bool {
    self.scroll_up
  }

  #[must_use]
  #[inline(always)]
  pub fn with_name(mut self, v: impl Into<SmolStr>) -> Self {
    self.name = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_width(mut self, v: f32) -> Self {
    self.width = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_lines(mut self, v: u32) -> Self {
    self.lines = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_region_anchor(mut self, x: f32, y: f32) -> Self {
    self.region_anchor_x = x;
    self.region_anchor_y = y;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_viewport_anchor(mut self, x: f32, y: f32) -> Self {
    self.viewport_anchor_x = x;
    self.viewport_anchor_y = y;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_scroll_up(mut self) -> Self {
    self.scroll_up = true;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_scroll_up(mut self, v: bool) -> Self {
    self.scroll_up = v;
    self
  }
}

// ===========================================================================
// VttStyleBlock — per-track WebVTT STYLE block
// ===========================================================================

/// One WebVTT `STYLE` block of a track. Multiple style blocks per track
/// are allowed and rendered in `ordinal` order; the body is opaque CSS
/// text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VttStyleBlock<Id = Uuid7> {
  id: Id,
  subtitle_track_id: Id,
  ordinal: u32,
  css_text: SmolStr,
}

impl VttStyleBlock<Uuid7> {
  pub fn try_new(
    id: Uuid7,
    subtitle_track_id: Uuid7,
    ordinal: u32,
    css_text: impl Into<SmolStr>,
  ) -> Result<Self, SubtitleCueError> {
    if id.is_nil() {
      return Err(SubtitleCueError::NilId);
    }
    if subtitle_track_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleTrackId);
    }
    Ok(Self {
      id,
      subtitle_track_id,
      ordinal,
      css_text: css_text.into(),
    })
  }
}

impl<Id> VttStyleBlock<Id> {
  #[inline(always)]
  pub const fn id_ref(&self) -> &Id {
    &self.id
  }
  #[inline(always)]
  pub const fn subtitle_track_id_ref(&self) -> &Id {
    &self.subtitle_track_id
  }
  #[inline(always)]
  pub const fn ordinal(&self) -> u32 {
    self.ordinal
  }
  #[inline(always)]
  pub fn css_text(&self) -> &str {
    self.css_text.as_str()
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_ordinal(mut self, v: u32) -> Self {
    self.ordinal = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_css_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.css_text = v.into();
    self
  }
}

// ===========================================================================
// AssStyle — per-track ASS V4+ Style row
// ===========================================================================

/// Per-track ASS/SSA `[V4+ Styles]` row. The full set of fields a
/// `Dialogue` line references via its Style name.
#[derive(Debug, Clone, PartialEq)]
pub struct AssStyle<Id = Uuid7> {
  id: Id,
  subtitle_track_id: Id,
  name: SmolStr,
  fontname: SmolStr,
  fontsize: f32,
  primary_colour: u32,
  secondary_colour: u32,
  outline_colour: u32,
  back_colour: u32,
  bold: bool,
  italic: bool,
  underline: bool,
  strikeout: bool,
  scale_x: i32,
  scale_y: i32,
  spacing: i32,
  angle: f32,
  border_style: i16,
  outline: f32,
  shadow: f32,
  alignment: i16,
  margin_l: i32,
  margin_r: i32,
  margin_v: i32,
  encoding: i32,
}

impl AssStyle<Uuid7> {
  /// Validating constructor with required `name` (non-empty, ASS Style
  /// names are the FK key parsers resolve `AssData::style_id` from).
  pub fn try_new(
    id: Uuid7,
    subtitle_track_id: Uuid7,
    name: impl Into<SmolStr>,
  ) -> Result<Self, SubtitleCueError> {
    if id.is_nil() {
      return Err(SubtitleCueError::NilId);
    }
    if subtitle_track_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleTrackId);
    }
    let name: SmolStr = name.into();
    if name.is_empty() {
      return Err(SubtitleCueError::EmptyAssStyleName);
    }
    Ok(Self {
      id,
      subtitle_track_id,
      name,
      fontname: SmolStr::new_inline("Arial"),
      fontsize: 20.0,
      primary_colour: 0x00FFFFFF,
      secondary_colour: 0x000000FF,
      outline_colour: 0x00000000,
      back_colour: 0x00000000,
      bold: false,
      italic: false,
      underline: false,
      strikeout: false,
      scale_x: 100,
      scale_y: 100,
      spacing: 0,
      angle: 0.0,
      border_style: 1,
      outline: 2.0,
      shadow: 0.0,
      alignment: 2,
      margin_l: 10,
      margin_r: 10,
      margin_v: 10,
      encoding: 1,
    })
  }
}

impl<Id> AssStyle<Id> {
  #[inline(always)]
  pub const fn id_ref(&self) -> &Id {
    &self.id
  }
  #[inline(always)]
  pub const fn subtitle_track_id_ref(&self) -> &Id {
    &self.subtitle_track_id
  }
  #[inline(always)]
  pub fn name(&self) -> &str {
    self.name.as_str()
  }
  #[inline(always)]
  pub fn fontname(&self) -> &str {
    self.fontname.as_str()
  }
  #[inline(always)]
  pub const fn fontsize(&self) -> f32 {
    self.fontsize
  }
  #[inline(always)]
  pub const fn primary_colour(&self) -> u32 {
    self.primary_colour
  }
  #[inline(always)]
  pub const fn secondary_colour(&self) -> u32 {
    self.secondary_colour
  }
  #[inline(always)]
  pub const fn outline_colour(&self) -> u32 {
    self.outline_colour
  }
  #[inline(always)]
  pub const fn back_colour(&self) -> u32 {
    self.back_colour
  }
  #[inline(always)]
  pub const fn bold(&self) -> bool {
    self.bold
  }
  #[inline(always)]
  pub const fn italic(&self) -> bool {
    self.italic
  }
  #[inline(always)]
  pub const fn underline(&self) -> bool {
    self.underline
  }
  #[inline(always)]
  pub const fn strikeout(&self) -> bool {
    self.strikeout
  }
  #[inline(always)]
  pub const fn scale_x(&self) -> i32 {
    self.scale_x
  }
  #[inline(always)]
  pub const fn scale_y(&self) -> i32 {
    self.scale_y
  }
  #[inline(always)]
  pub const fn spacing(&self) -> i32 {
    self.spacing
  }
  #[inline(always)]
  pub const fn angle(&self) -> f32 {
    self.angle
  }
  #[inline(always)]
  pub const fn border_style(&self) -> i16 {
    self.border_style
  }
  #[inline(always)]
  pub const fn outline(&self) -> f32 {
    self.outline
  }
  #[inline(always)]
  pub const fn shadow(&self) -> f32 {
    self.shadow
  }
  #[inline(always)]
  pub const fn alignment(&self) -> i16 {
    self.alignment
  }
  #[inline(always)]
  pub const fn margin_l(&self) -> i32 {
    self.margin_l
  }
  #[inline(always)]
  pub const fn margin_r(&self) -> i32 {
    self.margin_r
  }
  #[inline(always)]
  pub const fn margin_v(&self) -> i32 {
    self.margin_v
  }
  #[inline(always)]
  pub const fn encoding(&self) -> i32 {
    self.encoding
  }

  // Builders — typography group.
  #[must_use]
  #[inline(always)]
  pub fn with_fontname(mut self, v: impl Into<SmolStr>) -> Self {
    self.fontname = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_fontsize(mut self, v: f32) -> Self {
    self.fontsize = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_primary_colour(mut self, v: u32) -> Self {
    self.primary_colour = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_secondary_colour(mut self, v: u32) -> Self {
    self.secondary_colour = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_outline_colour(mut self, v: u32) -> Self {
    self.outline_colour = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_back_colour(mut self, v: u32) -> Self {
    self.back_colour = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_bold(mut self) -> Self {
    self.bold = true;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_bold(mut self, v: bool) -> Self {
    self.bold = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_italic(mut self) -> Self {
    self.italic = true;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_italic(mut self, v: bool) -> Self {
    self.italic = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_underline(mut self) -> Self {
    self.underline = true;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_underline(mut self, v: bool) -> Self {
    self.underline = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_strikeout(mut self) -> Self {
    self.strikeout = true;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn maybe_strikeout(mut self, v: bool) -> Self {
    self.strikeout = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_scale_x(mut self, v: i32) -> Self {
    self.scale_x = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_scale_y(mut self, v: i32) -> Self {
    self.scale_y = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_spacing(mut self, v: i32) -> Self {
    self.spacing = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_angle(mut self, v: f32) -> Self {
    self.angle = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_border_style(mut self, v: i16) -> Self {
    self.border_style = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_outline(mut self, v: f32) -> Self {
    self.outline = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_shadow(mut self, v: f32) -> Self {
    self.shadow = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_alignment(mut self, v: i16) -> Self {
    self.alignment = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_margin_l(mut self, v: i32) -> Self {
    self.margin_l = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_margin_r(mut self, v: i32) -> Self {
    self.margin_r = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_margin_v(mut self, v: i32) -> Self {
    self.margin_v = v;
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_encoding(mut self, v: i32) -> Self {
    self.encoding = v;
    self
  }
}

// ===========================================================================
// TtmlRegion — per-track TTML `<region>` element
// ===========================================================================

/// Per-track TTML `<region>` element. Cues reference a region by `id`
/// via `TtmlData::region_id`. The free-form `xml_attrs` carries the
/// region's serialised XML attribute list (`tts:origin`,
/// `tts:extent`, …) verbatim — TTML's styling vocabulary is large
/// enough that pinning each attribute as a typed column would invent
/// a parser; storing the raw fragment keeps the round trip lossless.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TtmlRegion<Id = Uuid7> {
  id: Id,
  subtitle_track_id: Id,
  xml_id: SmolStr,
  xml_attrs: SmolStr,
}

impl TtmlRegion<Uuid7> {
  pub fn try_new(
    id: Uuid7,
    subtitle_track_id: Uuid7,
    xml_id: impl Into<SmolStr>,
  ) -> Result<Self, SubtitleCueError> {
    if id.is_nil() {
      return Err(SubtitleCueError::NilId);
    }
    if subtitle_track_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleTrackId);
    }
    Ok(Self {
      id,
      subtitle_track_id,
      xml_id: xml_id.into(),
      xml_attrs: SmolStr::new_inline(""),
    })
  }
}

impl<Id> TtmlRegion<Id> {
  #[inline(always)]
  pub const fn id_ref(&self) -> &Id {
    &self.id
  }
  #[inline(always)]
  pub const fn subtitle_track_id_ref(&self) -> &Id {
    &self.subtitle_track_id
  }
  #[inline(always)]
  pub fn xml_id(&self) -> &str {
    self.xml_id.as_str()
  }
  #[inline(always)]
  pub fn xml_attrs(&self) -> &str {
    self.xml_attrs.as_str()
  }

  #[must_use]
  #[inline]
  pub fn with_xml_attrs(mut self, v: impl Into<SmolStr>) -> Self {
    self.xml_attrs = v.into();
    self
  }
}

// ===========================================================================
// TtmlStyle — per-track TTML `<style>` element
// ===========================================================================

/// Per-track TTML `<style>` element. Cues reference a style by `id`
/// via `TtmlData::style_id`. Like [`TtmlRegion`], the styling
/// vocabulary is stored verbatim in `xml_attrs`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TtmlStyle<Id = Uuid7> {
  id: Id,
  subtitle_track_id: Id,
  xml_id: SmolStr,
  xml_attrs: SmolStr,
}

impl TtmlStyle<Uuid7> {
  pub fn try_new(
    id: Uuid7,
    subtitle_track_id: Uuid7,
    xml_id: impl Into<SmolStr>,
  ) -> Result<Self, SubtitleCueError> {
    if id.is_nil() {
      return Err(SubtitleCueError::NilId);
    }
    if subtitle_track_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleTrackId);
    }
    Ok(Self {
      id,
      subtitle_track_id,
      xml_id: xml_id.into(),
      xml_attrs: SmolStr::new_inline(""),
    })
  }
}

impl<Id> TtmlStyle<Id> {
  #[inline(always)]
  pub const fn id_ref(&self) -> &Id {
    &self.id
  }
  #[inline(always)]
  pub const fn subtitle_track_id_ref(&self) -> &Id {
    &self.subtitle_track_id
  }
  #[inline(always)]
  pub fn xml_id(&self) -> &str {
    self.xml_id.as_str()
  }
  #[inline(always)]
  pub fn xml_attrs(&self) -> &str {
    self.xml_attrs.as_str()
  }

  #[must_use]
  #[inline]
  pub fn with_xml_attrs(mut self, v: impl Into<SmolStr>) -> Self {
    self.xml_attrs = v.into();
    self
  }
}

// ===========================================================================
// SamiStyle — per-track SAMI `<style>` class
// ===========================================================================

/// Per-track SAMI `<STYLE>` class. Cues reference a style by
/// `class_name` (the SAMI selector e.g. `ENCC`); the CSS body rides
/// in `css_text`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SamiStyle<Id = Uuid7> {
  id: Id,
  subtitle_track_id: Id,
  class_name: SmolStr,
  css_text: SmolStr,
}

impl SamiStyle<Uuid7> {
  pub fn try_new(
    id: Uuid7,
    subtitle_track_id: Uuid7,
    class_name: impl Into<SmolStr>,
  ) -> Result<Self, SubtitleCueError> {
    if id.is_nil() {
      return Err(SubtitleCueError::NilId);
    }
    if subtitle_track_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleTrackId);
    }
    Ok(Self {
      id,
      subtitle_track_id,
      class_name: class_name.into(),
      css_text: SmolStr::new_inline(""),
    })
  }
}

impl<Id> SamiStyle<Id> {
  #[inline(always)]
  pub const fn id_ref(&self) -> &Id {
    &self.id
  }
  #[inline(always)]
  pub const fn subtitle_track_id_ref(&self) -> &Id {
    &self.subtitle_track_id
  }
  #[inline(always)]
  pub fn class_name(&self) -> &str {
    self.class_name.as_str()
  }
  #[inline(always)]
  pub fn css_text(&self) -> &str {
    self.css_text.as_str()
  }

  #[must_use]
  #[inline]
  pub fn with_css_text(mut self, v: impl Into<SmolStr>) -> Self {
    self.css_text = v.into();
    self
  }
}

// ===========================================================================
// VobSubPalette — per-track DVD palette aggregate (16 RGB entries)
// ===========================================================================

/// Per-track DVD VobSub palette — 16 fixed-position RGB entries. The
/// 4-entry colour/contrast indices on a `VobSubData` cue index into
/// these. Stored as a `[u32; 16]` where each `u32` is `0x00RRGGBB`
/// (alpha is conveyed via the cue's contrast indices).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VobSubPalette<Id = Uuid7> {
  id: Id,
  subtitle_track_id: Id,
  entries: [u32; 16],
}

impl VobSubPalette<Uuid7> {
  /// Validating constructor — rejects nil id / parent track id.
  pub fn try_new(id: Uuid7, subtitle_track_id: Uuid7) -> Result<Self, SubtitleCueError> {
    if id.is_nil() {
      return Err(SubtitleCueError::NilId);
    }
    if subtitle_track_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleTrackId);
    }
    Ok(Self {
      id,
      subtitle_track_id,
      entries: [0u32; 16],
    })
  }
}

impl<Id> VobSubPalette<Id> {
  #[inline(always)]
  pub const fn id_ref(&self) -> &Id {
    &self.id
  }

  #[inline(always)]
  pub const fn subtitle_track_id_ref(&self) -> &Id {
    &self.subtitle_track_id
  }

  #[inline(always)]
  pub const fn entries(&self) -> &[u32; 16] {
    &self.entries
  }

  #[must_use]
  #[inline(always)]
  pub const fn with_entries(mut self, v: [u32; 16]) -> Self {
    self.entries = v;
    self
  }
}

// ===========================================================================
// LrcMetadata — per-track LRC header tags (1:1 with subtitle_track)
// ===========================================================================

/// Per-track LRC header metadata. Carries the `[ti:]`/`[ar:]`/… tags
/// and a global playback offset. 1:1 with the parent `SubtitleTrack`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LrcMetadata<Id = Uuid7> {
  subtitle_track_id: Id,
  title: SmolStr,
  artist: SmolStr,
  album: SmolStr,
  author: SmolStr,
  creator: SmolStr,
  length: SmolStr,
  offset_ms: i32,
}

impl LrcMetadata<Uuid7> {
  /// Validating constructor. Rejects nil `subtitle_track_id`.
  pub fn try_new(subtitle_track_id: Uuid7) -> Result<Self, SubtitleCueError> {
    if subtitle_track_id.is_nil() {
      return Err(SubtitleCueError::NilSubtitleTrackId);
    }
    Ok(Self {
      subtitle_track_id,
      title: SmolStr::new_inline(""),
      artist: SmolStr::new_inline(""),
      album: SmolStr::new_inline(""),
      author: SmolStr::new_inline(""),
      creator: SmolStr::new_inline(""),
      length: SmolStr::new_inline(""),
      offset_ms: 0,
    })
  }
}

impl<Id> LrcMetadata<Id> {
  #[inline(always)]
  pub const fn subtitle_track_id_ref(&self) -> &Id {
    &self.subtitle_track_id
  }
  #[inline(always)]
  pub fn title(&self) -> &str {
    self.title.as_str()
  }
  #[inline(always)]
  pub fn artist(&self) -> &str {
    self.artist.as_str()
  }
  #[inline(always)]
  pub fn album(&self) -> &str {
    self.album.as_str()
  }
  #[inline(always)]
  pub fn author(&self) -> &str {
    self.author.as_str()
  }
  #[inline(always)]
  pub fn creator(&self) -> &str {
    self.creator.as_str()
  }
  #[inline(always)]
  pub fn length(&self) -> &str {
    self.length.as_str()
  }
  #[inline(always)]
  pub const fn offset_ms(&self) -> i32 {
    self.offset_ms
  }

  #[must_use]
  #[inline(always)]
  pub fn with_title(mut self, v: impl Into<SmolStr>) -> Self {
    self.title = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_artist(mut self, v: impl Into<SmolStr>) -> Self {
    self.artist = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_album(mut self, v: impl Into<SmolStr>) -> Self {
    self.album = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_author(mut self, v: impl Into<SmolStr>) -> Self {
    self.author = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_creator(mut self, v: impl Into<SmolStr>) -> Self {
    self.creator = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub fn with_length(mut self, v: impl Into<SmolStr>) -> Self {
    self.length = v.into();
    self
  }
  #[must_use]
  #[inline(always)]
  pub const fn with_offset_ms(mut self, v: i32) -> Self {
    self.offset_ms = v;
    self
  }
}

// ===========================================================================
// Errors
// ===========================================================================

/// Returned when [`SubtitleCue::try_new`] or an aggregate constructor
/// cannot uphold an invariant.
#[derive(Debug, Clone, PartialEq, Eq, IsVariant, thiserror::Error)]
#[non_exhaustive]
pub enum SubtitleCueError {
  /// Supplied `id` was the nil sentinel.
  #[error("SubtitleCue id must not be the nil UUID")]
  NilId,
  /// Supplied `subtitle_track_id` was the nil sentinel.
  #[error("`subtitle_track_id` (FK → SubtitleTrack) must not be the nil UUID")]
  NilSubtitleTrackId,
  /// Supplied `subtitle_cue_id` was the nil sentinel (LrcWord child FK).
  #[error("`subtitle_cue_id` (FK → SubtitleCue) must not be the nil UUID")]
  NilSubtitleCueId,
  /// AssStyle `name` was empty (the Style name is the parser's FK key).
  #[error("AssStyle name must be non-empty")]
  EmptyAssStyleName,
  /// `Cea608Data.channel` was outside the valid `1..=4` range.
  #[error("Cea608Data.channel must be 1..=4, got {0}")]
  Cea608ChannelOutOfRange(u8),
  /// `EbuStlData.justification` was outside the valid `1..=3` range.
  #[error("EbuStlData.justification must be 1..=3, got {0}")]
  EbuStlJustificationOutOfRange(u8),
  /// A row carried a [`SubtitleCueKind`] discriminant whose `D` payload
  /// type isn't implemented in this revision (reserved for issue #56).
  #[error("subtitle cue kind `{0}` not yet implemented (issue #56)")]
  UnimplementedFormat(SubtitleCueKind),
  /// Last-resort escape hatch for descriptive text that has no
  /// structured variant.
  #[error("{0}")]
  Other(std::borrow::Cow<'static, str>),
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(all(test, feature = "std"))]
mod tests {
  use super::*;
  use mediatime::Timebase;

  fn span() -> TimeRange {
    TimeRange::new(1000, 2000, Timebase::default())
  }

  #[test]
  fn kind_discriminants_round_trip() {
    for k in [
      SubtitleCueKind::Srt,
      SubtitleCueKind::Vtt,
      SubtitleCueKind::Ass,
      SubtitleCueKind::MicroDvd,
      SubtitleCueKind::SubViewer,
      SubtitleCueKind::Sbv,
      SubtitleCueKind::Lrc,
      SubtitleCueKind::Ttml,
      SubtitleCueKind::Sami,
      SubtitleCueKind::VobSub,
      SubtitleCueKind::Pgs,
      SubtitleCueKind::Cea608,
      SubtitleCueKind::EbuStl,
    ] {
      assert_eq!(SubtitleCueKind::try_from_u8(k.to_u8()), Some(k));
    }
    assert_eq!(SubtitleCueKind::try_from_u8(13), None);
  }

  #[test]
  fn kind_implemented_flags_match_brief() {
    // All 13 formats are now implemented (issue #56 closed): 4 rev-1
    // formats (Srt/Vtt/Ass/Lrc) + 5 text formats (MicroDvd/SubViewer/
    // Sbv/Ttml/Sami) + 2 bitmap (VobSub/Pgs) + 2 broadcast (Cea608/
    // EbuStl).
    for k in [
      SubtitleCueKind::Srt,
      SubtitleCueKind::Vtt,
      SubtitleCueKind::Ass,
      SubtitleCueKind::Lrc,
      SubtitleCueKind::MicroDvd,
      SubtitleCueKind::SubViewer,
      SubtitleCueKind::Sbv,
      SubtitleCueKind::Ttml,
      SubtitleCueKind::Sami,
      SubtitleCueKind::VobSub,
      SubtitleCueKind::Pgs,
      SubtitleCueKind::Cea608,
      SubtitleCueKind::EbuStl,
    ] {
      assert!(k.is_implemented(), "{k:?} should be implemented");
    }
  }

  #[test]
  fn kind_as_str_round_trips_and_displays() {
    for (k, expected) in [
      (SubtitleCueKind::Srt, "srt"),
      (SubtitleCueKind::Vtt, "vtt"),
      (SubtitleCueKind::Ass, "ass"),
      (SubtitleCueKind::MicroDvd, "micro_dvd"),
      (SubtitleCueKind::SubViewer, "sub_viewer"),
      (SubtitleCueKind::Sbv, "sbv"),
      (SubtitleCueKind::Lrc, "lrc"),
      (SubtitleCueKind::Ttml, "ttml"),
      (SubtitleCueKind::Sami, "sami"),
      (SubtitleCueKind::VobSub, "vob_sub"),
      (SubtitleCueKind::Pgs, "pgs"),
      (SubtitleCueKind::Cea608, "cea_608"),
      (SubtitleCueKind::EbuStl, "ebu_stl"),
    ] {
      assert_eq!(k.as_str(), expected, "{:?} slug mismatch", k);
      assert_eq!(SubtitleCueKind::from_str(expected), Some(k));
      assert_eq!(format!("{k}"), expected, "{:?} Display mismatch", k);
    }
    assert_eq!(SubtitleCueKind::from_str("unknown"), None);
    assert_eq!(SubtitleCueKind::from_str(""), None);
  }

  #[test]
  fn kind_as_extension_maps_to_disk_form() {
    for (k, expected) in [
      (SubtitleCueKind::Srt, "srt"),
      (SubtitleCueKind::Vtt, "vtt"),
      (SubtitleCueKind::Ass, "ass"),
      (SubtitleCueKind::MicroDvd, "sub"),
      (SubtitleCueKind::SubViewer, "sub"),
      (SubtitleCueKind::Sbv, "sbv"),
      (SubtitleCueKind::Lrc, "lrc"),
      (SubtitleCueKind::Ttml, "ttml"),
      (SubtitleCueKind::Sami, "smi"),
      (SubtitleCueKind::VobSub, "idx"),
      (SubtitleCueKind::Pgs, "sup"),
      (SubtitleCueKind::Cea608, ""),
      (SubtitleCueKind::EbuStl, "stl"),
    ] {
      assert_eq!(k.as_extension(), expected, "{:?} extension mismatch", k);
    }
    // Slug-form mismatch is intentional: as_str("micro_dvd") != as_extension("sub").
    assert_ne!(
      SubtitleCueKind::MicroDvd.as_str(),
      SubtitleCueKind::MicroDvd.as_extension()
    );
    assert_eq!(SubtitleCueKind::Cea608.as_extension(), "");
  }

  #[test]
  fn kind_cea608_predicate_is_hand_written() {
    // `Cea608` carries `#[is_variant(ignore)]` to skip the awkward
    // auto-derived `is_cea_608`; the hand-written `is_cea608` is the
    // public predicate name.
    assert!(SubtitleCueKind::Cea608.is_cea608());
    assert!(!SubtitleCueKind::Srt.is_cea608());
    assert!(!SubtitleCueKind::EbuStl.is_cea608());
  }

  #[test]
  fn vtt_vertical_slug_round_trips_and_displays() {
    for (v, slug) in [(VttVertical::Lr, "lr"), (VttVertical::Rl, "rl")] {
      assert_eq!(v.as_str(), slug);
      assert_eq!(VttVertical::from_str(slug), Some(v));
      assert_eq!(format!("{v}"), slug);
    }
    assert_eq!(VttVertical::from_str("unknown"), None);
    assert_eq!(VttVertical::from_str(""), None);
  }

  #[test]
  fn vtt_line_align_slug_round_trips_and_displays() {
    for (v, slug) in [
      (VttLineAlign::Start, "start"),
      (VttLineAlign::Center, "center"),
      (VttLineAlign::End, "end"),
    ] {
      assert_eq!(v.as_str(), slug);
      assert_eq!(VttLineAlign::from_str(slug), Some(v));
      assert_eq!(format!("{v}"), slug);
    }
    assert_eq!(VttLineAlign::from_str("middle"), None);
  }

  #[test]
  fn vtt_position_align_slug_round_trips_and_displays() {
    for (v, slug) in [
      (VttPositionAlign::Start, "start"),
      (VttPositionAlign::Center, "center"),
      (VttPositionAlign::End, "end"),
      (VttPositionAlign::LineLeft, "line-left"),
      (VttPositionAlign::LineRight, "line-right"),
    ] {
      assert_eq!(v.as_str(), slug);
      assert_eq!(VttPositionAlign::from_str(slug), Some(v));
      assert_eq!(format!("{v}"), slug);
    }
    // W3C uses hyphen — confirm we accept ONLY the hyphenated form.
    assert_eq!(VttPositionAlign::from_str("line_left"), None);
    assert_eq!(VttPositionAlign::from_str("lineleft"), None);
  }

  #[test]
  fn vtt_text_align_slug_round_trips_and_displays() {
    for (v, slug) in [
      (VttTextAlign::Start, "start"),
      (VttTextAlign::Center, "center"),
      (VttTextAlign::End, "end"),
      (VttTextAlign::Left, "left"),
      (VttTextAlign::Right, "right"),
    ] {
      assert_eq!(v.as_str(), slug);
      assert_eq!(VttTextAlign::from_str(slug), Some(v));
      assert_eq!(format!("{v}"), slug);
    }
  }

  #[test]
  fn srt_cue_constructs_and_carries_kind() {
    let c = SrtCue::try_new_srt(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src("hello"),
    )
    .unwrap();
    assert_eq!(c.ordinal(), 0);
    assert_eq!(c.text_ref().src(), "hello");
    assert_eq!(c.kind(), SubtitleCueKind::Srt);
  }

  #[test]
  fn srt_cue_rejects_nil_id() {
    let e =
      SrtCue::try_new_srt(Uuid7::nil(), Uuid7::new(), 0, span(), LocalizedText::new()).unwrap_err();
    assert!(e.is_nil_id());
  }

  #[test]
  fn srt_cue_rejects_nil_subtitle_track_id() {
    let e =
      SrtCue::try_new_srt(Uuid7::new(), Uuid7::nil(), 0, span(), LocalizedText::new()).unwrap_err();
    assert!(e.is_nil_subtitle_track_id());
  }

  #[test]
  fn vtt_cue_constructs_and_builders_chain() {
    let region_id = Uuid7::new();
    let d = VttData::<Uuid7>::new()
      .with_cue_identifier("c1")
      .with_vertical(VttVertical::Rl)
      .with_line_value("50%")
      .with_line_align(VttLineAlign::Center)
      .with_position_value("50%")
      .with_position_align(VttPositionAlign::Center)
      .with_size_value(80.0)
      .with_text_align(VttTextAlign::Start)
      .with_region_id(region_id)
      .with_voice("Speaker A")
      .with_styled_text("<b>hi</b>");
    let c: VttCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      1,
      span(),
      LocalizedText::from_src("hi"),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::Vtt);
    assert_eq!(c.data_ref().cue_identifier(), "c1");
    assert_eq!(c.data_ref().vertical(), Some(VttVertical::Rl));
    assert_eq!(c.data_ref().region_id_ref(), Some(&region_id));
    assert_eq!(c.data_ref().voice(), "Speaker A");
  }

  #[test]
  fn ass_cue_constructs_with_style_id() {
    let style_id = Uuid7::new();
    let d = AssData::<Uuid7>::new(style_id)
      .with_layer(2)
      .with_name("Alice")
      .with_margin_l(10)
      .with_margin_r(20)
      .with_margin_v(30)
      .with_effect("karaoke")
      .with_styled_text("{\\b1}hi{\\b0}");
    let c: AssCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::new(),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::Ass);
    assert_eq!(c.data_ref().style_id_ref(), &style_id);
    assert_eq!(c.data_ref().layer(), 2);
    assert_eq!(c.data_ref().name(), "Alice");
  }

  #[test]
  fn lrc_cue_line_and_word_flag() {
    let line: LrcCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src("la la la"),
      LrcData::new(),
    )
    .unwrap();
    assert!(!line.data_ref().has_word_timing());

    let word: LrcCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src(""),
      LrcData::new().with_word_timing(),
    )
    .unwrap();
    assert!(word.data_ref().has_word_timing());
  }

  #[test]
  fn lrc_word_rejects_nil_subtitle_cue_id() {
    let e = LrcWord::try_new(Uuid7::nil(), 0, "la", 0).unwrap_err();
    assert!(e.is_nil_subtitle_cue_id());
  }

  #[test]
  fn vtt_region_rejects_nil_ids() {
    assert!(VttRegion::try_new(Uuid7::nil(), Uuid7::new(), "r")
      .unwrap_err()
      .is_nil_id());
    assert!(VttRegion::try_new(Uuid7::new(), Uuid7::nil(), "r")
      .unwrap_err()
      .is_nil_subtitle_track_id());
  }

  #[test]
  fn vtt_style_block_rejects_nil_ids() {
    assert!(VttStyleBlock::try_new(Uuid7::nil(), Uuid7::new(), 0, "")
      .unwrap_err()
      .is_nil_id());
    assert!(VttStyleBlock::try_new(Uuid7::new(), Uuid7::nil(), 0, "")
      .unwrap_err()
      .is_nil_subtitle_track_id());
  }

  #[test]
  fn ass_style_rejects_empty_name() {
    let e = AssStyle::try_new(Uuid7::new(), Uuid7::new(), "").unwrap_err();
    assert!(e.is_empty_ass_style_name());
  }

  #[test]
  fn ass_style_builders_round_trip() {
    let s = AssStyle::try_new(Uuid7::new(), Uuid7::new(), "Default")
      .unwrap()
      .with_fontname("Arial")
      .with_fontsize(48.0)
      .with_primary_colour(0x00FFFFFF)
      .with_bold()
      .with_italic()
      .with_outline(2.5)
      .with_shadow(1.5)
      .with_alignment(2);
    assert_eq!(s.name(), "Default");
    assert_eq!(s.fontsize(), 48.0);
    assert!(s.bold());
    assert!(s.italic());
    assert_eq!(s.alignment(), 2);
  }

  #[test]
  fn lrc_metadata_round_trip() {
    let m = LrcMetadata::try_new(Uuid7::new())
      .unwrap()
      .with_title("Song")
      .with_artist("Band")
      .with_offset_ms(-500);
    assert_eq!(m.title(), "Song");
    assert_eq!(m.artist(), "Band");
    assert_eq!(m.offset_ms(), -500);
  }

  // ---- New text-format domain types ---------------------------------------

  #[test]
  fn micro_dvd_cue_builds_and_carries_kind() {
    let d = MicroDvdData::new("{y:i}hi").with_styled_text("{y:b}hello");
    let c: MicroDvdCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src("hello"),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::MicroDvd);
    assert_eq!(c.data_ref().styled_text(), "{y:b}hello");
  }

  #[test]
  fn sub_viewer_cue_builds_and_carries_kind() {
    let d = SubViewerData::new("[b]hi[/b][br]line 2");
    let c: SubViewerCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src("hi"),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::SubViewer);
    assert_eq!(c.data_ref().styled_text(), "[b]hi[/b][br]line 2");
  }

  #[test]
  fn sbv_cue_builds_and_carries_kind() {
    let c: SbvCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src("plain"),
      SbvData::new(),
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::Sbv);
  }

  #[test]
  fn ttml_cue_builds_with_region_and_style_refs() {
    let region_id = Uuid7::new();
    let style_id = Uuid7::new();
    let d = TtmlData::<Uuid7>::new()
      .with_region_id(region_id)
      .with_style_id(style_id)
      .with_xml_id("cue-1")
      .with_styled_text("<span tts:color=\"red\">hi</span>");
    let c: TtmlCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src("hi"),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::Ttml);
    assert_eq!(c.data_ref().region_id_ref(), Some(&region_id));
    assert_eq!(c.data_ref().style_id_ref(), Some(&style_id));
    assert_eq!(c.data_ref().xml_id(), "cue-1");
  }

  #[test]
  fn sami_cue_builds_with_class_selector() {
    let d = SamiData::new()
      .with_class_name("ENCC")
      .with_styled_text("<P><B>Hello</B></P>");
    let c: SamiCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src("Hello"),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::Sami);
    assert_eq!(c.data_ref().class_name(), "ENCC");
  }

  #[test]
  fn ttml_region_rejects_nil_ids() {
    assert!(TtmlRegion::try_new(Uuid7::nil(), Uuid7::new(), "r")
      .unwrap_err()
      .is_nil_id());
    assert!(TtmlRegion::try_new(Uuid7::new(), Uuid7::nil(), "r")
      .unwrap_err()
      .is_nil_subtitle_track_id());
  }

  #[test]
  fn ttml_region_builders_round_trip() {
    let r = TtmlRegion::try_new(Uuid7::new(), Uuid7::new(), "r1")
      .unwrap()
      .with_xml_attrs("tts:origin=\"10% 80%\" tts:extent=\"80% 20%\"");
    assert_eq!(r.xml_id(), "r1");
    assert!(r.xml_attrs().contains("tts:origin"));
  }

  #[test]
  fn ttml_style_rejects_nil_ids() {
    assert!(TtmlStyle::try_new(Uuid7::nil(), Uuid7::new(), "s")
      .unwrap_err()
      .is_nil_id());
    assert!(TtmlStyle::try_new(Uuid7::new(), Uuid7::nil(), "s")
      .unwrap_err()
      .is_nil_subtitle_track_id());
  }

  #[test]
  fn sami_style_rejects_nil_ids() {
    assert!(SamiStyle::try_new(Uuid7::nil(), Uuid7::new(), "ENCC")
      .unwrap_err()
      .is_nil_id());
    assert!(SamiStyle::try_new(Uuid7::new(), Uuid7::nil(), "ENCC")
      .unwrap_err()
      .is_nil_subtitle_track_id());
  }

  // ---- New bitmap / broadcast domain types --------------------------------

  #[test]
  fn vob_sub_cue_builds_and_carries_kind() {
    let palette_id = Uuid7::new();
    let d = VobSubData::<Uuid7>::new(palette_id)
      .with_bitmap(Bytes::from_static(b"\x01\x02\x03"))
      .with_width(720)
      .with_height(60)
      .with_pos(20, 540)
      .with_color_indices([1, 2, 3, 4])
      .with_contrast_indices([0, 0xF, 0xF, 0xF]);
    let c: VobSubCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::new(),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::VobSub);
    assert_eq!(c.data_ref().palette_id_ref(), &palette_id);
    assert_eq!(c.data_ref().bitmap_ref().as_ref(), b"\x01\x02\x03");
    assert_eq!(c.data_ref().width(), 720);
    assert_eq!(c.data_ref().pos_x(), 20);
    assert_eq!(c.data_ref().color_indices(), &[1, 2, 3, 4]);
  }

  #[test]
  fn pgs_cue_builds_and_carries_kind() {
    let d = PgsData::new()
      .with_bitmap(Bytes::from_static(b"\xAA\xBB"))
      .with_palette_bytes(Bytes::from_static(b"\x10\x20\x30\x40"))
      .with_width(1920)
      .with_height(80)
      .with_pos(0, 920)
      .with_composition_state(0x80);
    let c: PgsCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::new(),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::Pgs);
    assert_eq!(c.data_ref().bitmap_ref().as_ref(), b"\xAA\xBB");
    assert_eq!(
      c.data_ref().palette_bytes_ref().as_ref(),
      b"\x10\x20\x30\x40"
    );
    assert_eq!(c.data_ref().composition_state(), 0x80);
  }

  #[test]
  fn cea608_data_accepts_valid_channels() {
    for ch in 1u8..=4 {
      let d = Cea608Data::try_new(ch).unwrap();
      assert_eq!(d.channel(), ch);
    }
  }

  #[test]
  fn cea608_data_rejects_zero_channel() {
    let e = Cea608Data::try_new(0).unwrap_err();
    assert!(matches!(e, SubtitleCueError::Cea608ChannelOutOfRange(0)));
  }

  #[test]
  fn cea608_data_rejects_channel_above_4() {
    let e = Cea608Data::try_new(5).unwrap_err();
    assert!(matches!(e, SubtitleCueError::Cea608ChannelOutOfRange(5)));
  }

  #[test]
  fn cea608_cue_builds_and_carries_kind() {
    let d = Cea608Data::try_new(2)
      .unwrap()
      .with_pac_byte_pair(0x1170)
      .with_styled_text("Caption text");
    let c: Cea608Cue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src("Caption text"),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::Cea608);
    assert_eq!(c.data_ref().channel(), 2);
    assert_eq!(c.data_ref().pac_byte_pair(), 0x1170);
  }

  #[test]
  fn ebu_stl_data_accepts_valid_justification() {
    for j in 1u8..=3 {
      let d = EbuStlData::try_new(j).unwrap();
      assert_eq!(d.justification(), j);
    }
  }

  #[test]
  fn ebu_stl_data_rejects_zero_justification() {
    let e = EbuStlData::try_new(0).unwrap_err();
    assert!(matches!(
      e,
      SubtitleCueError::EbuStlJustificationOutOfRange(0)
    ));
  }

  #[test]
  fn ebu_stl_data_rejects_justification_above_3() {
    let e = EbuStlData::try_new(4).unwrap_err();
    assert!(matches!(
      e,
      SubtitleCueError::EbuStlJustificationOutOfRange(4)
    ));
  }

  #[test]
  fn ebu_stl_cue_builds_and_carries_kind() {
    let d = EbuStlData::try_new(2)
      .unwrap()
      .with_subtitle_number(42)
      .with_cumulative()
      .with_vertical_pos(20);
    let c: EbuStlCue<Uuid7> = SubtitleCue::try_new(
      Uuid7::new(),
      Uuid7::new(),
      0,
      span(),
      LocalizedText::from_src("Hi"),
      d,
    )
    .unwrap();
    assert_eq!(c.kind(), SubtitleCueKind::EbuStl);
    assert_eq!(c.data_ref().subtitle_number(), 42);
    assert!(c.data_ref().cumulative());
    assert_eq!(c.data_ref().vertical_pos(), 20);
  }

  #[test]
  fn vob_sub_palette_rejects_nil_ids() {
    assert!(VobSubPalette::try_new(Uuid7::nil(), Uuid7::new())
      .unwrap_err()
      .is_nil_id());
    assert!(VobSubPalette::try_new(Uuid7::new(), Uuid7::nil())
      .unwrap_err()
      .is_nil_subtitle_track_id());
  }

  #[test]
  fn vob_sub_palette_builders_round_trip() {
    let mut entries = [0u32; 16];
    entries[0] = 0x00FF0000; // red
    entries[1] = 0x0000FF00; // green
    let p = VobSubPalette::try_new(Uuid7::new(), Uuid7::new())
      .unwrap()
      .with_entries(entries);
    assert_eq!(p.entries()[0], 0x00FF0000);
    assert_eq!(p.entries()[1], 0x0000FF00);
  }
}