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f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f70d2c5
3b0bd63
 
9e6f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f70d2c5
3b0bd63
 
9e6f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f70d2c5
 
9e6f3aa
 
 
 
 
f70d2c5
 
3b0bd63
f70d2c5
9e6f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Local subtitle editor for clip-workflow program folders.

Run:
    python subtitle_editor.py --program-dir programas/estacion_YYYYMMDD_slug

The program folder must include:
    raw/*.mp4
    raw/*_v.ass
    vertical_9x16/*_9x16.mp4
"""

from __future__ import annotations

import argparse
import base64
import contextlib
import html
import importlib.util
import json
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import traceback
import types
import uuid
import webbrowser
from dataclasses import dataclass
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, unquote, urlparse


CLIENT_DISCONNECT_ERRORS = (BrokenPipeError, ConnectionResetError)


APP_HTML = r"""<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Editor de subtitulos</title>
  <style>
    :root {
      color-scheme: light;
      --bg: #f4f5f4;
      --surface: #ffffff;
      --surface-soft: #f8f8f6;
      --ink: #171714;
      --ink-soft: #33332d;
      --muted: #76766f;
      --line: #e5e3dc;
      --line-strong: #d2cfc4;
      --rail: #151512;
      --rail-soft: #20201b;
      --rail-line: #303027;
      --accent: #e2b600;
      --accent-ink: #2b2400;
      --accent-soft: #fff7d3;
      --ok: #207a4b;
      --bad: #b2413a;
      --radius: 10px;
      --shadow: 0 18px 48px rgba(15, 15, 12, .09);
    }

    * { box-sizing: border-box; }

    html {
      background: var(--bg);
    }

    body {
      margin: 0;
      min-width: 1120px;
      font: 14px/1.45 Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      background: var(--bg);
      color: var(--ink);
      letter-spacing: 0;
    }

    button, textarea, input {
      font: inherit;
    }

    button {
      border: 1px solid var(--ink);
      background: var(--ink);
      color: #fff;
      min-height: 38px;
      padding: 0 14px;
      border-radius: var(--radius);
      cursor: pointer;
      font-weight: 760;
      letter-spacing: 0;
      white-space: nowrap;
      transition: background .15s ease, border-color .15s ease, color .15s ease, opacity .15s ease, transform .15s ease;
    }

    button.secondary {
      background: #fff;
      color: var(--ink);
      border-color: var(--line);
    }

    button.subtle {
      min-height: 34px;
      padding: 0 11px;
      background: var(--surface-soft);
      color: var(--ink-soft);
      border-color: var(--line);
      font-size: 12px;
    }

    button:hover:not(:disabled) {
      background: #292925;
      border-color: #292925;
      transform: translateY(-1px);
    }

    button.secondary:hover:not(:disabled) {
      background: var(--surface-soft);
      border-color: var(--line-strong);
    }

    button.subtle:hover:not(:disabled) {
      background: #fff;
      color: var(--ink);
      border-color: var(--line-strong);
    }

    button:disabled {
      cursor: default;
      opacity: .55;
      transform: none;
    }

    .shell {
      display: grid;
      grid-template-columns: 300px minmax(360px, 500px) minmax(520px, 1fr);
      height: 100vh;
      min-width: 0;
    }

    aside {
      border-right: 1px solid var(--rail-line);
      background: var(--rail);
      color: #f7f4e7;
      min-width: 0;
      display: flex;
      flex-direction: column;
    }

    .brand {
      padding: 18px 18px 16px;
      border-bottom: 1px solid var(--rail-line);
      display: flex;
      gap: 12px;
      align-items: center;
      min-height: 78px;
    }

    .mark {
      width: 30px;
      height: 30px;
      border-radius: 9px;
      background: var(--accent);
      box-shadow: inset 0 -8px 0 rgba(0,0,0,.13);
      flex: 0 0 auto;
    }

    h1, h2 {
      margin: 0;
      letter-spacing: 0;
    }

    h1 {
      font-size: 17px;
      line-height: 1.15;
      font-weight: 820;
    }

    .program {
      color: #a9a79a;
      font-size: 12.5px;
      margin-top: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 205px;
    }

    .program-picker {
      padding: 13px 18px 15px;
      border-bottom: 1px solid var(--rail-line);
      display: grid;
      gap: 8px;
    }

    .program-picker > span:first-child {
      color: #a9a79a;
      font-size: 11px;
      font-weight: 780;
      letter-spacing: .08em;
      text-transform: uppercase;
    }

    .program-select-wrap {
      position: relative;
      display: block;
    }

    .program-select-wrap::after {
      content: "";
      position: absolute;
      right: 13px;
      top: 50%;
      width: 8px;
      height: 8px;
      border-right: 2px solid #bfbcae;
      border-bottom: 2px solid #bfbcae;
      transform: translateY(-68%) rotate(45deg);
      pointer-events: none;
    }

    select {
      width: 100%;
      min-height: 44px;
      border: 1px solid var(--rail-line);
      border-radius: 8px;
      padding: 0 34px 0 13px;
      background: var(--rail-soft);
      color: #f7f4e7;
      outline: 0;
      font-size: 14px;
      line-height: 1.25;
      font-weight: 760;
      appearance: none;
      -webkit-appearance: none;
      text-overflow: ellipsis;
    }

    select:focus {
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(226, 182, 0, .18);
    }

    .clip-list {
      overflow: auto;
      padding: 10px 10px 14px;
    }

    .clip-button {
      width: 100%;
      display: grid;
      grid-template-columns: 34px minmax(0, 1fr);
      gap: 10px;
      align-items: center;
      text-align: left;
      border: 1px solid transparent;
      background: transparent;
      color: #f7f4e7;
      padding: 10px;
      min-height: 58px;
      border-radius: 12px;
      font-weight: 680;
    }

    .clip-button:hover {
      background: var(--rail-soft);
    }

    .clip-button.active {
      background: #fff;
      color: var(--ink);
      border-color: transparent;
    }

    .num {
      width: 34px;
      height: 34px;
      border-radius: 9px;
      border: 1px solid rgba(255,255,255,.16);
      display: grid;
      place-items: center;
      font-size: 12px;
      font-weight: 850;
      background: rgba(255,255,255,.07);
      color: inherit;
      font-variant-numeric: tabular-nums;
    }

    .clip-button.active .num {
      background: var(--accent);
      border-color: var(--accent);
      color: var(--accent-ink);
    }

    .clip-copy {
      min-width: 0;
    }

    .clip-title {
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .clip-meta {
      color: #aaa79a;
      font-size: 12px;
      margin-top: 2px;
      font-weight: 550;
    }

    .clip-button.active .clip-meta {
      color: var(--muted);
    }

    .video-pane,
    .edit-pane {
      min-height: 0;
      min-width: 0;
    }

    .video-pane {
      display: flex;
      flex-direction: column;
      gap: 14px;
      align-items: stretch;
      padding: 20px 22px;
      border-right: 1px solid var(--line);
      background:
        linear-gradient(180deg, rgba(255,255,255,.76), rgba(255,255,255,.22)),
        var(--bg);
      overflow: auto;
    }

    .video-frame {
      width: min(100%, 420px);
      align-self: center;
      border-radius: 16px;
      background: #070706;
      padding: 8px;
      box-shadow: var(--shadow);
    }

    video {
      width: 100%;
      aspect-ratio: 9 / 16;
      background: #050505;
      border-radius: 10px;
      border: 1px solid #050505;
      display: block;
      max-height: calc(100vh - 170px);
      object-fit: contain;
    }

    .actions {
      display: flex;
      gap: 9px;
      flex-wrap: wrap;
      align-items: center;
      width: min(100%, 420px);
      align-self: center;
    }

    .status {
      border: 1px solid var(--line);
      background: rgba(255,255,255,.76);
      border-radius: 12px;
      padding: 12px 14px;
      min-height: 44px;
      color: var(--muted);
      white-space: pre-wrap;
      box-shadow: 0 1px 0 rgba(0,0,0,.02);
      width: min(100%, 420px);
      align-self: center;
    }

    .status.busy {
      color: var(--ink-soft);
      border-color: #ead991;
      background: #fffaf0;
    }

    .status.ok { color: var(--ok); }
    .status.bad { color: var(--bad); }

    .edit-pane {
      background: var(--surface);
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }

    .edit-header {
      padding: 22px 24px 16px;
      border-bottom: 1px solid var(--line);
      display: grid;
      gap: 16px;
      background: rgba(255,255,255,.94);
      backdrop-filter: blur(14px);
    }

    .title-row {
      display: flex;
      justify-content: space-between;
      align-items: start;
      gap: 16px;
    }

    .title-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      justify-content: flex-end;
    }

    .title-block {
      min-width: 0;
      display: grid;
      gap: 5px;
    }

    .eyebrow {
      color: var(--muted);
      font-size: 11px;
      font-weight: 760;
      letter-spacing: .08em;
      text-transform: uppercase;
    }

    h2 {
      font-size: 20px;
      line-height: 1.2;
      font-weight: 850;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .search-tools {
      display: grid;
      grid-template-columns: minmax(190px, 1fr) auto auto auto auto;
      gap: 8px;
      align-items: center;
    }

    .search-box {
      position: relative;
      min-width: 0;
    }

    .search-box::before {
      content: "";
      position: absolute;
      left: 13px;
      top: 50%;
      width: 10px;
      height: 10px;
      border: 2px solid #8b8a82;
      border-radius: 50%;
      transform: translateY(-58%);
      pointer-events: none;
    }

    .search-box::after {
      content: "";
      position: absolute;
      left: 25px;
      top: 23px;
      width: 8px;
      height: 2px;
      background: #8b8a82;
      border-radius: 2px;
      transform: rotate(45deg);
      pointer-events: none;
    }

    input[type="search"] {
      width: 100%;
      min-height: 38px;
      border: 1px solid var(--line);
      border-radius: 11px;
      padding: 0 13px 0 40px;
      color: var(--ink);
      background: var(--surface-soft);
      outline: 0;
      font-weight: 650;
    }

    input[type="search"]:focus {
      background: #fff;
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(226, 182, 0, .18);
    }

    .match-count {
      min-width: 54px;
      color: var(--muted);
      font-size: 12px;
      font-weight: 740;
      text-align: right;
      font-variant-numeric: tabular-nums;
    }

    .rows {
      overflow: auto;
      padding: 6px 24px 24px;
      background: var(--surface);
    }

    .sub-row {
      display: grid;
      grid-template-columns: 150px minmax(0, 1fr);
      gap: 16px;
      padding: 12px;
      margin: 8px 0;
      border: 1px solid transparent;
      border-radius: 14px;
      background: transparent;
      transition: background .15s ease, border-color .15s ease, box-shadow .15s ease;
    }

    .sub-row:hover {
      background: #fafafa;
      border-color: #efeee9;
    }

    .sub-row.match {
      background: #fffdf1;
      border-color: #f0dda2;
    }

    .sub-row.current-match {
      background: var(--accent-soft);
      border-color: var(--accent);
      box-shadow: 0 10px 24px rgba(226, 182, 0, .14);
    }

    .time {
      color: var(--muted);
      font-size: 12px;
      font-variant-numeric: tabular-nums;
      white-space: nowrap;
      display: grid;
      gap: 8px;
      align-content: start;
    }

    .time label {
      display: grid;
      gap: 4px;
      color: #aaa79f;
      font-size: 10px;
      font-weight: 790;
      letter-spacing: .05em;
      text-transform: uppercase;
    }

    .time-input {
      width: 100%;
      min-height: 34px;
      border: 1px solid var(--line);
      border-radius: 9px;
      padding: 0 9px;
      color: var(--ink-soft);
      background: var(--surface-soft);
      outline: 0;
      font-size: 13px;
      font-weight: 720;
      font-variant-numeric: tabular-nums;
      letter-spacing: 0;
    }

    .time-input:focus {
      background: #fff;
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(226, 182, 0, .18);
    }

    .line-num {
      color: #aaa79f;
      font-size: 11px;
      font-weight: 760;
      letter-spacing: .04em;
      text-transform: uppercase;
    }

    .row-actions {
      display: flex;
      gap: 6px;
      flex-wrap: wrap;
    }

    .sub-main {
      display: grid;
      gap: 8px;
      min-width: 0;
    }

    textarea {
      width: 100%;
      min-height: 68px;
      resize: vertical;
      border: 1px solid var(--line);
      border-radius: 12px;
      padding: 12px 13px;
      color: var(--ink);
      background: var(--surface-soft);
      line-height: 1.35;
      font-weight: 760;
      letter-spacing: 0;
      transition: background .15s ease, border-color .15s ease, box-shadow .15s ease;
    }

    textarea:focus {
      background: #fff;
      outline: 0;
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(226, 182, 0, .18);
    }

    @media (max-width: 1180px) {
      body {
        min-width: 0;
      }

      .shell {
        grid-template-columns: 1fr;
        height: auto;
        min-height: 100vh;
      }

      aside {
        max-height: 270px;
        border-right: 0;
        border-bottom: 1px solid var(--line);
      }

      .video-pane {
        border-right: 0;
        border-bottom: 1px solid var(--line);
      }

      .program-picker {
        background: var(--rail);
      }

      video {
        max-height: 70vh;
      }

      .edit-pane {
        min-height: 520px;
      }
    }

    @media (max-width: 620px) {
      .video-pane {
        padding: 12px;
      }

      .sub-row {
        grid-template-columns: 1fr;
        gap: 6px;
        padding: 10px 0;
        border-radius: 0;
      }

      .time {
        padding-top: 0;
      }

      .search-tools {
        grid-template-columns: 1fr auto auto;
      }

      .search-tools .match-count,
      .search-tools #clearSearchBtn {
        display: none;
      }
    }
  </style>
</head>
<body>
  <div class="shell">
    <aside>
      <div class="brand">
        <div class="mark" aria-hidden="true"></div>
        <div>
          <h1>Editor de subtitulos</h1>
          <div class="program" id="programName"></div>
        </div>
      </div>
      <label class="program-picker">
        <span>Programa</span>
        <span class="program-select-wrap">
          <select id="programSelect"></select>
        </span>
      </label>
      <div class="clip-list" id="clipList"></div>
    </aside>

    <section class="video-pane">
      <div class="video-frame">
        <video id="video" controls playsinline preload="metadata" controlslist="nodownload"></video>
      </div>
      <div class="actions">
        <button id="saveBtn">Guardar</button>
        <button id="regenBtn">Regenerar clip</button>
        <button class="secondary" id="downloadBtn">Descargar final HQ</button>
        <button class="secondary" id="reloadBtn">Recargar</button>
      </div>
      <div class="status" id="status">Cargando...</div>
    </section>

    <section class="edit-pane">
      <div class="edit-header">
        <div class="title-row">
          <div class="title-block">
            <div class="eyebrow">Clip activo</div>
          <h2 id="clipTitle">Subtitulos</h2>
          </div>
          <div class="title-actions">
            <button class="secondary" id="addSubBtn">Agregar linea</button>
            <button class="secondary" id="openBtn">Abrir MP4</button>
          </div>
        </div>
        <div class="search-tools">
          <label class="search-box">
            <input id="searchInput" type="search" placeholder="Buscar en subtitulos" autocomplete="off">
          </label>
          <button class="subtle" id="prevMatchBtn" type="button">Ant</button>
          <button class="subtle" id="nextMatchBtn" type="button">Sig</button>
          <button class="subtle" id="clearSearchBtn" type="button">Limpiar</button>
          <div class="match-count" id="searchCount">0</div>
        </div>
      </div>
      <div class="rows" id="rows"></div>
    </section>
  </div>

  <script>
    const state = {
      programs: [],
      currentProgram: null,
      clips: [],
      current: null,
      subtitles: [],
      dirty: false,
      jobTimer: null,
      search: {
        query: '',
        matches: [],
        current: -1
      }
    };

    const els = {
      programName: document.getElementById('programName'),
      programSelect: document.getElementById('programSelect'),
      clipList: document.getElementById('clipList'),
      video: document.getElementById('video'),
      rows: document.getElementById('rows'),
      clipTitle: document.getElementById('clipTitle'),
      saveBtn: document.getElementById('saveBtn'),
      regenBtn: document.getElementById('regenBtn'),
      downloadBtn: document.getElementById('downloadBtn'),
      reloadBtn: document.getElementById('reloadBtn'),
      addSubBtn: document.getElementById('addSubBtn'),
      openBtn: document.getElementById('openBtn'),
      searchInput: document.getElementById('searchInput'),
      searchCount: document.getElementById('searchCount'),
      prevMatchBtn: document.getElementById('prevMatchBtn'),
      nextMatchBtn: document.getElementById('nextMatchBtn'),
      clearSearchBtn: document.getElementById('clearSearchBtn'),
      status: document.getElementById('status')
    };

    function setStatus(text, type = '') {
      els.status.textContent = text;
      els.status.className = 'status ' + type;
    }

    function friendlyJobMessage(job) {
      if (job.message) return job.message;
      if (job.status === 'queued') return 'Esperando para empezar...';
      if (job.status === 'running') return 'Regenerando el clip. Puede tardar unos minutos...';
      if (job.status === 'done') return 'Clip regenerado. Ya podes revisarlo arriba.';
      if (job.status === 'error') return 'No se pudo regenerar el clip.';
      return 'Preparando...';
    }

    async function api(path, options = {}) {
      const res = await fetch(path, {
        headers: { 'Content-Type': 'application/json' },
        ...options
      });
      const body = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(body.error || res.statusText);
      return body;
    }

    function clipLabel(clip) {
      return clip.title.replace(/_/g, ' ');
    }

    function programQuery() {
      return state.currentProgram ? `program=${encodeURIComponent(state.currentProgram)}` : '';
    }

    function apiWithProgram(path) {
      const query = programQuery();
      return query ? `${path}?${query}` : path;
    }

    function renderProgramSelect() {
      els.programSelect.innerHTML = '';
      state.programs.forEach(program => {
        const option = document.createElement('option');
        option.value = program.id;
        option.textContent = program.name;
        option.selected = program.id === state.currentProgram;
        els.programSelect.appendChild(option);
      });
      els.programSelect.disabled = state.programs.length <= 1;
    }

    function renderClipList() {
      els.clipList.innerHTML = '';
      state.clips.forEach((clip, index) => {
        const btn = document.createElement('button');
        btn.className = 'clip-button' + (state.current && state.current.id === clip.id ? ' active' : '');
        btn.innerHTML = `
          <span class="num">${String(index + 1).padStart(2, '0')}</span>
          <span class="clip-copy">
            <span class="clip-title">${escapeHtml(clipLabel(clip))}</span>
            <span class="clip-meta">${clip.has_output ? 'MP4 listo' : 'sin MP4 final'} - ${clip.subtitle_count} lineas</span>
          </span>`;
        btn.onclick = () => selectClip(clip.id);
        els.clipList.appendChild(btn);
      });
    }

    function escapeHtml(value) {
      return String(value)
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;');
    }

    function timeToSeconds(value) {
      const raw = String(value || '').trim().replace(',', '.');
      if (!raw) return NaN;
      if (!raw.includes(':')) return Number(raw);
      const parts = raw.split(':').map(part => part.trim());
      if (parts.length > 3 || parts.some(part => part === '')) return NaN;
      let seconds = Number(parts.pop());
      let minutes = parts.length ? Number(parts.pop()) : 0;
      let hours = parts.length ? Number(parts.pop()) : 0;
      if (![seconds, minutes, hours].every(Number.isFinite)) return NaN;
      return hours * 3600 + minutes * 60 + seconds;
    }

    function formatTime(seconds) {
      const safe = Math.max(0, Number(seconds) || 0);
      const minutes = Math.floor(safe / 60);
      const rest = safe - minutes * 60;
      return `${String(minutes).padStart(2, '0')}:${rest.toFixed(2).padStart(5, '0')}`;
    }

    function markDirty() {
      state.dirty = true;
    }

    function validateAndNormalizeSubtitles() {
      const normalized = state.subtitles
        .map((sub, position) => {
          const startSeconds = timeToSeconds(sub.start);
          const endSeconds = timeToSeconds(sub.end);
          if (!Number.isFinite(startSeconds) || !Number.isFinite(endSeconds)) {
            throw new Error(`Revisa los tiempos de la linea ${position + 1}.`);
          }
          if (endSeconds <= startSeconds) {
            throw new Error(`El fin debe ser mayor al inicio en la linea ${position + 1}.`);
          }
          return {
            ...sub,
            start: formatTime(startSeconds),
            end: formatTime(endSeconds),
            _startSeconds: startSeconds
          };
        })
        .filter(sub => String(sub.text || '').trim())
        .sort((a, b) => a._startSeconds - b._startSeconds)
        .map(({ _startSeconds, ...sub }) => sub);
      state.subtitles = normalized;
      return normalized;
    }

    function normalizeSearch(value) {
      return String(value)
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .toLowerCase()
        .trim();
    }

    function resetSearch() {
      state.search.query = '';
      state.search.matches = [];
      state.search.current = -1;
      els.searchInput.value = '';
      applySearchState();
    }

    function computeSearchMatches() {
      const query = normalizeSearch(state.search.query);
      if (!query) return [];
      const matches = [];
      state.subtitles.forEach((sub, index) => {
        if (normalizeSearch(sub.text).includes(query)) matches.push(index);
      });
      return matches;
    }

    function applySearchState({ focus = false } = {}) {
      const query = normalizeSearch(state.search.query);
      state.search.matches = computeSearchMatches();
      if (!query || !state.search.matches.length) {
        state.search.current = -1;
      } else if (!state.search.matches.includes(state.search.current)) {
        state.search.current = state.search.matches[0];
      }

      const currentPosition = state.search.matches.indexOf(state.search.current);
      els.searchCount.textContent = !query
        ? `${state.subtitles.length} lineas`
        : state.search.matches.length
          ? `${currentPosition + 1}/${state.search.matches.length}`
          : '0';

      const hasMatches = Boolean(query && state.search.matches.length);
      els.prevMatchBtn.disabled = !hasMatches;
      els.nextMatchBtn.disabled = !hasMatches;
      els.clearSearchBtn.disabled = !query;

      els.rows.querySelectorAll('.sub-row').forEach(row => {
        const index = Number(row.dataset.index);
        row.classList.toggle('match', state.search.matches.includes(index));
        row.classList.toggle('current-match', index === state.search.current);
      });

      if (focus && hasMatches) focusCurrentMatch();
    }

    function focusCurrentMatch() {
      const index = state.search.current;
      const row = els.rows.querySelector(`.sub-row[data-index="${index}"]`);
      const area = els.rows.querySelector(`textarea[data-index="${index}"]`);
      if (!row || !area) return;
      row.scrollIntoView({ block: 'center', behavior: 'smooth' });
      area.focus();
      const query = state.search.query.toLowerCase().trim();
      const position = area.value.toLowerCase().indexOf(query);
      if (position >= 0) {
        area.setSelectionRange(position, position + query.length);
      }
    }

    function moveSearch(direction) {
      if (!state.search.query) return;
      applySearchState();
      if (!state.search.matches.length) return;
      const currentPosition = Math.max(0, state.search.matches.indexOf(state.search.current));
      const nextPosition = (currentPosition + direction + state.search.matches.length) % state.search.matches.length;
      state.search.current = state.search.matches[nextPosition];
      applySearchState({ focus: true });
    }

    async function loadPrograms() {
      const data = await api('/api/programs');
      state.programs = data.programs;
      if (!state.programs.length) {
        els.programName.textContent = '';
        renderProgramSelect();
        setStatus('No hay programas con clips.', 'bad');
        return;
      }
      if (!state.currentProgram || !state.programs.some(p => p.id === state.currentProgram)) {
        state.currentProgram = state.programs[0].id;
      }
      renderProgramSelect();
      await loadClips();
    }

    async function loadClips(preferredClipId = null) {
      const data = await api(apiWithProgram('/api/clips'));
      els.programName.textContent = data.program_name;
      state.clips = data.clips;
      renderClipList();
      if (state.clips.length) {
        const nextId = preferredClipId && state.clips.some(c => c.id === preferredClipId)
          ? preferredClipId
          : state.current && state.clips.some(c => c.id === state.current.id)
            ? state.current.id
            : state.clips[0].id;
        await selectClip(nextId);
      } else {
        state.current = null;
        state.subtitles = [];
        renderRows();
        setStatus('No hay clips en este programa.', 'bad');
      }
    }

    async function selectClip(id) {
      if (state.dirty && !confirm('Hay cambios sin guardar. Continuar?')) return;
      const clip = state.clips.find(c => c.id === id);
      state.current = clip;
      state.dirty = false;
      renderClipList();
      els.clipTitle.textContent = clipLabel(clip);
      els.video.src = clip.video_url;
      els.openBtn.disabled = !clip.has_output;
      els.openBtn.onclick = () => window.open(clip.output_url || clip.video_url, '_blank');
      els.downloadBtn.disabled = !clip.has_output;
      els.downloadBtn.onclick = () => {
        if (clip.download_url) window.location.href = clip.download_url;
      };
      const data = await api(apiWithProgram(`/api/clips/${encodeURIComponent(id)}/subtitles`));
      state.subtitles = data.subtitles;
      renderRows();
      resetSearch();
      setStatus(`${state.subtitles.length} subtitulos cargados.`, 'ok');
    }

    function renderRows() {
      els.rows.innerHTML = '';
      state.subtitles.forEach((sub, index) => {
        const row = document.createElement('div');
        row.className = 'sub-row';
        row.dataset.index = index;
        const time = document.createElement('div');
        time.className = 'time';
        time.innerHTML = `
          <span class="line-num">Linea ${String(index + 1).padStart(2, '0')}</span>
          <label>Inicio
            <input class="time-input" data-index="${index}" data-field="start" value="${escapeHtml(sub.start)}" inputmode="decimal">
          </label>
          <label>Fin
            <input class="time-input" data-index="${index}" data-field="end" value="${escapeHtml(sub.end)}" inputmode="decimal">
          </label>`;
        time.querySelectorAll('.time-input').forEach(input => {
          input.addEventListener('input', () => {
            state.subtitles[index][input.dataset.field] = input.value;
            markDirty();
          });
          input.addEventListener('blur', () => {
            const seconds = timeToSeconds(input.value);
            if (Number.isFinite(seconds)) input.value = formatTime(seconds);
            state.subtitles[index][input.dataset.field] = input.value;
          });
        });
        const main = document.createElement('div');
        main.className = 'sub-main';
        const area = document.createElement('textarea');
        area.value = sub.text;
        area.dataset.index = index;
        area.addEventListener('input', () => {
          state.subtitles[index].text = area.value;
          markDirty();
          if (state.search.query) applySearchState();
        });
        const rowActions = document.createElement('div');
        rowActions.className = 'row-actions';
        const addBtn = document.createElement('button');
        addBtn.className = 'subtle';
        addBtn.type = 'button';
        addBtn.textContent = 'Agregar debajo';
        addBtn.onclick = () => addSubtitle(index);
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'subtle';
        deleteBtn.type = 'button';
        deleteBtn.textContent = 'Borrar';
        deleteBtn.onclick = () => deleteSubtitle(index);
        rowActions.appendChild(addBtn);
        rowActions.appendChild(deleteBtn);
        main.appendChild(area);
        main.appendChild(rowActions);
        row.appendChild(time);
        row.appendChild(main);
        els.rows.appendChild(row);
      });
      applySearchState();
    }

    function addSubtitle(afterIndex = null) {
      const current = Number.isFinite(els.video.currentTime) ? els.video.currentTime : 0;
      const base = afterIndex === null
        ? current
        : Math.max(current, timeToSeconds(state.subtitles[afterIndex]?.end) || current);
      const sub = {
        index: null,
        start: formatTime(base),
        end: formatTime(base + 2),
        text: ''
      };
      const insertAt = afterIndex === null ? state.subtitles.length : afterIndex + 1;
      state.subtitles.splice(insertAt, 0, sub);
      markDirty();
      renderRows();
      const area = els.rows.querySelector(`textarea[data-index="${insertAt}"]`);
      if (area) {
        area.scrollIntoView({ block: 'center', behavior: 'smooth' });
        area.focus();
      }
      setStatus('Linea nueva creada. Ajusta inicio, fin y texto.', 'ok');
    }

    function deleteSubtitle(index) {
      if (!confirm('Borrar esta linea de subtitulos?')) return;
      state.subtitles.splice(index, 1);
      markDirty();
      renderRows();
      setStatus('Linea borrada. Guarda o regenera para aplicar el cambio.', 'ok');
    }

    async function saveSubtitles() {
      if (!state.current) return;
      const subtitles = validateAndNormalizeSubtitles();
      await api(apiWithProgram(`/api/clips/${encodeURIComponent(state.current.id)}/subtitles`), {
        method: 'POST',
        body: JSON.stringify({ subtitles })
      });
      state.dirty = false;
      renderRows();
      setStatus('Subtitulos guardados.', 'ok');
    }

    async function regenerateClip() {
      if (!state.current) return;
      els.regenBtn.disabled = true;
      els.saveBtn.disabled = true;
      setStatus('Preparando el clip...', 'busy');
      if (state.dirty) await saveSubtitles();
      const data = await api(apiWithProgram(`/api/clips/${encodeURIComponent(state.current.id)}/regenerate`), {
        method: 'POST',
        body: JSON.stringify({})
      });
      pollJob(data.job_id);
    }

    async function pollJob(jobId) {
      clearInterval(state.jobTimer);
      const tick = async () => {
        const job = await api(`/api/jobs/${encodeURIComponent(jobId)}`);
        setStatus(friendlyJobMessage(job), job.status === 'error' ? 'bad' : 'busy');
        if (job.status === 'done' || job.status === 'error') {
          clearInterval(state.jobTimer);
          els.regenBtn.disabled = false;
          els.saveBtn.disabled = false;
          if (job.status === 'done') {
            const currentId = state.current ? state.current.id : null;
            await loadClips(currentId);
            const clip = state.clips.find(c => c.id === currentId);
            if (clip) {
              els.video.src = clip.video_url + '&refresh=' + Date.now();
              els.video.load();
            }
            setStatus(friendlyJobMessage(job), 'ok');
          } else {
            setStatus(friendlyJobMessage(job), 'bad');
            if (job.technical_log) console.warn(job.technical_log);
          }
        }
      };
      await tick();
      state.jobTimer = setInterval(tick, 1500);
    }

    els.saveBtn.onclick = () => saveSubtitles().catch(err => setStatus(err.message, 'bad'));
    els.addSubBtn.onclick = () => addSubtitle();
    els.regenBtn.onclick = () => regenerateClip().catch(err => {
      els.regenBtn.disabled = false;
      els.saveBtn.disabled = false;
      setStatus(err.message, 'bad');
    });
    els.reloadBtn.onclick = () => loadPrograms().catch(err => setStatus(err.message, 'bad'));
    els.programSelect.addEventListener('change', async () => {
      if (state.dirty && !confirm('Hay cambios sin guardar. Continuar?')) {
        renderProgramSelect();
        return;
      }
      state.currentProgram = els.programSelect.value;
      state.current = null;
      state.dirty = false;
      await loadClips();
    });
    els.searchInput.addEventListener('input', () => {
      state.search.query = els.searchInput.value;
      state.search.current = -1;
      applySearchState();
    });
    els.searchInput.addEventListener('keydown', event => {
      if (event.key !== 'Enter') return;
      event.preventDefault();
      moveSearch(event.shiftKey ? -1 : 1);
    });
    els.prevMatchBtn.onclick = () => moveSearch(-1);
    els.nextMatchBtn.onclick = () => moveSearch(1);
    els.clearSearchBtn.onclick = () => {
      resetSearch();
      els.searchInput.focus();
    };
    window.addEventListener('beforeunload', event => {
      if (!state.dirty) return;
      event.preventDefault();
      event.returnValue = '';
    });

    loadPrograms().catch(err => setStatus(err.message, 'bad'));
  </script>
</body>
</html>
"""


@dataclass
class ClipInfo:
    id: str
    title: str
    raw_path: Path
    ass_path: Path
    output_path: Path
    preview_path: Path
    subtitle_count: int


@dataclass
class ProgramInfo:
    id: str
    name: str
    path: Path
    clip_count: int
    source_id: str = ""
    source_url: str = ""


class Capture:
    def __init__(self, job: dict[str, Any]):
        self.job = job

    def write(self, value: str) -> int:
        if value.strip():
            self.job["technical_log"] += value
            self.job["technical_log"] = self.job["technical_log"][-12000:]
            update_job_message_from_log(self.job, value)
        return len(value)

    def flush(self) -> None:
        return None


def set_job_message(job: dict[str, Any], message: str) -> None:
    job["message"] = message
    job["log"] = message


def update_job_message_from_log(job: dict[str, Any], value: str) -> None:
    text = value.lower()
    if "detectando planos" in text or "layout panel" in text:
        set_job_message(job, "Analizando el video para seguir a quien habla...")
    elif "segmentos" in text or "plano(s) con zoom" in text:
        set_job_message(job, "Ajustando el encuadre y los cambios de cámara...")
    elif "ffmpeg" in text or "filter_complex" in text:
        set_job_message(job, "Generando el MP4 final. Puede tardar unos minutos...")


def ass_time_to_seconds(value: str) -> float:
    h, m, s = value.split(":")
    return int(h) * 3600 + int(m) * 60 + float(s)


def pretty_time(value: str) -> str:
    seconds = ass_time_to_seconds(value)
    minutes = int(seconds // 60)
    rest = seconds - minutes * 60
    return f"{minutes:02d}:{rest:05.2f}"


def edit_time_to_seconds(value: Any) -> float:
    text = str(value or "").strip().replace(",", ".")
    if not text:
        raise ValueError("tiempo vacio")
    if ":" not in text:
        return float(text)
    parts = [part.strip() for part in text.split(":")]
    if len(parts) > 3 or any(not part for part in parts):
        raise ValueError(f"tiempo invalido: {text}")
    seconds = float(parts.pop())
    minutes = float(parts.pop()) if parts else 0
    hours = float(parts.pop()) if parts else 0
    return hours * 3600 + minutes * 60 + seconds


def seconds_to_ass_time(seconds: float) -> str:
    seconds = max(0, seconds)
    hours = int(seconds // 3600)
    seconds -= hours * 3600
    minutes = int(seconds // 60)
    seconds -= minutes * 60
    return f"{hours}:{minutes:02d}:{seconds:05.2f}"


def split_ass_text(text: str) -> tuple[str, str]:
    prefixes: list[str] = []
    rest = text
    while rest.startswith("{"):
        end = rest.find("}")
        if end == -1:
            break
        prefixes.append(rest[: end + 1])
        rest = rest[end + 1 :]
    return "".join(prefixes), rest


def plain_from_ass(text: str) -> str:
    _, rest = split_ass_text(text)
    return rest.replace(r"\N", "\n").replace(r"\n", "\n").strip()


def ass_from_plain(text: str) -> str:
    clean_lines = []
    for line in text.replace("\r", "").split("\n"):
        line = line.strip()
        if not line:
            continue
        line = line.replace("\\", "/").replace("{", "(").replace("}", ")")
        clean_lines.append(line)
    return r"\N".join(clean_lines)


def parse_ass(path: Path) -> list[dict[str, Any]]:
    subtitles: list[dict[str, Any]] = []
    lines = path.read_text(encoding="utf-8").splitlines()
    event_index = 0
    for line_index, line in enumerate(lines):
        if not line.startswith("Dialogue:"):
            continue
        parts = line.split(",", 9)
        if len(parts) < 10:
            continue
        subtitles.append(
            {
                "index": event_index,
                "line_index": line_index,
                "start": pretty_time(parts[1]),
                "end": pretty_time(parts[2]),
                "text": plain_from_ass(parts[9]),
            }
        )
        event_index += 1
    return subtitles


def save_ass(path: Path, incoming: list[dict[str, Any]]) -> None:
    lines = path.read_text(encoding="utf-8").splitlines()
    original_events: list[tuple[int, list[str]]] = []
    event_index = 0
    for line_index, line in enumerate(lines):
        if not line.startswith("Dialogue:"):
            continue
        parts = line.split(",", 9)
        if len(parts) < 10:
            continue
        original_events.append((line_index, parts))
        event_index += 1

    fallback = (
        original_events[0][1][:]
        if original_events
        else ["Dialogue: 0", "0:00:00.00", "0:00:02.00", "Default", "", "0", "0", "0", "", ""]
    )
    by_index = {index: parts for index, (_line_index, parts) in enumerate(original_events)}
    rendered: list[tuple[float, str]] = []
    for position, item in enumerate(incoming):
        plain_text = str(item.get("text", "")).strip()
        if not plain_text:
            continue
        try:
            start_seconds = edit_time_to_seconds(item.get("start"))
            end_seconds = edit_time_to_seconds(item.get("end"))
        except Exception as exc:
            raise ValueError(f"Tiempo invalido en linea {position + 1}.") from exc
        if end_seconds <= start_seconds:
            raise ValueError(f"El fin debe ser mayor al inicio en linea {position + 1}.")
        try:
            original_index = int(item.get("index"))
        except Exception:
            original_index = -1
        parts = (by_index.get(original_index) or fallback)[:]
        prefix, _ = split_ass_text(parts[9])
        parts[1] = seconds_to_ass_time(start_seconds)
        parts[2] = seconds_to_ass_time(end_seconds)
        parts[9] = prefix + ass_from_plain(plain_text)
        rendered.append((start_seconds, ",".join(parts)))

    rendered_lines = [line for _start, line in sorted(rendered, key=lambda item: item[0])]
    if original_events:
        first_line = original_events[0][0]
        old_event_lines = {line_index for line_index, _parts in original_events}
        rebuilt: list[str] = []
        inserted = False
        for line_index, line in enumerate(lines):
            if line_index == first_line:
                rebuilt.extend(rendered_lines)
                inserted = True
            if line_index in old_event_lines:
                continue
            rebuilt.append(line)
        if not inserted:
            rebuilt.extend(rendered_lines)
        lines = rebuilt
    else:
        lines.extend(rendered_lines)
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")


def build_clip_id(base: str) -> str:
    return re.sub(r"[^A-Za-z0-9_.-]+", "_", base)


def build_program_id(name: str) -> str:
    return build_clip_id(name)


def is_program_dir(path: Path) -> bool:
    return (path / "raw").is_dir() and (path / "vertical_9x16").is_dir()


def load_program_metadata(program_dir: Path) -> dict[str, Any]:
    candidates = [
        program_dir / "program.json",
        *sorted(program_dir.glob("*.info.json")),
        *sorted((program_dir / "raw").glob("*.info.json")),
    ]
    for path in candidates:
        if not path.exists():
            continue
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
        except Exception:
            continue
        title = str(data.get("title") or data.get("fulltitle") or "").strip()
        video_id = str(data.get("video_id") or data.get("id") or "").strip()
        url = str(data.get("webpage_url") or data.get("url") or "").strip()
        return {
            "title": title,
            "video_id": video_id,
            "url": url,
            "hidden": bool(data.get("hidden")),
        }
    return {"title": "", "video_id": "", "url": "", "hidden": False}


def program_sort_key(program: ProgramInfo) -> tuple[int, str]:
    name = program.path.name.lower()
    is_hq = int(name.endswith("_hq") or "_hq" in name)
    return (is_hq, name)


def discover_clips(program_dir: Path) -> list[ClipInfo]:
    raw_dir = program_dir / "raw"
    output_dir = program_dir / "vertical_9x16"
    preview_dir = program_dir / "web_preview"
    clips: list[ClipInfo] = []
    for ass_path in sorted(raw_dir.glob("*_v.ass")):
        base = ass_path.name[: -len("_v.ass")]
        raw_path = raw_dir / f"{base}.mp4"
        output_path = output_dir / f"{base}_9x16.mp4"
        preview_path = preview_dir / f"{base}_preview.mp4"
        if not raw_path.exists():
            continue
        clips.append(
            ClipInfo(
                id=build_clip_id(base),
                title=base,
                raw_path=raw_path,
                ass_path=ass_path,
                output_path=output_path,
                preview_path=preview_path,
                subtitle_count=len(parse_ass(ass_path)),
            )
        )
    return clips


def discover_programs(root_dir: Path | None, single_program_dir: Path) -> list[ProgramInfo]:
    program_dirs: list[Path] = []
    if root_dir:
        nested_root = root_dir / "programs"
        search_roots = [nested_root, root_dir] if nested_root.exists() else [root_dir]
        for search_root in search_roots:
            if not search_root.exists():
                continue
            for candidate in sorted(search_root.iterdir()):
                if candidate.is_dir() and is_program_dir(candidate):
                    program_dirs.append(candidate)
        if is_program_dir(root_dir):
            program_dirs.append(root_dir)
    else:
        program_dirs.append(single_program_dir)

    unique: dict[Path, ProgramInfo] = {}
    by_source: dict[str, ProgramInfo] = {}
    for program_dir in program_dirs:
        resolved = program_dir.resolve()
        if resolved in unique:
            continue
        metadata = load_program_metadata(resolved)
        if metadata.get("hidden"):
            continue
        clips = discover_clips(resolved)
        if not clips:
            continue
        program = ProgramInfo(
            id=build_program_id(resolved.name),
            name=metadata["title"] or resolved.name.replace("_", " "),
            path=resolved,
            clip_count=len(clips),
            source_id=metadata["video_id"],
            source_url=metadata["url"],
        )
        source_key = program.source_id or program.source_url
        if source_key:
            previous = by_source.get(source_key)
            if previous and program_sort_key(previous) >= program_sort_key(program):
                continue
            if previous:
                unique.pop(previous.path.resolve(), None)
            by_source[source_key] = program
        unique[resolved] = program
    return list(unique.values())


def find_program(server: ThreadingHTTPServer, program_id: str | None = None) -> ProgramInfo:
    programs = discover_programs(
        getattr(server, "programs_root", None),
        server.program_dir,  # type: ignore[attr-defined]
    )
    if not programs:
        raise KeyError("No hay programas con clips en la biblioteca.")
    if not program_id:
        return programs[0]
    for program in programs:
        if program.id == program_id or program.name == program_id:
            return program
    raise KeyError(f"Programa no encontrado: {program_id}")


def find_clip(server: ThreadingHTTPServer, clip_id: str, program_id: str | None = None) -> ClipInfo:
    program = find_program(server, program_id)
    for clip in discover_clips(program.path):
        if clip.id == clip_id:
            return clip
    raise KeyError(f"Clip no encontrado: {clip_id}")


def json_bytes(value: Any) -> bytes:
    return json.dumps(value, ensure_ascii=False).encode("utf-8")


def hf_token() -> str | None:
    return (
        os.environ.get("CLIP_EDITOR_HF_TOKEN")
        or os.environ.get("HF_TOKEN")
        or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
    )


def hf_sync_repo() -> str | None:
    return os.environ.get("CLIP_EDITOR_SYNC_REPO") or os.environ.get("CLIP_DATA_REPO")


def download_sync_data(target_dir: Path, library_mode: bool = False) -> None:
    repo_id = hf_sync_repo()
    if not repo_id:
        return
    try:
        from huggingface_hub import snapshot_download
    except Exception as exc:
        raise RuntimeError("huggingface_hub no esta instalado; no puedo bajar los clips de la nube.") from exc

    target_dir.mkdir(parents=True, exist_ok=True)
    allow_patterns = ["raw/*", "vertical_9x16/*", "web_preview/*"]
    if library_mode:
        allow_patterns = ["programs/**"]
    snapshot_download(
        repo_id=repo_id,
        repo_type="dataset",
        token=hf_token(),
        local_dir=str(target_dir),
        allow_patterns=allow_patterns,
    )


def sync_base_dir(server: ThreadingHTTPServer) -> Path:
    return getattr(server, "programs_root", None) or server.program_dir  # type: ignore[attr-defined]


def upload_sync_file(server: ThreadingHTTPServer, path: Path) -> None:
    repo_id = hf_sync_repo()
    token = hf_token()
    if not repo_id or not token:
        return
    try:
        from huggingface_hub import HfApi
    except Exception:
        return
    try:
        rel_path = path.resolve().relative_to(sync_base_dir(server).resolve()).as_posix()
    except ValueError:
        return
    HfApi(token=token).upload_file(
        repo_id=repo_id,
        repo_type="dataset",
        path_or_fileobj=str(path),
        path_in_repo=rel_path,
        commit_message=f"Actualizar {rel_path}",
    )


def find_ffmpeg() -> str | None:
    app_dir = Path(__file__).resolve().parent
    candidates = [
        "/opt/homebrew/opt/ffmpeg-full/bin/ffmpeg",
        "/opt/homebrew/bin/ffmpeg",
        "/usr/local/bin/ffmpeg",
        app_dir / "ffmpeg" / "bin" / "ffmpeg.exe",
        app_dir / "bin" / "ffmpeg.exe",
        app_dir / "ffmpeg.exe",
        shutil.which("ffmpeg"),
        shutil.which("ffmpeg.exe"),
    ]
    for candidate in candidates:
        if candidate and Path(candidate).exists():
            return str(candidate)
    return None


def make_web_preview(source_path: Path, preview_path: Path, ffmpeg_bin: str) -> None:
    preview_path.parent.mkdir(parents=True, exist_ok=True)
    tmp_path = preview_path.with_name(f".{preview_path.stem}.tmp{preview_path.suffix}")
    cmd = [
        ffmpeg_bin,
        "-y",
        "-i",
        str(source_path),
        "-vf",
        "scale=720:1280:flags=lanczos,fps=30",
        "-c:v",
        "libx264",
        "-preset",
        "veryfast",
        "-crf",
        "28",
        "-c:a",
        "aac",
        "-b:a",
        "96k",
        "-movflags",
        "+faststart",
        str(tmp_path),
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        if tmp_path.exists():
            tmp_path.unlink()
        raise RuntimeError(f"No pude crear preview web: {result.stderr[-1200:]}")
    os.replace(tmp_path, preview_path)


def install_import_stubs() -> None:
    """Let the editor import clip_workflow.py without API-only dependencies."""
    if importlib.util.find_spec("anthropic") is None and "anthropic" not in sys.modules:
        module = types.ModuleType("anthropic")

        class MissingAnthropic:
            def __init__(self, *_args: Any, **_kwargs: Any) -> None:
                raise RuntimeError("anthropic no esta instalado; no hace falta para regenerar subtitulos.")

        module.Anthropic = MissingAnthropic  # type: ignore[attr-defined]
        sys.modules["anthropic"] = module


def load_clip_workflow(root_dir: Path):
    candidates = [
        root_dir / "clip_workflow.py",
        Path(__file__).resolve().parent / "clip_workflow.py",
        Path(__file__).resolve().parent.parent / "clip_workflow.py",
        Path.cwd() / "clip_workflow.py",
    ]
    for candidate in candidates:
        if candidate.exists():
            install_import_stubs()
            spec = importlib.util.spec_from_file_location("clip_workflow_editor", candidate)
            if spec and spec.loader:
                module = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(module)
                return module
    raise RuntimeError("No encontre clip_workflow.py junto a la app o en el proyecto.")


def regenerate_clip(server: ThreadingHTTPServer, clip: ClipInfo, job_id: str) -> None:
    job = server.jobs[job_id]  # type: ignore[attr-defined]
    job["status"] = "running"
    job["technical_log"] = ""
    set_job_message(job, "Preparando el clip...")
    try:
        ffmpeg_bin = find_ffmpeg()
        if not ffmpeg_bin:
            raise RuntimeError("No encontre ffmpeg. Instalar ffmpeg o ffmpeg-full.")

        set_job_message(job, "Cargando el motor de video...")
        module = load_clip_workflow(server.root_dir)  # type: ignore[attr-defined]
        module.FFMPEG_BIN = ffmpeg_bin
        module.VIDEO_PRESET = os.environ.get("CLIP_EDITOR_PRESET", "medium")
        module.VIDEO_CRF = os.environ.get("CLIP_EDITOR_CRF", getattr(module, "VIDEO_CRF", "18"))

        if importlib.util.find_spec("cv2") is None:
            job["technical_log"] += "Aviso: OpenCV no esta instalado; se usara zoom estatico.\n"
            set_job_message(job, "Regenerando con encuadre simple porque falta OpenCV...")

        clip.output_path.parent.mkdir(parents=True, exist_ok=True)
        tmp_output = clip.output_path.with_name(f".{clip.output_path.stem}.tmp{clip.output_path.suffix}")
        set_job_message(job, "Analizando el video para seguir a quien habla...")
        with contextlib.redirect_stdout(Capture(job)), contextlib.redirect_stderr(Capture(job)):
            module.encode_vertical_dynamic_zoom(clip.raw_path, clip.ass_path, tmp_output)
        set_job_message(job, "Guardando el clip actualizado...")
        os.replace(tmp_output, clip.output_path)
        upload_sync_file(server, clip.output_path)
        set_job_message(job, "Preparando una vista rápida para la web...")
        make_web_preview(clip.output_path, clip.preview_path, ffmpeg_bin)
        upload_sync_file(server, clip.preview_path)
        job["status"] = "done"
        set_job_message(job, "Clip regenerado. Ya podes revisarlo arriba.")
    except Exception:
        job["status"] = "error"
        set_job_message(job, "No se pudo regenerar el clip. Revisá que el archivo siga en la carpeta y probá de nuevo.")
        job["technical_log"] += "\n" + traceback.format_exc()


class Handler(BaseHTTPRequestHandler):
    server_version = "SubtitleEditor/1.0"

    def log_message(self, fmt: str, *args: Any) -> None:
        return None

    def is_authorized(self) -> bool:
        username = os.environ.get("CLIP_EDITOR_USERNAME", "editor")
        password = os.environ.get("CLIP_EDITOR_PASSWORD", "")
        if not password:
            return True
        header = self.headers.get("Authorization", "")
        if not header.startswith("Basic "):
            return False
        try:
            decoded = base64.b64decode(header.removeprefix("Basic ").strip()).decode("utf-8")
        except Exception:
            return False
        provided_username, sep, provided_password = decoded.partition(":")
        return bool(sep) and provided_username == username and provided_password == password

    def require_auth(self) -> None:
        self.send_response(HTTPStatus.UNAUTHORIZED)
        self.send_header("WWW-Authenticate", 'Basic realm="Clip editor"')
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.end_headers()
        self.wfile.write("Necesitas la contraseña del editor.\n".encode("utf-8"))

    def send_json(self, value: Any, status: HTTPStatus = HTTPStatus.OK) -> None:
        payload = json_bytes(value)
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def send_text(self, value: str, content_type: str = "text/html; charset=utf-8") -> None:
        payload = value.encode("utf-8")
        self.send_response(HTTPStatus.OK)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def send_file(self, path: Path, send_body: bool = True, disposition: str = "inline") -> None:
        if not path.exists() or not path.is_file():
            self.send_error(HTTPStatus.NOT_FOUND)
            return

        size = path.stat().st_size
        range_header = self.headers.get("Range", "")
        start = 0
        end = size - 1
        status = HTTPStatus.OK

        if range_header.startswith("bytes="):
            match = re.match(r"bytes=(\d*)-(\d*)", range_header)
            if match:
                if match.group(1):
                    start = int(match.group(1))
                if match.group(2):
                    end = int(match.group(2))
                end = min(end, size - 1)
                if start > end or start >= size:
                    self.send_response(HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
                    self.send_header("Content-Range", f"bytes */{size}")
                    self.end_headers()
                    return
                status = HTTPStatus.PARTIAL_CONTENT

        length = end - start + 1
        self.send_response(status)
        self.send_header("Content-Type", "video/mp4")
        self.send_header("Accept-Ranges", "bytes")
        if status == HTTPStatus.PARTIAL_CONTENT:
            self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
        self.send_header("Content-Length", str(length))
        self.send_header("Cache-Control", "private, max-age=86400, immutable")
        self.send_header("Content-Disposition", f'{disposition}; filename="{path.name}"')
        self.end_headers()

        if send_body:
            with path.open("rb") as file:
                file.seek(start)
                remaining = length
                while remaining > 0:
                    chunk = file.read(min(1024 * 1024, remaining))
                    if not chunk:
                        break
                    try:
                        self.wfile.write(chunk)
                    except CLIENT_DISCONNECT_ERRORS:
                        return
                    remaining -= len(chunk)

    def read_json(self) -> dict[str, Any]:
        length = int(self.headers.get("Content-Length", "0"))
        if length <= 0:
            return {}
        raw = self.rfile.read(length)
        return json.loads(raw.decode("utf-8"))

    def program_id_from_query(self, parsed) -> str | None:
        return parse_qs(parsed.query).get("program", [""])[0] or None

    def do_GET(self) -> None:
        if not self.is_authorized():
            self.require_auth()
            return
        parsed = urlparse(self.path)
        path = parsed.path
        try:
            if path == "/":
                self.send_text(APP_HTML)
                return
            if path == "/api/programs":
                programs = discover_programs(
                    getattr(self.server, "programs_root", None),
                    self.server.program_dir,  # type: ignore[attr-defined]
                )
                self.send_json(
                    {
                        "programs": [
                            {"id": program.id, "name": program.name, "clip_count": program.clip_count}
                            for program in programs
                        ]
                    }
                )
                return
            if path == "/api/clips":
                program = find_program(self.server, self.program_id_from_query(parsed))
                clips = discover_clips(program.path)
                self.send_json(
                    {
                        "program_id": program.id,
                        "program_name": program.name,
                        "clips": [self.clip_payload(clip, program) for clip in clips],
                    }
                )
                return
            if path.startswith("/api/clips/") and path.endswith("/subtitles"):
                clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/subtitles")).strip("/")
                clip = find_clip(self.server, clip_id, self.program_id_from_query(parsed))
                self.send_json({"subtitles": parse_ass(clip.ass_path)})
                return
            if path.startswith("/api/jobs/"):
                job_id = unquote(path.removeprefix("/api/jobs/")).strip("/")
                job = self.server.jobs.get(job_id)  # type: ignore[attr-defined]
                if not job:
                    self.send_json({"error": "Job no encontrado"}, HTTPStatus.NOT_FOUND)
                    return
                self.send_json(job)
                return
            if path.startswith("/media/"):
                qs = parse_qs(parsed.query)
                clip_id = qs.get("clip", [""])[0]
                clip = find_clip(self.server, clip_id, qs.get("program", [""])[0] or None)
                media_path = clip.preview_path if path.endswith("/preview") and clip.preview_path.exists() else clip.output_path
                disposition = "attachment" if path.endswith("/download") else "inline"
                self.send_file(media_path, disposition=disposition)
                return
            self.send_error(HTTPStatus.NOT_FOUND)
        except CLIENT_DISCONNECT_ERRORS:
            return
        except CLIENT_DISCONNECT_ERRORS:
            return
        except Exception as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.INTERNAL_SERVER_ERROR)

    def do_HEAD(self) -> None:
        if not self.is_authorized():
            self.require_auth()
            return
        parsed = urlparse(self.path)
        path = parsed.path
        try:
            if path.startswith("/media/"):
                qs = parse_qs(parsed.query)
                clip_id = qs.get("clip", [""])[0]
                clip = find_clip(self.server, clip_id, qs.get("program", [""])[0] or None)
                media_path = clip.preview_path if path.endswith("/preview") and clip.preview_path.exists() else clip.output_path
                disposition = "attachment" if path.endswith("/download") else "inline"
                self.send_file(media_path, send_body=False, disposition=disposition)
                return
            self.send_error(HTTPStatus.NOT_FOUND)
        except CLIENT_DISCONNECT_ERRORS:
            return
        except Exception as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.INTERNAL_SERVER_ERROR)

    def do_POST(self) -> None:
        if not self.is_authorized():
            self.require_auth()
            return
        parsed = urlparse(self.path)
        path = parsed.path
        try:
            if path.startswith("/api/clips/") and path.endswith("/subtitles"):
                clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/subtitles")).strip("/")
                clip = find_clip(self.server, clip_id, self.program_id_from_query(parsed))
                body = self.read_json()
                subtitles = body.get("subtitles")
                if not isinstance(subtitles, list):
                    self.send_json({"error": "Payload invalido"}, HTTPStatus.BAD_REQUEST)
                    return
                save_ass(clip.ass_path, subtitles)
                upload_sync_file(self.server, clip.ass_path)
                self.send_json({"ok": True})
                return
            if path.startswith("/api/clips/") and path.endswith("/regenerate"):
                clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/regenerate")).strip("/")
                clip = find_clip(self.server, clip_id, self.program_id_from_query(parsed))
                job_id = uuid.uuid4().hex[:12]
                self.server.jobs[job_id] = {  # type: ignore[attr-defined]
                    "status": "queued",
                    "message": "Esperando para empezar...",
                    "log": "Esperando para empezar...",
                    "technical_log": "",
                }
                thread = threading.Thread(target=regenerate_clip, args=(self.server, clip, job_id), daemon=True)
                thread.start()
                self.send_json({"job_id": job_id})
                return
            self.send_error(HTTPStatus.NOT_FOUND)
        except Exception as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.INTERNAL_SERVER_ERROR)

    def clip_payload(self, clip: ClipInfo, program: ProgramInfo) -> dict[str, Any]:
        mtime = int(clip.output_path.stat().st_mtime) if clip.output_path.exists() else int(time.time())
        preview_mtime = int(clip.preview_path.stat().st_mtime) if clip.preview_path.exists() else mtime
        video_kind = "preview" if clip.preview_path.exists() else "output"
        return {
            "id": clip.id,
            "title": clip.title,
            "has_output": clip.output_path.exists(),
            "subtitle_count": clip.subtitle_count,
            "video_url": f"/media/{video_kind}?program={program.id}&clip={clip.id}&v={preview_mtime}",
            "output_url": f"/media/output?program={program.id}&clip={clip.id}&v={mtime}",
            "download_url": f"/media/download?program={program.id}&clip={clip.id}&v={mtime}",
            "has_preview": clip.preview_path.exists(),
        }


def main() -> None:
    parser = argparse.ArgumentParser(description="Editor local de subtitulos ASS para clip-workflow.")
    parser.add_argument("--program-dir", default=".", help="Carpeta del programa con raw/ y vertical_9x16/")
    parser.add_argument("--programs-root", help="Biblioteca con varios programas (usa subcarpetas con raw/ y vertical_9x16/)")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=8787)
    parser.add_argument("--no-open", action="store_true", help="No abrir el navegador automaticamente")
    args = parser.parse_args()

    programs_root = Path(args.programs_root).expanduser().resolve() if args.programs_root else None
    program_dir = Path(args.program_dir).expanduser().resolve()
    if programs_root:
        download_sync_data(programs_root, library_mode=True)
        programs = discover_programs(programs_root, program_dir)
        if not programs:
            raise SystemExit(f"No hay programas con raw/ y vertical_9x16/ en {programs_root}")
        program_dir = programs[0].path
    else:
        download_sync_data(program_dir)
        if not (program_dir / "raw").exists():
            raise SystemExit(f"No existe raw/ en {program_dir}")

    httpd = ThreadingHTTPServer((args.host, args.port), Handler)
    httpd.program_dir = program_dir  # type: ignore[attr-defined]
    httpd.programs_root = programs_root  # type: ignore[attr-defined]
    httpd.root_dir = Path(__file__).resolve().parent  # type: ignore[attr-defined]
    httpd.jobs = {}  # type: ignore[attr-defined]

    url = f"http://{args.host}:{args.port}"
    print(f"Editor abierto en {url}")
    print(f"Biblioteca: {programs_root or program_dir}")
    if not args.no_open:
        webbrowser.open(url)
    httpd.serve_forever()


if __name__ == "__main__":
    main()