File size: 89,648 Bytes
a6cd665
0608bab
 
 
 
68e5297
be0fd54
c9c1811
68e5297
0608bab
a701adb
 
 
 
 
 
 
68e5297
a4ab9c4
 
 
c9dc548
92cb616
a4ab9c4
68e5297
a4ab9c4
68e5297
d86cc4e
8ce84cd
 
d86cc4e
0608bab
b68c304
 
0608bab
 
b68c304
0608bab
33650b0
 
6afc845
 
 
 
 
 
 
 
 
 
 
 
 
 
b68c304
 
 
 
0608bab
b68c304
 
 
 
 
 
 
 
 
 
 
 
d86cc4e
b68c304
 
 
0608bab
b68c304
d86cc4e
b68c304
 
d86cc4e
33650b0
b68c304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d86cc4e
 
b68c304
a4ab9c4
 
 
 
 
 
b3402f4
a4ab9c4
 
 
 
 
2de1d31
 
 
43cffbe
 
2de1d31
 
 
a4ab9c4
2de1d31
a4ab9c4
 
34c521f
 
 
 
 
 
 
 
 
 
 
 
 
a4ab9c4
 
 
 
 
 
 
 
 
 
 
 
e146039
 
 
 
 
 
 
a4ab9c4
 
 
 
 
e2b2b1d
a701adb
 
 
 
 
 
 
 
 
 
e2b2b1d
a4ab9c4
a701adb
a4ab9c4
 
 
 
 
ce9842f
 
 
 
 
 
 
 
 
 
 
 
 
43cffbe
a4ab9c4
43cffbe
 
 
 
 
a4ab9c4
 
 
ce9842f
43cffbe
0a446e6
 
ce9842f
 
43cffbe
0a446e6
 
 
43cffbe
a4ab9c4
 
ce9842f
43cffbe
ce9842f
 
 
a4ab9c4
 
 
 
 
 
 
ce9842f
 
 
43cffbe
a4ab9c4
ce9842f
 
a4ab9c4
43cffbe
 
a4ab9c4
 
 
ce9842f
 
 
d5d1216
a4ab9c4
2de1d31
a4ab9c4
ce9842f
a4ab9c4
 
 
 
ce9842f
030d017
 
0a446e6
43cffbe
2de1d31
 
43cffbe
 
 
 
d5d1216
43cffbe
 
030d017
43cffbe
2de1d31
0a446e6
d86cc4e
ce9842f
 
 
 
d5d1216
 
a4ab9c4
 
c059c15
2de1d31
 
d5d1216
 
a4ab9c4
d86cc4e
a4ab9c4
b68c304
 
d86cc4e
b68c304
 
d86cc4e
b68c304
 
d86cc4e
b68c304
 
d86cc4e
b68c304
 
 
 
 
 
 
 
 
 
 
 
d86cc4e
b68c304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d86cc4e
b68c304
 
 
 
 
 
 
 
 
 
 
 
 
 
d86cc4e
b68c304
 
d86cc4e
b68c304
 
 
 
 
 
 
 
d86cc4e
b68c304
 
d86cc4e
b68c304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d86cc4e
0608bab
8c2ad4f
68e5297
e02cbea
 
d013767
13e305e
d013767
 
e02cbea
d86cc4e
42b01ce
68e5297
be0fd54
d86cc4e
42b01ce
cb113a6
be0fd54
d86cc4e
42b01ce
68e5297
be0fd54
 
d86cc4e
42b01ce
68e5297
be0fd54
 
 
 
 
 
 
d86cc4e
42b01ce
68e5297
e146039
 
 
 
 
be0fd54
 
e146039
be0fd54
 
 
e146039
be0fd54
 
e146039
be0fd54
e146039
be0fd54
 
 
e146039
be0fd54
 
 
 
e146039
be0fd54
d86cc4e
e146039
42b01ce
68e5297
be0fd54
d86cc4e
ae85eba
 
42b01ce
68e5297
be0fd54
 
 
 
 
 
 
 
 
 
d86cc4e
42b01ce
68e5297
be0fd54
 
 
 
 
 
 
 
 
 
 
 
 
d86cc4e
42b01ce
68e5297
be0fd54
 
 
 
 
 
 
d86cc4e
c9dc548
604f83c
 
34c521f
604f83c
 
 
 
34c521f
 
 
c9dc548
604f83c
 
c9dc548
 
 
 
604f83c
c9dc548
e146039
c9dc548
 
 
 
 
0a446e6
c9dc548
604f83c
 
 
c9dc548
604f83c
 
2de1d31
 
604f83c
2de1d31
 
 
 
43cffbe
 
2de1d31
 
 
 
 
 
 
 
 
 
 
 
672687a
604f83c
 
 
 
 
 
dd47776
 
 
5b09386
dd47776
fa09e9f
4736201
dd47776
 
 
92cb616
604f83c
 
 
 
 
672687a
604f83c
 
 
 
34c521f
604f83c
 
34c521f
604f83c
 
672687a
13e305e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e146039
 
 
946f3aa
 
 
 
13e305e
604f83c
f2b6c38
42b01ce
87d51bb
be0fd54
 
 
f2b6c38
be0fd54
 
 
f2b6c38
 
be0fd54
f2b6c38
 
be0fd54
87d51bb
f2b6c38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d86cc4e
baba197
a4ab9c4
42b01ce
e02cbea
87d51bb
 
 
 
 
 
baba197
 
 
 
 
 
 
 
 
 
 
 
87d51bb
 
d86cc4e
42b01ce
e02cbea
 
d86cc4e
42b01ce
e02cbea
87d51bb
 
 
e02cbea
 
baba197
 
 
 
 
 
e02cbea
d86cc4e
42b01ce
e02cbea
87d51bb
 
e02cbea
 
baba197
 
 
87d51bb
d86cc4e
0608bab
abf19cd
 
 
87d51bb
e02cbea
0608bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946f3aa
 
 
 
a9291a6
 
946f3aa
abf19cd
0608bab
 
 
 
 
 
 
 
b01ddf3
 
 
 
 
 
0608bab
b01ddf3
 
 
2de1d31
 
 
 
b01ddf3
2de1d31
b01ddf3
 
 
 
0608bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b01ddf3
 
 
2de1d31
 
b01ddf3
 
 
 
 
 
ab92b74
b01ddf3
 
 
946f3aa
 
 
 
ab92b74
946f3aa
 
 
2de1d31
 
946f3aa
 
b3402f4
 
 
 
 
 
1b8fd89
 
 
 
 
 
 
 
 
 
b3402f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b01ddf3
 
 
 
 
 
 
 
 
 
 
 
 
a9291a6
 
6afc845
 
 
510ad14
 
 
6afc845
 
b01ddf3
 
 
2de1d31
030d017
43cffbe
 
030d017
2de1d31
 
030d017
43cffbe
 
 
2de1d31
 
 
43cffbe
 
2de1d31
 
43cffbe
 
2de1d31
 
43cffbe
 
2de1d31
 
030d017
afd2a57
13e305e
 
 
afd2a57
 
 
 
 
 
 
 
 
 
 
b01ddf3
afd2a57
34c521f
 
 
b01ddf3
ab92b74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b01ddf3
 
 
 
 
510ad14
5b09386
 
6afc845
510ad14
6afc845
 
 
 
 
 
510ad14
b01ddf3
510ad14
af3c71a
510ad14
b01ddf3
510ad14
 
 
a55def5
510ad14
 
 
 
 
 
 
a55def5
510ad14
 
 
 
 
 
c059c15
510ad14
132dd4e
b01ddf3
 
13e305e
510ad14
069b7aa
510ad14
 
 
 
 
 
 
 
0a446e6
 
13e305e
510ad14
 
34c521f
b01ddf3
 
 
34c521f
b01ddf3
34c521f
b01ddf3
 
 
 
 
 
afd2a57
 
 
 
86b3d9f
afd2a57
86b3d9f
afd2a57
 
 
 
86b3d9f
b01ddf3
86b3d9f
 
 
 
afd2a57
86b3d9f
 
 
 
e2001ec
 
 
13e305e
 
 
 
 
 
 
 
 
 
 
 
 
 
86b3d9f
e2b2b1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34c521f
86b3d9f
34c521f
 
13e305e
 
86b3d9f
b01ddf3
afd2a57
13e305e
86b3d9f
 
 
b01ddf3
510ad14
afd2a57
 
86b3d9f
afd2a57
 
 
 
 
 
c059c15
510ad14
 
 
 
 
 
 
 
 
 
 
b01ddf3
 
afd2a57
 
 
86b3d9f
b01ddf3
 
afd2a57
b01ddf3
 
13e305e
 
 
 
 
 
 
 
 
 
 
 
 
 
b01ddf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
069b7aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946f3aa
 
34c521f
946f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
510ad14
946f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
b01ddf3
 
 
0608bab
 
 
 
 
 
 
 
1b8fd89
0608bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995b0ca
 
 
0608bab
995b0ca
 
 
 
0608bab
995b0ca
 
 
 
0608bab
995b0ca
 
0608bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b8fd89
995b0ca
1b8fd89
0608bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b8fd89
 
 
 
 
 
0608bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abf19cd
d9a75ff
d86cc4e
42b01ce
d9a75ff
0608bab
d86cc4e
a701adb
d86cc4e
a701adb
 
586c647
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
# app.py — Video Editor API (v0.5.9) good 2 multi  rectangle
# v0.5.9:
# - Centrages "Aller à #" / "Frame #" 100% fiables (attend rendu + image chargée)
# - /mask, /mask/rename, /mask/delete : Body(...) explicite => plus de 422 silencieux
# - Bouton "Enregistrer masque" : erreurs visibles (alert) si l’API ne répond pas OK
from fastapi import FastAPI, UploadFile, File, HTTPException, Request, Body, Response
from fastapi.responses import HTMLResponse, FileResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from typing import Optional, Dict, Any
import uuid
import shutil
import cv2
import json
import time
import urllib.parse
import sys
import threading
# <<<< HUGINFACE PATCH: WARMUP IMPORTS START >>>>
from typing import List
from huggingface_hub import snapshot_download
from copy import deepcopy

# <<<< HUGINFACE PATCH: WARMUP IMPORTS END >>>>
import subprocess

import shutil as _shutil
# --- POINTEUR DE BACKEND (lit l'URL actuelle depuis une source externe) ------
import os
import httpx

print("[BOOT] Video Editor API starting…")
POINTER_URL = os.getenv("BACKEND_POINTER_URL", "").strip()
FALLBACK_BASE = os.getenv("BACKEND_BASE_URL", "http://127.0.0.1:8765").strip()
print(f"[BOOT] POINTER_URL={POINTER_URL or '(unset)'}")
print(f"[BOOT] FALLBACK_BASE={FALLBACK_BASE}")
_backend_url_cache = {"url": None, "ts": 0.0}

# <<< IMPORTANT : créer l'app AVANT tout décorateur @app.* >>>
app = FastAPI(title="Video Editor API", version="0.5.9")

# --- Instance ID (utile si plusieurs répliques derrière un proxy) -------------
INSTANCE_ID = os.getenv("INSTANCE_ID", uuid.uuid4().hex[:6])

@app.middleware("http")
async def inject_instance_id_header(request: Request, call_next):
    resp = await call_next(request)
    try:
        resp.headers["x-instance-id"] = INSTANCE_ID
    except Exception:
        pass
    return resp
# ------------------------------------------------------------------------------

def get_backend_base() -> str:
    try:
        if POINTER_URL:
            now = time.time()
            need_refresh = (not _backend_url_cache["url"] or now - _backend_url_cache["ts"] > 30)
            if need_refresh:
                r = httpx.get(POINTER_URL, timeout=5, follow_redirects=True)
                url = (r.text or "").strip()
                if url.startswith("http"):
                    _backend_url_cache["url"] = url
                    _backend_url_cache["ts"] = now
                else:
                    return FALLBACK_BASE
            return _backend_url_cache["url"] or FALLBACK_BASE
        return FALLBACK_BASE
    except Exception:
        return FALLBACK_BASE

DATA_DIR = Path("/app/data")
THUMB_DIR = DATA_DIR / "_thumbs"
MASK_DIR = DATA_DIR / "_masks"
for p in (DATA_DIR, THUMB_DIR, MASK_DIR):
    p.mkdir(parents=True, exist_ok=True)

app.mount("/data", StaticFiles(directory=str(DATA_DIR)), name="data")
app.mount("/thumbs", StaticFiles(directory=str(THUMB_DIR)), name="thumbs")


# --- PROXY VERS LE BACKEND (pas de CORS côté navigateur) --------------------
@app.api_route("/p/{full_path:path}", methods=["GET","POST","PUT","PATCH","DELETE","OPTIONS"])
async def proxy_all(full_path: str, request: Request):
    base = get_backend_base().rstrip("/")
    target = f"{base}/{full_path}"
    qs = request.url.query
    if qs:
        target = f"{target}?{qs}"
    body = await request.body()
    headers = dict(request.headers)
    headers.pop("host", None)
    async with httpx.AsyncClient(follow_redirects=True, timeout=60) as client:
        r = await client.request(request.method, target, headers=headers, content=body)
    drop = {"content-encoding","transfer-encoding","connection",
            "keep-alive","proxy-authenticate","proxy-authorization",
            "te","trailers","upgrade"}
    out_headers = {k:v for k,v in r.headers.items() if k.lower() not in drop}
    return Response(content=r.content, status_code=r.status_code, headers=out_headers)
# -------------------------------------------------------------------------------
# Global progress dict (vid_stem -> {percent, logs, done})
progress_data: Dict[str, Dict[str, Any]] = {}
# <<<< HUGINFACE PATCH: WARMUP STATE+HELPERS START >>>>
# État global du warm-up (progression, logs, etc.)
warmup_state: Dict[str, Any] = {
    "running": False,
    "percent": 0,
    "logs": [],
    "ok_count": 0,
    "done": False,
    "current": None,
    "total": 0,
    "idx": 0,
    "job_id": "default",
    # NOUVEAUX CHAMPS POUR RÉCAP
    "asked": [],           # liste demandée au lancement
    "ok_repos": [],        # liste des repos téléchargés OK
    "cache_repos": [],     # liste des repos ignorés car déjà en cache
    "downloaded_repos": [],# liste des repos réellement téléchargés pendant ce run
    "failed_repos": [],    # liste des repos en échec
    "started_at": 0.0,     # timestamp début
    "finished_at": 0.0,    # timestamp fin
}

warmup_lock = threading.Lock()
warmup_stop = threading.Event()
# --- Shim anti-avertissement Pylance (défini si absent) ----------------------
if "_hf_cache_dir" not in globals():
    def _hf_cache_dir() -> str:
        return os.path.expanduser(os.getenv("HF_HOME", "/home/user/.cache/huggingface"))

if "_is_repo_cached" not in globals():
    def _is_repo_cached(repo_id: str) -> bool:
        local_dir = os.path.join(_hf_cache_dir(), "models", repo_id.replace("/", "__"))
        try:
            return os.path.isdir(local_dir) and any(os.scandir(local_dir))
        except FileNotFoundError:
            return False
# ---------------------------------------------------------------------------

def _default_model_list() -> List[str]:
    """
    Liste par défaut lue depuis l'env WARMUP_MODELS (JSON array) sinon vide.
    Exemple env:
      WARMUP_MODELS=["runwayml/stable-diffusion-v1-5","facebook/sam2-hiera-base"]
    """
    env = (os.getenv("WARMUP_MODELS") or "").strip()
    if env:
        try:
            lst = json.loads(env)
            if isinstance(lst, list):
                # correction douce de typos connues
                fixups = {"stabilityai/sd-vae-ft-ms": "stabilityai/sd-vae-ft-mse"}
                cleaned = [fixups.get(str(x).strip(), str(x).strip()) for x in lst if str(x).strip()]
                return cleaned



        except Exception:
            pass
    return []

def _log_warmup(msg: str):
    # >>> ICONES LOGS (ajout) <<<
    if msg.startswith("[CACHE]"):
        msg = "⬛ " + msg   # ignoré: déjà en cache
    elif msg.startswith("[START]"):
        msg = "⏳ " + msg   # démarrage d'un dépôt
    elif msg.startswith("[DONE]"):
        msg = "✅ " + msg   # téléchargement OK
    elif msg.startswith("[FAIL]"):
        msg = "❌ " + msg   # échec
    elif msg.startswith("[STOP]"):
        msg = "⏹️ " + msg   # arrêt demandé

    print(f"[WARMUP] {msg}", file=sys.stdout)

    with warmup_lock:
        warmup_state["logs"].append(msg)
        if len(warmup_state["logs"]) > 400:
            warmup_state["logs"] = warmup_state["logs"][-400:]

def _dir_size_bytes(path: str) -> int:
    try:
        total = 0
        for root, _, files in os.walk(path):
            for f in files:
                try:
                    total += os.path.getsize(os.path.join(root, f))
                except Exception:
                    pass
        return total
    except Exception:
        return 0

def _download_one(repo_id: str, tries: int = 3) -> str:
    """
    Renvoie un statut précis :
      - "cache"   : déjà présent localement, rien à faire
      - "ok"      : téléchargé avec succès
      - "fail"    : échec après toutes les tentatives
      - "stopped" : arrêt demandé pendant le run
    """
    cache_home = os.path.expanduser(os.getenv("HF_HOME", "/home/user/.cache/huggingface"))
    local_dir = os.path.join(cache_home, "models", repo_id.replace("/", "__"))

    # 1) Déjà en cache ?
    try:
        if _is_repo_cached(repo_id):
            sz = _dir_size_bytes(local_dir)
            _log_warmup(f"[CACHE] {repo_id}{local_dir}{sz/1e6:.1f} MB (skip)")
            return "cache"
    except Exception:
        pass

    # 2) Tentatives de téléchargement
    for attempt in range(1, tries + 1):
        if warmup_stop.is_set():
            _log_warmup(f"[STOP] Abandon demandé avant téléchargement de {repo_id}")
            return "stopped"

        t0 = time.time()
        _log_warmup(f"[START] {repo_id} • tentative {attempt}/{tries}{local_dir}")
        try:
            snapshot_download(
                repo_id,
                local_dir=local_dir,
                local_dir_use_symlinks=False,
                resume_download=True,
            )
            dt = time.time() - t0
            sz = _dir_size_bytes(local_dir)
            _log_warmup(f"[DONE]  {repo_id}{dt:.1f}s • {sz/1e6:.1f} MB")
            return "ok"
        except Exception as e:
            dt = time.time() - t0
            _log_warmup(f"[FAIL]  {repo_id}{dt:.1f}s • {type(e).__name__}: {e}")
            time.sleep(min(10, 2 * attempt))
    return "fail"


def _warmup_thread(models: List[str]):
    ok_count = 0
    t_global = time.time()
    _log_warmup(f"[JOB] start • {len(models)} dépôts")

    for i, repo in enumerate(models):
        if warmup_stop.is_set():
            _log_warmup("[STOP] Arrêt demandé — fin du job après ce point")
            break

        with warmup_lock:
            warmup_state["idx"] = i
            warmup_state["current"] = repo
            warmup_state["percent"] = int((i / max(1, len(models))) * 100)

        res = _download_one(repo)

        with warmup_lock:
            if res == "ok":
                ok_count += 1
                warmup_state["ok_count"] = ok_count
                warmup_state.setdefault("downloaded_repos", []).append(repo)
            elif res == "cache":
                warmup_state.setdefault("cache_repos", []).append(repo)
            elif res == "fail":
                warmup_state.setdefault("failed_repos", []).append(repo)
            elif res == "stopped":
                _log_warmup("[STOP] Fin anticipée — demande reçue pendant le run")
                warmup_state["percent"] = int(((i + 1) / max(1, len(models))) * 100)
                break

            warmup_state["percent"] = int(((i + 1) / max(1, len(models))) * 100)

        if warmup_stop.is_set():
            _log_warmup("[STOP] Fin anticipée — demande reçue pendant le run")
            break

    with warmup_lock:
        warmup_state["percent"] = 100
        warmup_state["done"] = True
        warmup_state["running"] = False
        warmup_state["ok_count"] = ok_count
        warmup_state["finished_at"] = time.time()

    _log_warmup(f"[JOB] done • {ok_count}/{len(models)}{time.time()-t_global:.1f}s")

# <<<< HUGINFACE PATCH: WARMUP STATE+HELPERS END >>>>
# ---------- Helpers ----------

def _is_video(p: Path) -> bool:
    return p.suffix.lower() in {".mp4", ".mov", ".mkv", ".webm"}

def _safe_name(name: str) -> str:
    return Path(name).name.replace(" ", "_")

def _has_ffmpeg() -> bool:
    return _shutil.which("ffmpeg") is not None

def _ffmpeg_scale_filter(max_w: int = 320) -> str:
    return f"scale=min(iw\\,{max_w}):-2"

def _meta(video: Path):
    cap = cv2.VideoCapture(str(video))
    if not cap.isOpened():
        print(f"[META] OpenCV cannot open: {video}", file=sys.stdout)
        return None
    frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
    fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0) or 30.0
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
    cap.release()
    print(f"[META] {video.name} -> frames={frames}, fps={fps:.3f}, size={w}x{h}", file=sys.stdout)
    return {"frames": frames, "fps": fps, "w": w, "h": h}

def _frame_jpg(video: Path, idx: int) -> Path:
    out = THUMB_DIR / f"f_{video.stem}_{idx}.jpg"
    if out.exists():
        return out
    if _has_ffmpeg():
        m = _meta(video) or {"fps": 30.0}
        fps = float(m.get("fps") or 30.0) or 30.0
        t = max(0.0, float(idx) / fps)
        cmd = [
            "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
            "-ss", f"{t:.6f}",
            "-i", str(video),
            "-frames:v", "1",
            "-vf", _ffmpeg_scale_filter(320),
            "-q:v", "8",
            str(out)
        ]
        try:
            subprocess.run(cmd, check=True)
            return out
        except subprocess.CalledProcessError as e:
            print(f"[FRAME:FFMPEG] seek fail t={t:.4f} idx={idx}: {e}", file=sys.stdout)
    cap = cv2.VideoCapture(str(video))
    if not cap.isOpened():
        print(f"[FRAME] Cannot open video for frames: {video}", file=sys.stdout)
        raise HTTPException(500, "OpenCV ne peut pas ouvrir la vidéo.")
    total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
    if total <= 0:
        cap.release()
        print(f"[FRAME] Frame count invalid for: {video}", file=sys.stdout)
        raise HTTPException(500, "Frame count invalide.")
    idx = max(0, min(idx, total - 1))
    cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
    ok, img = cap.read()
    cap.release()
    if not ok or img is None:
        print(f"[FRAME] Cannot read idx={idx} for: {video}", file=sys.stdout)
        raise HTTPException(500, "Impossible de lire la frame demandée.")
    h, w = img.shape[:2]
    if w > 320:
        new_w = 320
        new_h = int(h * (320.0 / w)) or 1
        img = cv2.resize(img, (new_w, new_h), interpolation=getattr(cv2, 'INTER_AREA', cv2.INTER_LINEAR))
    cv2.imwrite(str(out), img, [int(cv2.IMWRITE_JPEG_QUALITY), 80])
    return out

def _poster(video: Path) -> Path:
    out = THUMB_DIR / f"poster_{video.stem}.jpg"
    if out.exists():
        return out
    try:
        cap = cv2.VideoCapture(str(video))
        cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
        ok, img = cap.read()
        cap.release()
        if ok and img is not None:
            cv2.imwrite(str(out), img)
    except Exception as e:
        print(f"[POSTER] Failed: {e}", file=sys.stdout)
    return out

def _mask_file(vid: str) -> Path:
    return MASK_DIR / f"{Path(vid).name}.json"

def _load_masks(vid: str) -> Dict[str, Any]:
    f = _mask_file(vid)
    if f.exists():
        try:
            return json.loads(f.read_text(encoding="utf-8"))
        except Exception as e:
            print(f"[MASK] Read fail {vid}: {e}", file=sys.stdout)
    return {"video": vid, "masks": []}

def _save_masks(vid: str, data: Dict[str, Any]):
    _mask_file(vid).write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")

def _gen_thumbs_background(video: Path, vid_stem: str):
    progress_data[vid_stem] = {'percent': 0, 'logs': [], 'done': False}
    try:
        m = _meta(video)
        if not m:
            progress_data[vid_stem]['logs'].append("Erreur métadonnées")
            progress_data[vid_stem]['done'] = True
            return
        total_frames = int(m["frames"] or 0)
        if total_frames <= 0:
            progress_data[vid_stem]['logs'].append("Aucune frame détectée")
            progress_data[vid_stem]['done'] = True
            return
        for f in THUMB_DIR.glob(f"f_{video.stem}_*.jpg"):
            f.unlink(missing_ok=True)
        if _has_ffmpeg():
            out_tpl = str(THUMB_DIR / f"f_{video.stem}_%d.jpg")
            cmd = [
                "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
                "-i", str(video),
                "-vf", _ffmpeg_scale_filter(320),
                "-q:v", "8",
                "-start_number", "0",
                out_tpl
            ]
            progress_data[vid_stem]['logs'].append("FFmpeg: génération en cours…")
            proc = subprocess.Popen(cmd)
            last_report = -1
            while proc.poll() is None:
                generated = len(list(THUMB_DIR.glob(f"f_{video.stem}_*.jpg")))
                percent = int(min(99, (generated / max(1, total_frames)) * 100))
                progress_data[vid_stem]['percent'] = percent
                if generated != last_report and generated % 50 == 0:
                    progress_data[vid_stem]['logs'].append(f"Gen {generated}/{total_frames}")
                    last_report = generated
                time.sleep(0.4)
            proc.wait()
            generated = len(list(THUMB_DIR.glob(f"f_{video.stem}_*.jpg")))
            progress_data[vid_stem]['percent'] = 100
            progress_data[vid_stem]['logs'].append("OK FFmpeg: {}/{} thumbs".format(generated, total_frames))
            progress_data[vid_stem]['done'] = True
            print(f"[PRE-GEN:FFMPEG] {generated} thumbs for {video.name}", file=sys.stdout)
        else:
            progress_data[vid_stem]['logs'].append("OpenCV (FFmpeg non dispo) : génération…")
            cap = cv2.VideoCapture(str(video))
            if not cap.isOpened():
                progress_data[vid_stem]['logs'].append("OpenCV ne peut pas ouvrir la vidéo.")
                progress_data[vid_stem]['done'] = True
                return
            idx = 0
            last_report = -1
            while True:
                ok, img = cap.read()
                if not ok or img is None:
                    break
                out = THUMB_DIR / f"f_{video.stem}_{idx}.jpg"
                h, w = img.shape[:2]
                if w > 320:
                    new_w = 320
                    new_h = int(h * (320.0 / w)) or 1
                    img = cv2.resize(img, (new_w, new_h), interpolation=getattr(cv2, 'INTER_AREA', cv2.INTER_LINEAR))
                cv2.imwrite(str(out), img, [int(cv2.IMWRITE_JPEG_QUALITY), 80])
                idx += 1
                if idx % 50 == 0:
                    progress_data[vid_stem]['percent'] = int(min(99, (idx / max(1, total_frames)) * 100))
                    if idx != last_report:
                        progress_data[vid_stem]['logs'].append(f"Gen {idx}/{total_frames}")
                        last_report = idx
            cap.release()
            progress_data[vid_stem]['percent'] = 100
            progress_data[vid_stem]['logs'].append(f"OK OpenCV: {idx}/{total_frames} thumbs")
            progress_data[vid_stem]['done'] = True
            print(f"[PRE-GEN:CV2] {idx} thumbs for {video.name}", file=sys.stdout)
    except Exception as e:
        progress_data[vid_stem]['logs'].append(f"Erreur: {e}")
        progress_data[vid_stem]['done'] = True

# ---------- API ----------
@app.get("/", tags=["meta"])
def root():
    return {
        "ok": True,
                                "routes": ["/", "/health", "/files", "/upload", "/meta/{vid}", "/frame_idx", "/poster/{vid}", "/window/{vid}",
                   "/mask", "/mask/{vid}", "/mask/rename", "/mask/delete", "/progress/{vid_stem}", "/ui",
                   "/warmup/start", "/warmup/status", "/warmup/stop", "/warmup/audit", "/warmup/catalog"]

    }

@app.get("/health", tags=["meta"])
def health():
    return {"status": "ok"}

@app.get("/_env", tags=["meta"])
def env_info():
    return {"pointer_set": bool(POINTER_URL), "resolved_base": get_backend_base()}

@app.get("/files", tags=["io"])
def files():
    items = [p.name for p in sorted(DATA_DIR.glob("*")) if _is_video(p)]
    return {"count": len(items), "items": items}

@app.get("/meta/{vid}", tags=["io"])
def video_meta(vid: str):
    v = DATA_DIR / vid
    if not v.exists():
        raise HTTPException(404, "Vidéo introuvable")
    m = _meta(v)
    if not m:
        raise HTTPException(500, "Métadonnées indisponibles")
    return m

@app.post("/upload", tags=["io"])
async def upload(request: Request, file: UploadFile = File(...), redirect: Optional[bool] = True):
    # Sécuriser le nom de fichier (UploadFile.filename peut être None)
    fname = file.filename or "upload.mp4"
    base = _safe_name(fname)
    ext = (Path(base).suffix or ".mp4").lower()

    if ext not in {".mp4", ".mov", ".mkv", ".webm"}:
        raise HTTPException(400, "Formats acceptés : mp4/mov/mkv/webm")

    dst = DATA_DIR / base
    if dst.exists():
        dst = DATA_DIR / f"{Path(base).stem}__{uuid.uuid4().hex[:8]}{ext}"

    with dst.open("wb") as f:
        shutil.copyfileobj(file.file, f)

    print(f"[UPLOAD] Saved {dst.name} ({dst.stat().st_size} bytes)", file=sys.stdout)

    _poster(dst)
    stem = dst.stem
    threading.Thread(target=_gen_thumbs_background, args=(dst, stem), daemon=True).start()

    accept = (request.headers.get("accept") or "").lower()
    if redirect or "text/html" in accept:
        msg = urllib.parse.quote(f"Vidéo importée : {dst.name}. Génération thumbs en cours…")
        return RedirectResponse(url=f"/ui?v={urllib.parse.quote(dst.name)}&msg={msg}", status_code=303)

    return {"name": dst.name, "size_bytes": dst.stat().st_size, "gen_started": True}


@app.get("/progress/{vid_stem}", tags=["io"])
def progress(vid_stem: str):
    return progress_data.get(vid_stem, {'percent': 0, 'logs': [], 'done': False})



@app.delete("/delete/{vid}", tags=["io"])
def delete_video(vid: str):
    v = DATA_DIR / vid
    if not v.exists():
        raise HTTPException(404, "Vidéo introuvable")
    (THUMB_DIR / f"poster_{v.stem}.jpg").unlink(missing_ok=True)
    for f in THUMB_DIR.glob(f"f_{v.stem}_*.jpg"):
        f.unlink(missing_ok=True)
    _mask_file(vid).unlink(missing_ok=True)
    v.unlink(missing_ok=True)
    print(f"[DELETE] {vid}", file=sys.stdout)
    return {"deleted": vid}

@app.get("/frame_idx", tags=["io"])
def frame_idx(vid: str, idx: int):
    v = DATA_DIR / vid
    if not v.exists():
        raise HTTPException(404, "Vidéo introuvable")
    try:
        out = _frame_jpg(v, int(idx))
        print(f"[FRAME] OK {vid} idx={idx}", file=sys.stdout)
        return FileResponse(str(out), media_type="image/jpeg")
    except HTTPException as he:
        print(f"[FRAME] FAIL {vid} idx={idx}: {he.detail}", file=sys.stdout)
        raise
    except Exception as e:
        print(f"[FRAME] FAIL {vid} idx={idx}: {e}", file=sys.stdout)
        raise HTTPException(500, "Frame error")

@app.get("/poster/{vid}", tags=["io"])
def poster(vid: str):
    v = DATA_DIR / vid
    if not v.exists():
        raise HTTPException(404, "Vidéo introuvable")
    p = _poster(v)
    if p.exists():
        return FileResponse(str(p), media_type="image/jpeg")
    raise HTTPException(404, "Poster introuvable")

# Remove redundant import and ensure imports are at the top of the file
@app.post("/warmup/start", tags=["warmup"])
async def warmup_start(payload: Optional[Dict[str, Any]] = Body(None)):
    """
    Démarre le téléchargement séquentiel des modèles.
    Corps JSON optionnel: { "models": ["repo1","repo2", ...] }
    Si vide: lit la variable d'env WARMUP_MODELS (JSON).
    """
    # Nettoie un éventuel stop précédent pour permettre un nouveau run
    warmup_stop.clear()

    # 1) Prendre la liste fournie si présente
    if payload and isinstance(payload, dict):
        models = [str(x).strip() for x in (payload.get("models") or []) if str(x).strip()]
    else:
        models = []

    # 2) Sinon charger la liste par défaut (depuis WARMUP_MODELS)
    if not models:
        models = _default_model_list()

    # 3) Normaliser (fix typos) + dédoublonner
    fixups = {"stabilityai/sd-vae-ft-ms": "stabilityai/sd-vae-ft-mse"}
    models = [fixups.get(m, m) for m in models]
    seen = set()
    models = [m for m in models if not (m in seen or seen.add(m))]

    # 4) Encore vide ? -> 400
    if not models:
        raise HTTPException(400, "Aucun modèle fourni (payload.models) et WARMUP_MODELS vide")

    # 5) Lancer le job
    with warmup_lock:
        if warmup_state.get("running"):
            return {"ok": False, "already_running": True, "status": deepcopy(warmup_state)}
        # RESET d’un nouveau job
        job_id = uuid.uuid4().hex[:8]
        warmup_state.update({
            "job_id": job_id,
            "asked": models[:],
            "ok_repos": [],
            "cache_repos": [],
            "downloaded_repos": [],
            "failed_repos": [],
            "ok_count": 0,
            "logs": [],
            "idx": 0,
            "total": len(models),
            "percent": 0,
            "running": True,
            "done": False,
            "current": None,
            "started_at": time.time(),
            "finished_at": 0.0,
        })
        th = threading.Thread(target=_warmup_thread, args=(models,), daemon=True)
        th.start()

    return {"ok": True, "started": True, "total": len(models), "job_id": job_id}

@app.get("/warmup/status", tags=["warmup"])
def warmup_status():
    """Retourne l'état courant du warm-up (progression, logs, etc.)."""
    # On copie l'état sous verrou pour éviter les lectures concurrentes
    with warmup_lock:
        data = deepcopy(warmup_state)
        data["instance_id"] = INSTANCE_ID  # aide au diagnostic multi-répliques

    # Infos d’audit du cache (hors verrou)
    cached = _list_cached_repos()
    data["audit_count"] = len(cached)
    data["audit_cached"] = cached

    data["ts"] = time.time()
    return data

@app.post("/warmup/stop", tags=["warmup"])
def warmup_stop_api():
    """Demande l'arrêt propre (on termine le modèle en cours puis on stoppe)."""
    with warmup_lock:
        running = bool(warmup_state.get("running"))
    if running:
        warmup_stop.set()
        _log_warmup("[STOP] Demande d'arrêt reçue — arrêt après le dépôt en cours")
        return {"ok": True, "was_running": True}
    return {"ok": True, "was_running": False}

# >>> B1_END warmup_routes


# >>> B2_BEGIN warmup_audit
def _hf_cache_dir() -> str:
    return os.path.expanduser(os.getenv("HF_HOME", "/home/user/.cache/huggingface"))

def _is_repo_cached(repo_id: str) -> bool:
    local_dir = os.path.join(_hf_cache_dir(), "models", repo_id.replace("/", "__"))
    try:
        return os.path.isdir(local_dir) and any(os.scandir(local_dir))
    except FileNotFoundError:
        return False

def _list_cached_repos() -> List[str]:
    base = os.path.join(_hf_cache_dir(), "models")
    out: List[str] = []
    try:
        for e in os.scandir(base):
            if e.is_dir():
                out.append(e.name.replace("__", "/"))
    except FileNotFoundError:
        pass
    return sorted(out)

@app.get("/warmup/audit", tags=["warmup"])
def warmup_audit():
    """
    Retourne l'état du cache HF côté serveur.
    - cached: tous les repos détectés localement
    - present_default / missing_default: croisement avec WARMUP_MODELS (si défini)
    """
    cached = _list_cached_repos()
    defaults = _default_model_list()
    present_default = [r for r in defaults if r in cached]
    missing_default = [r for r in defaults if r not in cached]
    return {
        "count": len(cached),
        "cached": cached,
        "present_default": present_default,
        "missing_default": missing_default,
    }
@app.get("/warmup/catalog", tags=["warmup"])
def warmup_catalog():
    try:
        env = (os.getenv("WARMUP_MODELS") or "").strip()
        base = []
        if env:
            try:
                lst = json.loads(env)
                if isinstance(lst, list) and lst:
                    base = [str(x).strip() for x in lst if str(x).strip()]
            except Exception:
                base = []
    except Exception:
        base = []

    if not base:
        base = [
            "runwayml/stable-diffusion-v1-5",
            "facebook/sam-vit-base",
            "stabilityai/sd-vae-ft-mse",
            "lixiaowen/diffuEraser",
            "facebook/sam2-hiera-base",
        ]
    # Correction douce de typos connues (catalog)
    fixups = {"stabilityai/sd-vae-ft-ms": "stabilityai/sd-vae-ft-mse"}
    base = [fixups.get(m, m) for m in base]

    seen = set()
    out = [m for m in base if not (m in seen or seen.add(m))]
    return {"count": len(out), "models": out}


# >>> A1_BEGIN window_fix
@app.get("/window/{vid}", tags=["io"])
def window(vid: str, center: int = 0, count: int = 21):
    v = DATA_DIR / vid
    if not v.exists():
        raise HTTPException(404, "Vidéo introuvable")

    m = _meta(v)
    if not m:
        raise HTTPException(500, "Métadonnées indisponibles")

    frames = int(m.get("frames") or 0)
    count = max(3, int(count))
    center = max(0, min(int(center), max(0, frames - 1)))

    if frames <= 0:
        print(f"[WINDOW] frames=0 for {vid}", file=sys.stdout)
        return {
            "vid": vid,
            "start": 0,
            "count": 0,
            "selected": 0,
            "items": [],
            "frames": 0,
        }

    if frames <= count:
        start = 0
        sel = center
        n = frames
    else:
        start = max(0, min(center - (count // 2), frames - count))
        n = count
        sel = center - start

    items = []
    bust = int(time.time() * 1000)
    for i in range(n):
        idx = start + i
        url = f"/thumbs/f_{v.stem}_{idx}.jpg?b={bust}"
        items.append({"i": i, "idx": idx, "url": url})

    print(f"[WINDOW] {vid} start={start} n={n} sel={sel} frames={frames}", file=sys.stdout)
    return {
        "vid": vid,
        "start": start,
        "count": n,
        "selected": sel,
        "items": items,
        "frames": frames,
    }
# >>> A1_END window_fix

# ----- Masques -----

@app.post("/mask", tags=["mask"])
async def save_mask(payload: Dict[str, Any] = Body(...)):
    vid = payload.get("vid")
    if not vid:
        raise HTTPException(400, "vid manquant")
    pts = payload.get("points") or []
    if len(pts) != 4:
        raise HTTPException(400, "points rect (x1,y1,x2,y2) requis")
    data = _load_masks(vid)
    m = {
        "id": uuid.uuid4().hex[:10],
        "time_s": float(payload.get("time_s") or 0.0),
        "frame_idx": int(payload.get("frame_idx") or 0),
        "shape": "rect",
        "points": [float(x) for x in pts],
        "color": payload.get("color") or "#10b981",
        "note": payload.get("note") or ""
    }
    data.setdefault("masks", []).append(m)
    _save_masks(vid, data)
    print(f"[MASK] save {vid} frame={m['frame_idx']} note={m['note']}", file=sys.stdout)
    return {"saved": True, "mask": m}

@app.get("/mask/{vid}", tags=["mask"])
def list_masks(vid: str):
    return _load_masks(vid)

@app.post("/mask/rename", tags=["mask"])
async def rename_mask(payload: Dict[str, Any] = Body(...)):
    vid = payload.get("vid")
    mid = payload.get("id")
    new_note = (payload.get("note") or "").strip()
    if not vid or not mid:
        raise HTTPException(400, "vid et id requis")
    data = _load_masks(vid)
    for m in data.get("masks", []):
        if m.get("id") == mid:
            m["note"] = new_note
            _save_masks(vid, data)
            return {"ok": True}
    raise HTTPException(404, "Masque introuvable")

@app.post("/mask/delete", tags=["mask"])
async def delete_mask(payload: Dict[str, Any] = Body(...)):
    vid = payload.get("vid")
    mid = payload.get("id")
    if not vid or not mid:
        raise HTTPException(400, "vid et id requis")
    data = _load_masks(vid)
    data["masks"] = [m for m in data.get("masks", []) if m.get("id") != mid]
    _save_masks(vid, data)
    return {"ok": True}

# ---------- UI (multi-rects par frame) ----------
HTML_TEMPLATE = r"""
<!doctype html>
<html lang="fr"><meta charset="utf-8">
<title>Video Editor</title>
<style>
 :root{--b:#e5e7eb;--muted:#64748b; --controlsH:44px; --active-bg:#dbeafe; --active-border:#2563eb;}
 *{box-sizing:border-box}
 body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,'Helvetica Neue',Arial;margin:16px;color:#111}
 h1{margin:0 0 8px 0}
 .topbar{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:10px}
 .card{border:1px solid var(--b);border-radius:12px;padding:10px;background:#fff}
 .muted{color:var(--muted);font-size:13px}
 .layout{display:grid;grid-template-columns:1fr 320px;gap:14px;align-items:start}
 .viewer{max-width:1024px;margin:0 auto; position:relative}
 .player-wrap{position:relative; padding-bottom: var(--controlsH);}
 video{display:block;width:100%;height:auto;max-height:58vh;border-radius:10px;box-shadow:0 0 0 1px #ddd}
 #editCanvas{position:absolute;left:0;right:0;top:0;bottom:var(--controlsH);border-radius:10px;pointer-events:none}
 .timeline-container{margin-top:10px}
 .timeline{position:relative;display:flex;flex-wrap:nowrap;gap:8px;overflow-x:auto;overflow-y:hidden;padding:6px;border:1px solid var(--b);border-radius:10px;-webkit-overflow-scrolling:touch;width:100%}
 .thumb{flex:0 0 auto;display:inline-block;position:relative;transition:transform 0.2s;text-align:center}
 .thumb:hover{transform:scale(1.05)}
 .thumb img{height:var(--thumbH,110px);display:block;border-radius:6px;cursor:pointer;border:2px solid transparent;object-fit:cover}
 .thumb img.sel{border-color:var(--active-border)}
 .thumb img.sel-strong{outline:3px solid var(--active-border);box-shadow:0 0 0 3px #fff,0 0 0 5px var(--active-border)}
 .thumb.hasmask::after{content:"★";position:absolute;right:6px;top:4px;color:#f5b700;text-shadow:0 0 3px rgba(0,0,0,0.35);font-size:16px}
 .thumb-label{font-size:11px;color:var(--muted);margin-top:2px;display:block}
 .timeline.filter-masked .thumb:not(.hasmask){display:none}
 .tools .row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
 .btn{padding:8px 12px;border-radius:8px;border:1px solid var(--b);background:#f8fafc;cursor:pointer;transition:background 0.2s, border 0.2s}
 .btn:hover{background:var(--active-bg);border-color:var(--active-border)}
 .btn.active,.btn.toggled{background:var(--active-bg);border-color:var(--active-border)}
 .swatch{width:20px;height:20px;border-radius:50%;border:2px solid #fff;box-shadow:0 0 0 1px #ccc;cursor:pointer;transition:box-shadow 0.2s}
 .swatch.sel{box-shadow:0 0 0 2px var(--active-border)}
 ul.clean{list-style:none;padding-left:0;margin:6px 0}
 ul.clean li{margin:2px 0;display:flex;align-items:center;gap:6px}
 .rename-btn{font-size:12px;padding:2px 4px;border:none;background:transparent;cursor:pointer;color:var(--muted);transition:color 0.2s}
 .rename-btn:hover{color:#2563eb}
 .delete-btn{color:#ef4444;font-size:14px;cursor:pointer;transition:color 0.2s}
 .delete-btn:hover{color:#b91c1c}
 #loading-indicator{display:none;margin-top:6px;color:#f59e0b}
 .portion-row{display:flex;gap:6px;align-items:center;margin-top:8px}
 .portion-input{width:70px}
 #tl-progress-bar{background:#f3f4f6;border-radius:4px;height:8px;margin-top:10px}
 #tl-progress-fill{background:#2563eb;height:100%;width:0;border-radius:4px}
 #popup {position:fixed;top:20%;left:50%;transform:translate(-50%, -50%);background:#fff;padding:20px;border-radius:8px;box-shadow:0 0 10px rgba(0,0,0,0.2);z-index:1000;display:none;min-width:320px}
 #popup-progress-bar{background:#f3f4f6;border-radius:4px;height:8px;margin:10px 0}
 #popup-progress-fill{background:#2563eb;height:100%;width:0;border-radius:4px}
 #popup-logs {max-height:200px;overflow:auto;font-size:12px;color:#6b7280}
 #hud{position:absolute;right:10px;top:10px;background:rgba(17,24,39,.6);color:#fff;font-size:12px;padding:4px 8px;border-radius:6px}
 #toast{position:fixed;right:12px;bottom:12px;display:flex;flex-direction:column;gap:8px;z-index:2000}
 .toast-item{background:#111827;color:#fff;padding:8px 12px;border-radius:8px;box-shadow:0 6px 16px rgba(0,0,0,.25);opacity:.95}
 #portionBand{position:absolute;top:0;height:calc(var(--thumbH,110px) + 24px);background:rgba(37,99,235,.12);pointer-events:none;display:none}
 #inHandle,#outHandle{position:absolute;top:0;height:calc(var(--thumbH,110px) + 24px);width:6px;background:rgba(37,99,235,.9);border-radius:2px;cursor:ew-resize;display:none;pointer-events:auto}
 .playhead{position:absolute;top:0;bottom:0;width:2px;background:var(--active-border);opacity:.9;pointer-events:none;display:block}
 .repo-list{max-height:320px; overflow:auto; border:1px solid var(--b); border-radius:8px; padding:6px}
 .repo-item{display:flex; align-items:center; gap:8px; padding:6px; border-bottom:1px solid #f3f4f6}
 .repo-item:last-child{border-bottom:none}
 .repo-id{font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size:12px}
 /* Popups déplaçables : poignée = <h3> */
 #warmupPopup h3, #warmupSelectPopup h3 { cursor: move; user-select: none; }

</style>
<h1>🎬 Video Editor</h1>
<div class="topbar card">
 <form action="/upload?redirect=1" method="post" enctype="multipart/form-data" style="display:flex;gap:8px;align-items:center" id="uploadForm">
 <strong>Charger une vidéo :</strong>
 <input type="file" name="file" accept="video/*" required>
 <button class="btn" type="submit">Uploader</button>
 </form>
 <span class="muted" id="msg">__MSG__</span>






 <span class="muted">Liens : <a href="/docs" target="_blank">/docs</a> • <a href="/files" target="_blank">/files</a></span>

<!-- >>> A2B2_BEGIN warmup_topbar -->
<div style="display:flex;gap:8px;align-items:center">
    <button id="warmupStartBtn" class="btn" title="Télécharger les modèles (séquentiel)">🔥 Télécharger modèles</button>
  <button id="warmupStopBtn" class="btn" title="Arrêter le téléchargement en cours" style="display:none">⏹️ Stop téléchargement</button>
  <button id="warmupSelectBtn" class="btn" title="Sélectionner les repos à télécharger">🧩 Choisir modèles</button>
  <button id="warmupLogsBtn" class="btn" title="Voir les logs du téléchargement">📜 Logs téléchargement</button>
  <span id="warmupStatus" class="muted"></span>

</div>
<!-- >>> A2B2_END warmup_topbar -->


</div>
<div class="layout">
 <div>
  <div class="viewer card" id="viewerCard">
   <div class="player-wrap" id="playerWrap">
    <video id="player" controls playsinline poster="/poster/__VID__">
     <source id="vidsrc" src="/data/__VID__" type="video/mp4">
    </video>
    <canvas id="editCanvas"></canvas>
    <div id="hud"></div>
   </div>
   <div class="muted" style="margin-top:6px">
    <label>Frame # <input id="goFrame" type="number" min="1" value="1" style="width:90px"> </label>
    <label>à <input id="endPortion" class="portion-input" type="number" min="1" placeholder="Optionnel pour portion"></label>
    <button id="isolerBoucle" class="btn">Isoler & Boucle</button>
    <button id="resetFull" class="btn" style="display:none">Retour full</button>
    <span id="posInfo" style="margin-left:10px"></span>
    <span id="status" style="margin-left:10px;color:#2563eb"></span>
   </div>
  </div>
  <div class="card timeline-container">
   <h4 style="margin:2px 0 8px 0">Timeline</h4>
   <div class="row" id="tlControls" style="margin:4px 0 8px 0;gap:8px;align-items:center">
     <button id="btnFollow" class="btn" title="Centrer pendant la lecture (OFF par défaut)">🔭 Suivre</button>
     <button id="btnFilterMasked" class="btn" title="Afficher uniquement les frames avec masque">⭐ Masquées</button>
     <label class="muted">Zoom <input id="zoomSlider" type="range" min="80" max="180" value="110" step="10"></label>
     <label class="muted">Aller à # <input id="gotoInput" type="number" min="1" style="width:90px"></label>
     <button id="gotoBtn" class="btn">Aller</button>
     <span class="muted" id="maskedCount"></span>
   </div>
   <div id="timeline" class="timeline"></div>
   <div class="muted" id="tlNote" style="margin-top:6px;display:none">Mode secours: vignettes générées dans le navigateur.</div>
   <div id="loading-indicator">Chargement des frames...</div>
   <div id="tl-progress-bar"><div id="tl-progress-fill"></div></div>
  </div>
 </div>
 <div class="card tools">
  <div class="row"><span class="muted">Mode : <strong id="modeLabel">Lecture</strong></span></div>
  <div class="row" style="margin-top:6px">
   <button id="btnEdit" class="btn" title="Passer en mode édition pour dessiner un masque">✏️ Éditer cette image</button>
   <button id="btnBack" class="btn" style="display:none" title="Retour au mode lecture">🎬 Retour lecteur</button>
   <button id="btnSave" class="btn" style="display:none" title="Enregistrer tous les masques dessinés sur cette frame">💾 Enregistrer masque</button>
   <button id="btnClear" class="btn" style="display:none" title="Effacer le dernier rectangle de cette frame">🧽 Effacer sélection</button>
  </div>
  <div style="margin-top:10px">
   <div class="muted">Couleur</div>
   <div class="row" id="palette" style="margin-top:6px">
    <div class="swatch" data-c="#10b981" style="background:#10b981" title="Vert"></div>
    <div class="swatch" data-c="#2563eb" style="background:#2563eb" title="Bleu"></div>
    <div class="swatch" data-c="#ef4444" style="background:#ef4444" title="Rouge"></div>
    <div class="swatch" data-c="#f59e0b" style="background:#f59e0b" title="Orange"></div>
    <div class="swatch" data-c="#a21caf" style="background:#a21caf" title="Violet"></div>
   </div>
  </div>
  <div style="margin-top:12px">
   <details open>
    <summary><strong>Masques</strong></summary>
    <div id="maskList" class="muted">—</div>
    <button class="btn" style="margin-top:8px" id="exportBtn" title="Exporter la vidéo avec les masques appliqués (bientôt IA)">Exporter vidéo modifiée</button>
   </details>
   <div style="margin-top:6px">
    <strong>Vidéos disponibles</strong>
    <ul id="fileList" class="clean muted" style="max-height:180px;overflow:auto">Chargement…</ul>
   </div>
  </div>
 </div>
</div>
<div id="popup">
 <h3>Génération thumbs en cours</h3>
 <div id="popup-progress-bar"><div id="popup-progress-fill"></div></div>
 <div id="popup-logs"></div>
</div>

<!-- >>> A2B2_BEGIN warmup_popup -->
<div id="warmupPopup" style="display:none; position:fixed; top:22%; left:50%; transform:translate(-50%,-50%); background:#fff; padding:20px; border-radius:8px; box-shadow:0 0 10px rgba(0,0,0,0.2); z-index:1001; min-width:360px">
    <h3>Téléchargement des modèles (warm-up)</h3>

  <div class="muted" id="warmupPopupStatus">—</div>
  <div style="background:#f3f4f6;border-radius:4px;height:8px;margin:10px 0">
    <div id="warmup-progress-fill" style="background:#2563eb;height:100%;width:0;border-radius:4px"></div>
  </div>
  <div id="warmup-logs" style="max-height:220px; overflow:auto; font-size:12px; color:#6b7280; white-space:pre-wrap"></div>
  <div style="margin-top:10px; display:flex; gap:8px; justify-content:flex-end">
          <button id="warmupCopyBtn" class="btn" title="Copier le contenu">Copier</button>
    <button id="warmupCloseBtn" class="btn">Fermer</button>
  </div>
</div>
<div id="warmupSelectPopup" style="display:none; position:fixed; top:24%; left:50%; transform:translate(-50%,-50%); background:#fff; padding:20px; border-radius:8px; box-shadow:0 0 10px rgba(0,0,0,0.2); z-index:1001; min-width:420px; max-width:720px; width:90%">
  <h3>Sélection des modèles à préparer</h3>
  <div id="repoList" class="repo-list"></div>
  <div style="margin-top:12px; display:flex; gap:8px; justify-content:flex-end; flex-wrap:wrap">
          <button id="selectCopyBtn" class="btn" title="Copier la liste visible">Copier</button>
    <button id="selectAllBtn" class="btn">Tout cocher</button>
    <button id="selectNoneBtn" class="btn">Tout décocher</button>
    <button id="selectCancelBtn" class="btn">Annuler</button>
        <button id="launchSelectedBtn" class="btn">Lancer le téléchargement</button>

  </div>
</div>
<!-- >>> A2B2_END warmup_popup -->
<div id="toast"></div>
<script>
const serverVid = "__VID__";
const serverMsg = "__MSG__";
document.getElementById('msg').textContent = serverMsg;
// Après affichage du message, on retire ?msg=... de l'URL pour éviter qu'il persiste au refresh.
try {
  const u = new URL(location.href);
  if (u.searchParams.has('msg')) {
    u.searchParams.delete('msg');
    const q = u.searchParams.toString();
    history.replaceState({}, '', u.pathname + (q ? ('?' + q) : ''));
  }
} catch (_) {}


// Références DOM globales pour l’éditeur (nécessaires à tout le code en dessous)
const statusEl = document.getElementById('status');
const player = document.getElementById('player');
const srcEl = document.getElementById('vidsrc');
const canvas = document.getElementById('editCanvas');
const ctx = canvas.getContext('2d');
const modeLabel = document.getElementById('modeLabel');
const btnEdit = document.getElementById('btnEdit');
const btnBack = document.getElementById('btnBack');
const btnSave = document.getElementById('btnSave');
const btnClear = document.getElementById('btnClear');
const posInfo = document.getElementById('posInfo');
const goFrame = document.getElementById('goFrame');
const palette = document.getElementById('palette');
const fileList = document.getElementById('fileList');
const tlBox = document.getElementById('timeline');
const tlNote = document.getElementById('tlNote');
const playerWrap = document.getElementById('playerWrap');
const loadingInd = document.getElementById('loading-indicator');
const isolerBoucle = document.getElementById('isolerBoucle');
const resetFull = document.getElementById('resetFull');
const endPortion = document.getElementById('endPortion');
const popup = document.getElementById('popup');
const popupLogs = document.getElementById('popup-logs');
const tlProgressFill = document.getElementById('tl-progress-fill');
const popupProgressFill = document.getElementById('popup-progress-fill');
const btnFollow = document.getElementById('btnFollow');
const btnFilterMasked = document.getElementById('btnFilterMasked');
const zoomSlider = document.getElementById('zoomSlider');
const maskedCount = document.getElementById('maskedCount');
const hud = document.getElementById('hud');
const toastWrap = document.getElementById('toast');
const gotoInput = document.getElementById('gotoInput');


// >>> A2B2_BEGIN warmup_dom
// Références DOM (topbar + popup)
const warmupStartBtn   = document.getElementById('warmupStartBtn');
const warmupStopBtn    = document.getElementById('warmupStopBtn');
const warmupLogsBtn    = document.getElementById('warmupLogsBtn');
const warmupStatusEl   = document.getElementById('warmupStatus');

const warmupPopup        = document.getElementById('warmupPopup');
const warmupPopupStatus  = document.getElementById('warmupPopupStatus');
const warmupProgressFill = document.getElementById('warmup-progress-fill');
const warmupLogs         = document.getElementById('warmup-logs');
const warmupCopyBtn       = document.getElementById('warmupCopyBtn');
const warmupSelectCopyBtn = document.getElementById('warmupSelectCopyBtn');

// Mémorise la dernière instance vue pour détecter les bascules
window._lastInstanceId = null;
// Job courant (pour ignorer d’éventuelles réponses d’un ancien run)
let currentJobId = null;



const warmupCloseBtn     = document.getElementById('warmupCloseBtn');

// Helpers popup
function buildFinalSummary(s){
    const asked  = Array.isArray(s.asked) ? s.asked : [];
  const cacheL = Array.isArray(s.cache_repos) ? s.cache_repos : [];
  const dlL    = Array.isArray(s.downloaded_repos) ? s.downloaded_repos : [];
  const failL  = Array.isArray(s.failed_repos) ? s.failed_repos : [];

  const lines = [];
  lines.push(`Terminé — demandés: ${asked.length} • ⬛ cache: ${cacheL.length} • ✅ téléchargés: ${dlL.length} • ❌ échecs: ${failL.length}`);
  lines.push("");

  lines.push("Demandés : " + asked.length);
  if (asked.length) lines.push(asked.map(m=>' • '+m).join('\n'));

  lines.push("");
  lines.push(`⬛ Ignorés (déjà en cache) : ${cacheL.length}`);
  if (cacheL.length) lines.push(cacheL.map(m=>' • '+m).join('\n'));

  lines.push("");
  lines.push(`✅ Téléchargés : ${dlL.length}`);
  if (dlL.length) lines.push(dlL.map(m=>' • '+m).join('\n'));

  lines.push("");
  lines.push(`❌ Échecs : ${failL.length}`);
  if (failL.length) lines.push(failL.map(m=>' • '+m).join('\n'));

  return lines.join('\n');
}

// >>> C2_BEGIN warmup_preface
let warmupPreface = '';
// >>> C2_END warmup_preface

// >>> A2B2P3_BEGIN warmup_defaults
// Modèles par défaut si l’utilisateur laisse la saisie vide.
// (Liste “safe” validée chez toi ; on pourra l’étendre plus tard.)
const DEFAULT_MODELS = [
  "runwayml/stable-diffusion-v1-5",
  "facebook/sam-vit-base",
  "stabilityai/sd-vae-ft-mse"
];
// >>> A2B2P3_END warmup_defaults

function openWarmupPopup(){ if(warmupPopup) warmupPopup.style.display = 'block'; }

function closeWarmupPopup(){ if(warmupPopup) warmupPopup.style.display = 'none'; } 
let userClosedWarmupPopup = false;

if (warmupCloseBtn) warmupCloseBtn.addEventListener('click', closeWarmupPopup);
// -- DRAG & COPY (popups warmup) --
(function(){
  const $popup = document.getElementById('warmupPopup');
  const $sel   = document.getElementById('warmupSelectPopup');
  const $copy  = document.getElementById('warmupCopyBtn');
  const $copy2 = document.getElementById('selectCopyBtn');

  function makeDraggable(box){
    if (!box) return;
    let sx=0, sy=0, ox=0, oy=0, drag=false;
    box.addEventListener('mousedown', e=>{
      if (e.target.tagName === 'BUTTON' || e.target.closest('button')) return;
      drag=true; box.style.transform='none';
      ox = box.offsetLeft; oy = box.offsetTop; sx = e.clientX; sy = e.clientY;
      document.body.style.userSelect='none';
    });
    window.addEventListener('mousemove', e=>{
      if(!drag) return;
      box.style.left = (ox + (e.clientX - sx)) + 'px';
      box.style.top  = (oy + (e.clientY - sy)) + 'px';
    });
    window.addEventListener('mouseup', ()=>{ drag=false; document.body.style.userSelect=''; });
  }
  makeDraggable($popup);
  makeDraggable($sel);

  function copyText(txt){
    if (navigator.clipboard && navigator.clipboard.writeText){
      navigator.clipboard.writeText(txt||'').then(()=> (window.showToast?showToast('Copié ✅'):alert('Copié ✅')) );
    } else {
      const ta=document.createElement('textarea'); ta.value=txt||''; document.body.appendChild(ta); ta.select();
      try{ document.execCommand('copy'); (window.showToast?showToast('Copié ✅'):alert('Copié ✅')); }catch{}
      ta.remove();
    }
  }
  if ($copy){
    $copy.addEventListener('click', ()=>{
      const s = document.getElementById('warmupPopupStatus');
      const l = document.getElementById('warmup-logs');
      copyText((s?('[Status] '+s.textContent+'\n\n'):'') + (l?l.textContent:''));
    });
  }
  if ($copy2){
    $copy2.addEventListener('click', ()=>{
      const list = document.getElementById('repoList');
      copyText(list ? list.innerText : '');
    });
  }
})();

// Rafraîchissement d’état
let warmupTimer = null;
async function refreshWarmupUI(){
  try{
      const r = await fetch('/warmup/status');
    if(!r.ok) return;
    const s = await r.json();

    // Instance courante (multi-répliques)
    const instanceId = s.instance_id || 'n/a';
    if (window._lastInstanceId && window._lastInstanceId !== instanceId) {
      showToast(`Bascule d'instance détectée : ${window._lastInstanceId} → ${instanceId}`);
    }
    window._lastInstanceId = instanceId;

    const pct = Math.max(0, Math.min(100, parseInt(s.percent || 0, 10)));
    const running = !!s.running;

    if (warmupStopBtn) warmupStopBtn.style.display = running ? 'inline-block' : 'none';

    if (warmupStatusEl) {
      const tot = (s.total ?? 0);
      if (running) {
        const idx = (s.idx ?? 0) + 1;
        warmupStatusEl.textContent = `⏳ ${pct}% — ${s.current||''} (${idx}/${tot}) [inst:${instanceId}]`;
      } else if (s.done) {
        const cacheN = Array.isArray(s.cache_repos) ? s.cache_repos.length : 0;
        const dlN    = Array.isArray(s.downloaded_repos) ? s.downloaded_repos.length : 0;
        const failN  = Array.isArray(s.failed_repos) ? s.failed_repos.length : Math.max(0, tot - (s.ok_count||0));
        warmupStatusEl.textContent = `✅ Terminé — ⬛ ${cacheN} • ✅ ${dlN} • ❌ ${failN} / ${tot} [inst:${instanceId}]`;
        if (warmupPopupStatus) warmupPopupStatus.textContent = 'Terminé';
        if (warmupLogs) warmupLogs.textContent = buildFinalSummary(s);
      } else {
        const nCache = Number.isFinite(s.audit_count)
          ? s.audit_count
          : (Array.isArray(s.audit_cached) ? s.audit_cached.length : 0);
        warmupStatusEl.textContent = nCache > 0
          ? `✅ Prêt — cache local: ${nCache} [inst:${instanceId}]`
          : `Prêt (aucun run)`;
      }
    }

    if (warmupProgressFill) warmupProgressFill.style.width = pct + '%';
    if (warmupPopupStatus)  warmupPopupStatus.textContent = running ? 'Téléchargement en cours…' : 'Terminé';

    // Logs live dans la popup pendant l’exécution
    if (running && warmupLogs) {
      const logsTxt = Array.isArray(s.logs) ? s.logs.join('\n') : '';
      const asked = Array.isArray(s.asked)
        ? s.asked
        : (Array.isArray(window.lastRequestedModels) ? window.lastRequestedModels : []);
      const preface = (warmupPreface && warmupPreface.trim())
        ? warmupPreface
        : ('Demandés (' + asked.length + '):\n' + asked.map(m=>' • '+m).join('\n'));
      warmupLogs.textContent = preface + '\n\n' + (logsTxt || '— en cours…');
      warmupLogs.scrollTop = warmupLogs.scrollHeight;
    }

    // Gestion du polling + ouverture/fermeture popup
    if (running) {
      if (!userClosedWarmupPopup) openWarmupPopup();
      if (!warmupTimer) warmupTimer = setInterval(refreshWarmupUI, 1000);
    } else {
      if (warmupTimer) { clearInterval(warmupTimer); warmupTimer = null; }
      userClosedWarmupPopup = false;
    }

  }catch(e){ /* no-op */ }
}

// Boutons
if (warmupStartBtn){
  warmupStartBtn.addEventListener('click', async ()=>{




    // Saisie optionnelle — accepte virgules, espaces, retours à la ligne, points-virgules
    const txt = prompt(
      'Modèles (optionnel). Tu peux séparer par virgule, espace ou retour à la ligne.\n' +
      'Laisse vide pour utiliser la liste par défaut.',
      ''
    );

    let models;
    if (txt && txt.trim()){
      // Découpe souple + nettoyage + dédoublonnage
      const mods = txt.split(/[\s,;]+/).map(s=>s.trim()).filter(Boolean);
      if (!mods.length){ alert('Aucun modèle détecté.'); return; }
      models = Array.from(new Set(mods));
    } else {
      // Liste par défaut définie plus haut (P4.1)
      models = DEFAULT_MODELS;
    }

    // Mémorise la demande en cours pour l’affichage des logs
    window.lastRequestedModels = models;


    // Préface (audit du cache serveur, pour afficher le cumul)
    try {
      const ra = await fetch('/warmup/audit');
      const audit = ra.ok ? await ra.json() : null;
      const cached = (audit && Array.isArray(audit.cached)) ? audit.cached : [];
      warmupPreface =
        'Déjà en cache (' + cached.length + '):\n' +
        cached.map(m => ' • ' + m).join('\n') + '\n\n' +
        'Demandé dans cette exécution (' + models.length + '):\n' +
        models.map(m => ' • ' + m).join('\n');
    } catch(e) {
      warmupPreface = '';
    }
    // Ouvre la popup et affiche immédiatement la liste demandée
    // >>> PRÉAMBULE EXPLICITE (ajout) <<<
    try {
      const ra2 = await fetch('/warmup/audit');
      const audit2 = ra2.ok ? await ra2.json() : null;
      const cached2 = (audit2 && Array.isArray(audit2.cached)) ? audit2.cached : [];
      const ignored = models.filter(m => cached2.includes(m));
      warmupPreface =
        'Demandés (' + models.length + '):\n' +
        models.map(m => ' • ' + m).join('\n') + '\n\n' +
        '⬛ Ignorés (déjà en cache) (' + ignored.length + '):\n' +
        ignored.map(m => ' • ' + m).join('\n') + '\n\n' +
        '📦 Déjà en cache global (' + cached2.length + '):\n' +
        cached2.map(m => ' • ' + m).join('\n');
    } catch(_) { /* no-op */ }
    // >>> FIN AJOUT <<<

    userClosedWarmupPopup = false;
    openWarmupPopup();
    if (warmupPopupStatus) warmupPopupStatus.textContent = 'Téléchargement en cours…';

        if (warmupLogs) {
      warmupLogs.textContent = (warmupPreface ? warmupPreface + '\n' : '') + '— démarrage…';
      warmupLogs.scrollTop = warmupLogs.scrollHeight; // auto-scroll vers le bas
    }


    // Sécurité : évite 2 timers concurrents
    if (warmupTimer) { clearInterval(warmupTimer); warmupTimer = null; }

    try{
            const r = await fetch('/warmup/start', {
        method:'POST',
        headers:{ 'Content-Type':'application/json' },
        body: JSON.stringify({ models })
      });
      if(!r.ok){
        const t = await r.text();
        alert('Échec démarrage: ' + r.status + ' ' + t);
        return;
      }

      // Lecture unique du payload (évite les doublons)
      const payload = await r.json().catch(()=>null);
      if (payload && payload.already_running) {
        showToast("Un warm-up est déjà en cours — j'affiche l'état.");
      }
      // Mémoriser un éventuel job_id renvoyé
      if (payload && (payload.job_id || payload.job)) {
        currentJobId = payload.job_id || payload.job;
      }

      // Rafraîchir l’UI + lancer le polling local
      await refreshWarmupUI();
      if (!warmupTimer) warmupTimer = setInterval(refreshWarmupUI, 1000);
    }catch(e){
      alert('Erreur réseau');
    }

  });
}

if (warmupLogsBtn){
  warmupLogsBtn.addEventListener('click', async ()=>{

    // Recalcule une préface à la volée (hors exécution)
    try{
      const ra = await fetch('/warmup/audit');
      const audit = ra.ok ? await ra.json() : null;
      const cached = (audit && Array.isArray(audit.cached)) ? audit.cached : [];
      if (!warmupPreface) {
        warmupPreface =
          'Déjà en cache (' + cached.length + '):\n' +
          cached.map(m => ' • ' + m).join('\n');
      }
    }catch(e){}


    openWarmupPopup();
    await refreshWarmupUI();
    if (!warmupTimer) warmupTimer = setInterval(refreshWarmupUI, 1000);
  });
}
if (warmupStopBtn){
  warmupStopBtn.addEventListener('click', async ()=>{
    try{ await fetch('/warmup/stop',{method:'POST'}); await refreshWarmupUI(); }catch(e){}
  });
}

// 1er affichage (badge de statut en topbar)
refreshWarmupUI();
// >>> A2B2_END warmup_dom

const warmupSelectBtn = document.getElementById('warmupSelectBtn');
const warmupSelectPopup = document.getElementById('warmupSelectPopup');
const repoListEl = document.getElementById('repoList');
const selectCancelBtn = document.getElementById('selectCancelBtn');
const selectAllBtn = document.getElementById('selectAllBtn');
const selectNoneBtn = document.getElementById('selectNoneBtn');
const launchSelectedBtn = document.getElementById('launchSelectedBtn');

function openSelect(){ if(warmupSelectPopup) warmupSelectPopup.style.display='block'; }
function closeSelect(){ if(warmupSelectPopup) warmupSelectPopup.style.display='none'; }

async function loadCatalog(){
  if(!repoListEl) return;
  repoListEl.innerHTML = '<div class="muted">Chargement…</div>';
  try{
    const r = await fetch('/warmup/catalog');
    if(!r.ok){ repoListEl.innerHTML = '<div class="muted">Erreur de chargement.</div>'; return; }
    const d = await r.json();
    const items = Array.isArray(d.models) ? d.models : [];
    if(!items.length){ repoListEl.innerHTML = '<div class="muted">Aucun modèle proposé.</div>'; return; }
    repoListEl.innerHTML = '';
    items.forEach(id=>{
      const row = document.createElement('div'); row.className='repo-item';
      const cb  = document.createElement('input'); cb.type='checkbox'; cb.value=id;
      const label = document.createElement('span'); label.className='repo-id'; label.textContent = id;
      row.appendChild(cb); row.appendChild(label);
      repoListEl.appendChild(row);
    });
  }catch(e){
    repoListEl.innerHTML = '<div class="muted">Erreur réseau.</div>';
  }
}

if (warmupSelectBtn){
  warmupSelectBtn.addEventListener('click', async ()=>{
    await loadCatalog();
    openSelect();
  });
}
if (selectCancelBtn){ selectCancelBtn.addEventListener('click', closeSelect); }
if (selectAllBtn){
  selectAllBtn.addEventListener('click', ()=>{
    repoListEl.querySelectorAll('input[type="checkbox"]').forEach(cb=> cb.checked=true);
  });
}
if (selectNoneBtn){
  selectNoneBtn.addEventListener('click', ()=>{
    repoListEl.querySelectorAll('input[type="checkbox"]').forEach(cb=> cb.checked=false);
  });
}
if (launchSelectedBtn){
  launchSelectedBtn.addEventListener('click', async ()=>{
    const picks = Array.from(repoListEl.querySelectorAll('input[type="checkbox"]'))
      .filter(cb=>cb.checked).map(cb=>cb.value);
          // Réinitialiser l’état d’affichage pour ce nouveau run
    warmupPreface = '';
    window.lastRequestedModels = picks.slice();

    // Construire immédiatement une préface exacte (Demandés + Ignorés + Cache global)
    try {
      const ra = await fetch('/warmup/audit');
      const audit = ra.ok ? await ra.json() : null;
      const cached = (audit && Array.isArray(audit.cached)) ? audit.cached : [];
      const ignored = picks.filter(m => cached.includes(m));
      warmupPreface =
        'Demandés (' + picks.length + '):\n' +
        picks.map(m => ' • ' + m).join('\n') + '\n\n' +
        '⬛ Ignorés (déjà en cache) (' + ignored.length + '):\n' +
        (ignored.length ? ignored.map(m => ' • ' + m).join('\n') : '') + '\n\n' +
        '📦 Déjà en cache global (' + cached.length + '):\n' +
        (cached.length ? cached.map(m => ' • ' + m).join('\n') : '');
    } catch(_) { /* no-op */ }

    if(!picks.length){ alert('Sélectionne au moins un modèle.'); return; }
    window.lastRequestedModels = picks.slice();
        userClosedWarmupPopup = false;
    if (typeof openWarmupPopup === 'function') openWarmupPopup();
    if (typeof refreshWarmupUI === 'function') await refreshWarmupUI();
    try{
      const r = await fetch('/warmup/start', {
        method:'POST',
        headers:{ 'Content-Type':'application/json' },
        body: JSON.stringify({ models: picks })
      });
      if(!r.ok){
        const t = await r.text();
        alert('Échec démarrage: ' + r.status + ' ' + t);
        return;
      }
      if (typeof refreshWarmupUI === 'function') {
      
        const id = setInterval(async ()=>{
          await refreshWarmupUI();
          try{
            const s = await (await fetch('/warmup/status')).json();
            if (!s.running) clearInterval(id);
          }catch(e){ clearInterval(id); }
        }, 1000);
      }
      closeSelect();
    }catch(e){
      alert('Erreur réseau.');
    }
  });
}



const gotoBtn = document.getElementById('gotoBtn');

// State
let vidName = serverVid || '';
function fileStem(name){ const i = name.lastIndexOf('.'); return i>0 ? name.slice(0,i) : name; }
let vidStem = '';
let bustToken = Date.now();
let fps = 30, frames = 0;
let metaPromise = null; // évite les doubles requêtes /meta
let currentIdx = 0;
let mode = 'view';

// ==== Multi-rects ====
let currentDraw = null;          // rect en cours de tracé
let rectsMap = new Map();        // frame_idx -> Array<rect>
let color = '#10b981';

// autres états inchangés
let masks = [];
let maskedSet = new Set();
let timelineUrls = [];
let portionStart = null;
let portionEnd = null;
let loopInterval = null;
let chunkSize = 50;
let timelineStart = 0, timelineEnd = 0;
let viewRangeStart = 0, viewRangeEnd = 0;
const scrollThreshold = 100;
let followMode = false;
let isPaused = true;
let thumbEls = new Map();
let lastCenterMs = 0;
const CENTER_THROTTLE_MS = 150;
const PENDING_KEY = 've_pending_masks_v1';
let maskedOnlyMode = false;

// Utils
function showToast(msg){ const el = document.createElement('div'); el.className='toast-item'; el.textContent=String(msg||''); toastWrap.appendChild(el); setTimeout(()=>{ el.remove(); }, 2000); }
function ensureOverlays(){
  if(!document.getElementById('playhead')){ const ph=document.createElement('div'); ph.id='playhead'; ph.className='playhead'; tlBox.appendChild(ph); }
  if(!document.getElementById('portionBand')){ const pb=document.createElement('div'); pb.id='portionBand'; tlBox.appendChild(pb); }
  if(!document.getElementById('inHandle')){ const ih=document.createElement('div'); ih.id='inHandle'; tlBox.appendChild(ih); }
  if(!document.getElementById('outHandle')){ const oh=document.createElement('div'); oh.id='outHandle'; tlBox.appendChild(oh); }
}
function playheadEl(){ return document.getElementById('playhead'); }
function portionBand(){ return document.getElementById('portionBand'); }
function inHandle(){ return document.getElementById('inHandle'); }
function outHandle(){ return document.getElementById('outHandle'); }
function findThumbEl(idx){ return thumbEls.get(idx) || null; }
function updateHUD(){ const total = frames || 0, cur = currentIdx+1; hud.textContent = `t=${player.currentTime.toFixed(2)}s • #${cur}/${total} • ${fps.toFixed(2)}fps`; }
function updateSelectedThumb(){
  tlBox.querySelectorAll('.thumb img.sel, .thumb img.sel-strong').forEach(img=>{ img.classList.remove('sel','sel-strong'); });
  const el = findThumbEl(currentIdx); if(!el) return; const img = el.querySelector('img');
  img.classList.add('sel'); if(isPaused) img.classList.add('sel-strong');
}
function rawCenterThumb(el){
  tlBox.scrollLeft = Math.max(0, el.offsetLeft + el.clientWidth/2 - tlBox.clientWidth/2);
}
async function ensureThumbVisibleCentered(idx){
  for(let k=0; k<40; k++){
    const el = findThumbEl(idx);
    if(el){
      const img = el.querySelector('img');
      if(!img.complete || img.naturalWidth === 0){
        await new Promise(r=>setTimeout(r, 25));
      }else{
        rawCenterThumb(el);
        updatePlayhead();
        return true;
      }
    }else{
      await new Promise(r=>setTimeout(r, 25));
    }
  }
  return false;
}
function centerSelectedThumb(){ ensureThumbVisibleCentered(currentIdx); }
function updatePlayhead(){
  ensureOverlays();
  const el = findThumbEl(currentIdx);
  const ph = playheadEl();
  if(!el){ ph.style.display='none'; return; }
  ph.style.display='block'; ph.style.left = (el.offsetLeft + el.clientWidth/2) + 'px';
}
function updatePortionOverlays(){
  ensureOverlays();
  const pb = portionBand(), ih = inHandle(), oh = outHandle();
  if(portionStart==null || portionEnd==null){ pb.style.display='none'; ih.style.display='none'; oh.style.display='none'; return; }
  const a = findThumbEl(portionStart), b = findThumbEl(portionEnd-1);
  if(!a || !b){ pb.style.display='none'; ih.style.display='none'; oh.style.display='none'; return; }
  const left = a.offsetLeft, right = b.offsetLeft + b.clientWidth;
  pb.style.display='block'; pb.style.left = left+'px'; pb.style.width = Math.max(0, right-left)+'px';
  ih.style.display='block'; ih.style.left = (left - ih.clientWidth/2) + 'px';
  oh.style.display='block'; oh.style.left = (right - oh.clientWidth/2) + 'px';
}
function nearestFrameIdxFromClientX(clientX){
  const rect = tlBox.getBoundingClientRect();
  const xIn = clientX - rect.left + tlBox.scrollLeft;
  let bestIdx = currentIdx, bestDist = Infinity;
  for(const [idx, el] of thumbEls.entries()){
    const mid = el.offsetLeft + el.clientWidth/2;
    const d = Math.abs(mid - xIn);
    if(d < bestDist){ bestDist = d; bestIdx = idx; }
  }
  return bestIdx;
}
function loadPending(){ try{ return JSON.parse(localStorage.getItem(PENDING_KEY) || '[]'); }catch{ return []; } }
function savePendingList(lst){ localStorage.setItem(PENDING_KEY, JSON.stringify(lst)); }
function addPending(payload){ const lst = loadPending(); lst.push(payload); savePendingList(lst); }
async function flushPending(){
  const lst = loadPending(); if(!lst.length) return;
  const kept = [];
  for(const p of lst){
    try{ const r = await fetch('/mask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(p)}); if(!r.ok) kept.push(p); }
    catch{ kept.push(p); }
  }
  savePendingList(kept);
  if(kept.length===0) showToast('Masques hors-ligne synchronisés ✅');
}

// Layout
function syncTimelineWidth(){ const w = playerWrap.clientWidth; tlBox.style.width = w + 'px'; }
function fitCanvas(){
  const r=player.getBoundingClientRect();
  const ctrlH = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--controlsH'));
  canvas.width=Math.round(r.width);
  canvas.height=Math.round(r.height - ctrlH);
  canvas.style.width=r.width+'px';
  canvas.style.height=(r.height - ctrlH)+'px';
  syncTimelineWidth();
}
function timeToIdx(t){ return Math.max(0, Math.min(frames-1, Math.round((fps||30) * t))); }
function idxToSec(i){ return (fps||30)>0 ? (i / fps) : 0; }

// ==== Multi-rects helpers ====
function getRectsForFrame(fi){
  let arr = rectsMap.get(fi);
  if(!arr){ arr = []; rectsMap.set(fi, arr); }
  return arr;
}
function draw(){
  ctx.clearRect(0,0,canvas.width,canvas.height);
  const arr = getRectsForFrame(currentIdx);
  for(const r of arr){
    const x=Math.min(r.x1,r.x2), y=Math.min(r.y1,r.y2);
    const w=Math.abs(r.x2-r.x1), h=Math.abs(r.y2-r.y1);
    ctx.strokeStyle=r.color||color; ctx.lineWidth=2; ctx.strokeRect(x,y,w,h);
    ctx.fillStyle=(r.color||color)+'28'; ctx.fillRect(x,y,w,h);
  }
  if(currentDraw){
    const x=Math.min(currentDraw.x1,currentDraw.x2), y=Math.min(currentDraw.y1,currentDraw.y2);
    const w=Math.abs(currentDraw.x2-currentDraw.x1), h=Math.abs(currentDraw.y2-currentDraw.y1);
    ctx.setLineDash([6,4]);
    ctx.strokeStyle=currentDraw.color||color; ctx.lineWidth=2; ctx.strokeRect(x,y,w,h);
    ctx.setLineDash([]);
  }
}
function setMode(m){
  mode=m;
  if(m==='edit'){
    player.pause();
    player.controls = false;
    playerWrap.classList.add('edit-mode');
    modeLabel.textContent='Édition';
    btnEdit.style.display='none'; btnBack.style.display='inline-block';
    btnSave.style.display='inline-block'; btnClear.style.display='inline-block';
    canvas.style.pointerEvents='auto';
    draw();
  }else{
    player.controls = true;
    playerWrap.classList.remove('edit-mode');
    modeLabel.textContent='Lecture';
    btnEdit.style.display='inline-block'; btnBack.style.display='none';
    btnSave.style.display='none'; btnClear.style.display='none';
    canvas.style.pointerEvents='none';
    currentDraw=null; draw();
  }
}

// Dessin multi-rectangles
let dragging=false, sx=0, sy=0;
canvas.addEventListener('mousedown',(e)=>{
  if(mode!=='edit' || !vidName) return;
  dragging=true; const r=canvas.getBoundingClientRect();
  sx=e.clientX-r.left; sy=e.clientY-r.top;
  currentDraw={x1:sx,y1:sy,x2:sx,y2:sy,color:color}; draw();
});
canvas.addEventListener('mousemove',(e)=>{
  if(!dragging) return;
  const r=canvas.getBoundingClientRect();
  currentDraw.x2=e.clientX-r.left; currentDraw.y2=e.clientY-r.top; draw();
});
['mouseup','mouseleave'].forEach(ev=>canvas.addEventListener(ev,()=>{
  if(!dragging) return;
  dragging=false;
  if(currentDraw){
    const arr = getRectsForFrame(currentIdx);
    // ignorer les clics trop petits
    if(Math.abs(currentDraw.x2-currentDraw.x1) > 3 && Math.abs(currentDraw.y2-currentDraw.y1) > 3){
      arr.push({...currentDraw});
    }
    currentDraw=null; draw();
  }
}));

btnClear.onclick=()=>{ 
  const arr = getRectsForFrame(currentIdx);
  if(arr.length){ arr.pop(); draw(); } 
};
btnEdit.onclick =()=> setMode('edit');
btnBack.onclick =()=> setMode('view');

// Palette
palette.querySelectorAll('.swatch').forEach(el=>{
  if(el.dataset.c===color) el.classList.add('sel');
  el.onclick=()=>{
    palette.querySelectorAll('.swatch').forEach(s=>s.classList.remove('sel'));
    el.classList.add('sel'); color=el.dataset.c;
    if(currentDraw){ currentDraw.color=color; draw(); }
  };
});

// === Timeline (identique sauf interactions internes) ===
async function loadTimelineUrls(){
  timelineUrls = [];
  const stem = vidStem, b = bustToken;
  for(let idx=0; idx<frames; idx++){
    timelineUrls[idx] = `/thumbs/f_${stem}_${idx}.jpg?b=${b}`;
  }
  tlProgressFill.style.width='0%';
}
async function renderTimeline(centerIdx){
  if(!vidName) return;
  loadingInd.style.display='block';
  if(timelineUrls.length===0) await loadTimelineUrls();
  tlBox.innerHTML = ''; thumbEls = new Map(); ensureOverlays();

  if(maskedOnlyMode){
    const idxs = Array.from(maskedSet).sort((a,b)=>a-b);
    for(const i of idxs){ addThumb(i,'append'); }
    setTimeout(async ()=>{ syncTimelineWidth(); updateSelectedThumb(); await ensureThumbVisibleCentered(currentIdx); loadingInd.style.display='none'; updatePlayhead(); updatePortionOverlays(); },0);
    return;
  }

  if(portionStart!=null && portionEnd!=null){
    const s = Math.max(0, portionStart), e = Math.min(frames, portionEnd);
    for(let i=s;i<e;i++){ addThumb(i,'append'); }
    setTimeout(async ()=>{ syncTimelineWidth(); updateSelectedThumb(); await ensureThumbVisibleCentered(currentIdx); loadingInd.style.display='none'; updatePlayhead(); updatePortionOverlays(); },0);
    return;
  }

  await loadWindow(centerIdx ?? currentIdx);
  loadingInd.style.display='none';
}
async function loadWindow(centerIdx){
  tlBox.innerHTML=''; thumbEls = new Map(); ensureOverlays();
  const rngStart = (viewRangeStart ?? 0);
  const rngEnd = (viewRangeEnd ?? frames);
  const mid = Math.max(rngStart, Math.min(centerIdx, Math.max(rngStart, rngEnd-1)));
  const start = Math.max(rngStart, Math.min(mid - Math.floor(chunkSize/2), Math.max(rngStart, rngEnd - chunkSize)));
  const end = Math.min(rngEnd, start + chunkSize);
  for(let i=start;i<end;i++){ addThumb(i,'append'); }
  timelineStart = start; timelineEnd = end;
  setTimeout(async ()=>{
    syncTimelineWidth();
    updateSelectedThumb();
    await ensureThumbVisibleCentered(currentIdx);
    updatePortionOverlays();
  },0);
}
function addThumb(idx, place='append'){
  if(thumbEls.has(idx)) return;
  const wrap=document.createElement('div'); wrap.className='thumb'; wrap.dataset.idx=idx;
  if(maskedSet.has(idx)) wrap.classList.add('hasmask');
  const img=new Image(); img.title='frame '+(idx+1);
  img.src=timelineUrls[idx];
    // Fallback solide : on affiche /frame_idx tout de suite,
  // puis on ne bascule vers /thumbs que si elle existe (sonde en tâche de fond).
  img.addEventListener('error', ()=>{
    const fallback = `/frame_idx?vid=${encodeURIComponent(vidName)}&idx=${idx}`;
    img.onerror = null;              // éviter les boucles d'erreur
    img.src = fallback;              // montrer la frame générée à la volée

    const trySwap = () => {
      const nu = `/thumbs/f_${vidStem}_${idx}.jpg?b=${Date.now()}`;
      const probe = new Image();
      probe.onload  = () => { timelineUrls[idx] = nu; img.src = nu; };
      probe.onerror = () => { setTimeout(trySwap, 1500); }; // réessaie plus tard
      probe.src = nu;
    };
    setTimeout(trySwap, 1500);
  }, { once:true });
  if(idx===currentIdx){ img.classList.add('sel'); if(isPaused) img.classList.add('sel-strong'); }
  img.onclick=async ()=>{
    currentIdx=idx; player.currentTime=idxToSec(currentIdx);
    draw();
    updateSelectedThumb(); await ensureThumbVisibleCentered(currentIdx); updatePlayhead();
  };
  wrap.appendChild(img);
  const label=document.createElement('span'); label.className='thumb-label'; label.textContent = `#${idx+1}`;
  wrap.appendChild(label);
  if(place==='append'){ tlBox.appendChild(wrap); }
  else if(place==='prepend'){ tlBox.insertBefore(wrap, tlBox.firstChild); }
  else{ tlBox.appendChild(wrap); }
  thumbEls.set(idx, wrap);
}

tlBox.addEventListener('scroll', ()=>{
  if (maskedOnlyMode || (portionStart!=null && portionEnd!=null)){
    updatePlayhead(); updatePortionOverlays();
    return;
  }
  const scrollLeft = tlBox.scrollLeft, scrollWidth = tlBox.scrollWidth, clientWidth = tlBox.clientWidth;
  if (scrollWidth - scrollLeft - clientWidth < scrollThreshold && timelineEnd < viewRangeEnd){
    const newEnd = Math.min(viewRangeEnd, timelineEnd + chunkSize);
    for(let i=timelineEnd;i<newEnd;i++){ addThumb(i,'append'); }
    timelineEnd = newEnd;
  }
  if (scrollLeft < scrollThreshold && timelineStart > viewRangeStart){
    const newStart = Math.max(viewRangeStart, timelineStart - chunkSize);
    for(let i=newStart;i<timelineStart;i++){ addThumb(i,'prepend'); }
    tlBox.scrollLeft += (timelineStart - newStart) * (110 + 8);
    timelineStart = newStart;
  }
  updatePlayhead(); updatePortionOverlays();
});

// Isoler & Boucle (inchangé)
isolerBoucle.onclick = async ()=>{
  const start = parseInt(goFrame.value || '1',10) - 1;
  const end = parseInt(endPortion.value || '',10);
  if(!endPortion.value || end <= start || end > frames){ alert('Portion invalide (fin > début)'); return; }
  if (end - start > 1200 && !confirm('Portion très large, cela peut être lent. Continuer ?')) return;
  portionStart = start; portionEnd = end;
  viewRangeStart = start; viewRangeEnd = end;
  player.pause(); isPaused = true;
  currentIdx = start; player.currentTime = idxToSec(start);
  await renderTimeline(currentIdx);
  resetFull.style.display = 'inline-block';
  startLoop(); updatePortionOverlays();
};
function startLoop(){
  if(loopInterval) clearInterval(loopInterval);
  if(portionEnd != null){
    loopInterval = setInterval(()=>{ if(player.currentTime >= idxToSec(portionEnd)) player.currentTime = idxToSec(portionStart); }, 100);
  }
}
resetFull.onclick = async ()=>{
  portionStart = null; portionEnd = null;
  viewRangeStart = 0; viewRangeEnd = frames;
  goFrame.value = 1; endPortion.value = '';
  player.pause(); isPaused = true;
  await renderTimeline(currentIdx);
  resetFull.style.display='none';
  clearInterval(loopInterval); updatePortionOverlays();
};

// Drag IN/OUT (inchangé)
function attachHandleDrag(handle, which){
  let draggingH=false;
  function onMove(e){
    if(!draggingH) return;
    const idx = nearestFrameIdxFromClientX(e.clientX);
    if(which==='in'){ portionStart = Math.min(idx, portionEnd ?? idx+1); goFrame.value = (portionStart+1); }
    else { portionEnd = Math.max(idx+1, (portionStart ?? idx)); endPortion.value = portionEnd; }
    viewRangeStart = (portionStart ?? 0); viewRangeEnd = (portionEnd ?? frames);
    updatePortionOverlays();
  }
  handle.addEventListener('mousedown', (e)=>{ draggingH=true; e.preventDefault(); });
  window.addEventListener('mousemove', onMove);
  window.addEventListener('mouseup', ()=>{ draggingH=false; });
}
ensureOverlays(); attachHandleDrag(document.getElementById('inHandle'), 'in'); attachHandleDrag(document.getElementById('outHandle'), 'out');

// Progress popup (inchangé)
async function showProgress(vidStem){
  popup.style.display = 'block';
  const interval = setInterval(async () => {
    const r = await fetch('/progress/' + vidStem);
    const d = await r.json();
    tlProgressFill.style.width = d.percent + '%';
    popupProgressFill.style.width = d.percent + '%';
    popupLogs.innerHTML = d.logs.map(x=>String(x)).join('<br>');
    if(d.done){
      clearInterval(interval);
      popup.style.display = 'none';
      await renderTimeline(currentIdx);
    }
  }, 800);
}

// Meta & boot
async function loadVideoAndMeta() {
  if(!vidName){ statusEl.textContent='Aucune vidéo sélectionnée.'; return; }
  vidStem = fileStem(vidName); bustToken = Date.now();
  const bust = Date.now();
  srcEl.src = '/data/'+encodeURIComponent(vidName)+'?t='+bust;
  player.setAttribute('poster', '/poster/'+encodeURIComponent(vidName)+'?t='+bust);
  player.load();
  fitCanvas();
  statusEl.textContent = 'Chargement vidéo…';
try{
        metaPromise = fetch('/meta/'+encodeURIComponent(vidName));
    const r = await metaPromise;
    if(r.ok){
      const m=await r.json();
      fps=m.fps||30; frames=m.frames||0;
      statusEl.textContent = `OK (${frames} frames @ ${fps.toFixed(2)} fps)`;
      viewRangeStart = 0; viewRangeEnd = frames;
      await loadTimelineUrls();
      await loadMasks();
      currentIdx = 0; player.currentTime = 0;
      await renderTimeline(0);
      showProgress(vidStem);
    }else{
      statusEl.textContent = 'Erreur meta';
    }
  }catch(err){
    statusEl.textContent = 'Erreur réseau meta';
  }
}
player.addEventListener('loadedmetadata', async ()=>{
  fitCanvas();
  if(!frames || frames<=0){
    try{
      if (metaPromise) {
        const r = await metaPromise;
        if (r.ok) { const m = await r.json(); fps = m.fps||30; frames = m.frames||0; }
      }
    }catch{}
  }
  currentIdx=0; goFrame.value=1; draw();
});
window.addEventListener('resize', ()=>{ fitCanvas(); draw(); });
player.addEventListener('pause', ()=>{ isPaused = true; updateSelectedThumb(); centerSelectedThumb(); });
player.addEventListener('play', ()=>{ isPaused = false; updateSelectedThumb(); });
player.addEventListener('timeupdate', ()=>{
  posInfo.textContent='t='+player.currentTime.toFixed(2)+'s';
  currentIdx=timeToIdx(player.currentTime);
  if(mode==='edit'){ draw(); }
  updateHUD(); updateSelectedThumb(); updatePlayhead();
  if(followMode && !isPaused){
    const now = Date.now();
    if(now - lastCenterMs > CENTER_THROTTLE_MS){ lastCenterMs = now; centerSelectedThumb(); }
  }
});
goFrame.addEventListener('change', async ()=>{
  if(!vidName) return;
  const val=Math.max(1, parseInt(goFrame.value||'1',10));
  player.pause(); isPaused = true;
  currentIdx=val-1; player.currentTime=idxToSec(currentIdx);
  await renderTimeline(currentIdx);
  draw();
  await ensureThumbVisibleCentered(currentIdx);
});

// Follow / Filter / Zoom / Goto
btnFollow.onclick = ()=>{ followMode = !followMode; btnFollow.classList.toggle('toggled', followMode); if(followMode) centerSelectedThumb(); };
btnFilterMasked.onclick = async ()=>{
  maskedOnlyMode = !maskedOnlyMode;
  btnFilterMasked.classList.toggle('toggled', maskedOnlyMode);
  tlBox.classList.toggle('filter-masked', maskedOnlyMode);
  await renderTimeline(currentIdx);
  await ensureThumbVisibleCentered(currentIdx);
};
zoomSlider.addEventListener('input', ()=>{ tlBox.style.setProperty('--thumbH', zoomSlider.value + 'px'); });
async function gotoFrameNum(){
  const v = parseInt(gotoInput.value||'',10);
  if(!Number.isFinite(v) || v<1 || v>frames) return;
  player.pause(); isPaused = true;
  currentIdx = v-1; player.currentTime = idxToSec(currentIdx);
  goFrame.value = v;
  await renderTimeline(currentIdx);
  draw();
  await ensureThumbVisibleCentered(currentIdx);
}
gotoBtn.onclick = ()=>{ gotoFrameNum(); };
gotoInput.addEventListener('keydown',(e)=>{ if(e.key==='Enter'){ e.preventDefault(); gotoFrameNum(); } });

// Drag & drop upload
const uploadZone = document.getElementById('uploadForm');
uploadZone.addEventListener('dragover', (e) => { e.preventDefault(); uploadZone.style.borderColor = '#2563eb'; });
uploadZone.addEventListener('dragleave', () => { uploadZone.style.borderColor = 'transparent'; });
uploadZone.addEventListener('drop', (e) => {
  e.preventDefault(); uploadZone.style.borderColor = 'transparent';
  const file = e.dataTransfer.files[0];
  if(file && file.type.startsWith('video/')){
    const fd = new FormData(); fd.append('file', file);
    fetch('/upload?redirect=1', {method: 'POST', body: fd}).then(() => location.reload());
  }
});

// Export placeholder
document.getElementById('exportBtn').onclick = () => { console.log('Export en cours... (IA à venir)'); alert('Fonctionnalité export IA en développement !'); };

// Fichiers & masques (chargement existants => rectsMap)
async function loadFiles(){
  const r=await fetch('/files'); const d=await r.json();
  if(!d.items || !d.items.length){ fileList.innerHTML='<li>(aucune)</li>'; return; }
  fileList.innerHTML='';
  d.items.forEach(name=>{
    const li=document.createElement('li');
    const delBtn = document.createElement('span'); delBtn.className='delete-btn'; delBtn.textContent='❌'; delBtn.title='Supprimer cette vidéo';
    delBtn.onclick=async()=>{
      if(!confirm(`Supprimer "${name}" ?`)) return;
      await fetch('/delete/'+encodeURIComponent(name),{method:'DELETE'});
      loadFiles(); if(vidName===name){ vidName=''; loadVideoAndMeta(); }
    };
    const a=document.createElement('a'); a.textContent=name; a.href='/ui?v='+encodeURIComponent(name); a.title='Ouvrir cette vidéo';
    li.appendChild(delBtn); li.appendChild(a); fileList.appendChild(li);
  });
}
async function loadMasks(){
  loadingInd.style.display='block';
  const box=document.getElementById('maskList');
  const r=await fetch('/mask/'+encodeURIComponent(vidName));
  const d=await r.json();
  masks=d.masks||[];
  maskedSet = new Set(masks.map(m=>parseInt(m.frame_idx||0,10)));

  // Reconstituer rectsMap depuis les masques existants
  rectsMap.clear();
  const normW = canvas.clientWidth, normH = canvas.clientHeight;
  masks.forEach(m=>{
    if(m.shape==='rect'){
      const [x1,y1,x2,y2] = m.points; // normalisés
      const rx = {x1:x1*normW, y1:y1*normH, x2:x2*normW, y2:y2*normH, color:m.color||'#10b981'};
      const arr = getRectsForFrame(parseInt(m.frame_idx||0,10));
      arr.push(rx);
    }
  });

  maskedCount.textContent = `(${maskedSet.size} ⭐)`;
  if(!masks.length){ box.textContent='—'; loadingInd.style.display='none'; draw(); return; }
  box.innerHTML='';
  const ul=document.createElement('ul'); ul.className='clean';
  masks.forEach(m=>{
    const li=document.createElement('li');
    const fr=(parseInt(m.frame_idx||0,10)+1);
    const t=(m.time_s||0).toFixed(2);
    const col=m.color||'#10b981';
    const label=m.note||(`frame ${fr}`);
    li.innerHTML = `<span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${col};margin-right:6px;vertical-align:middle"></span> <strong>${label.replace(/</g,'&lt;').replace(/>/g,'&gt;')}</strong> — #${fr} · t=${t}s`;
    const renameBtn=document.createElement('span'); renameBtn.className='rename-btn'; renameBtn.textContent='✏️'; renameBtn.title='Renommer le masque';
    renameBtn.onclick=async()=>{
      const nv=prompt('Nouveau nom du masque :', label);
      if(nv===null) return;
      const rr=await fetch('/mask/rename',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({vid:vidName,id:m.id,note:nv})});
      if(rr.ok){ await loadMasks(); await renderTimeline(currentIdx); draw(); showToast('Masque renommé ✅'); } else {
        const txt = await rr.text(); alert('Échec renommage: ' + rr.status + ' ' + txt);
      }
    };
    const delMaskBtn=document.createElement('span'); delMaskBtn.className='delete-btn'; delMaskBtn.textContent='❌'; delMaskBtn.title='Supprimer ce masque';
    delMaskBtn.onclick=async()=>{
      if(!confirm(`Supprimer masque "${label}" ?`)) return;
      const rr=await fetch('/mask/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({vid:vidName,id:m.id})});
      if(rr.ok){ await loadMasks(); await renderTimeline(currentIdx); draw(); showToast('Masque supprimé ✅'); } else {
        const txt = await rr.text(); alert('Échec suppression: ' + rr.status + ' ' + txt);
      }
    };
    li.appendChild(renameBtn); li.appendChild(delMaskBtn); ul.appendChild(li);
  });
  box.appendChild(ul);
  loadingInd.style.display='none';
  draw();
}

// Save masks (tous les rectangles de la frame courante)
btnSave.onclick = async ()=>{
  const arr = getRectsForFrame(currentIdx);
  if(currentDraw){
    // finaliser le tracé en cours
    if(Math.abs(currentDraw.x2-currentDraw.x1) > 3 && Math.abs(currentDraw.y2-currentDraw.y1) > 3){
      arr.push({...currentDraw});
    }
    currentDraw=null;
  }
  if(!arr.length){ alert('Aucun rectangle sur cette frame.'); return; }
  const defaultName = `frame ${currentIdx+1}`;
  const baseNote = (prompt('Nom de base (optionnel) :', defaultName) || defaultName).trim();
  const normW = canvas.clientWidth, normH = canvas.clientHeight;

  // Sauvegarder séquentiellement pour éviter les erreurs réseau cumulées
  for(let i=0;i<arr.length;i++){
    const r = arr[i];
    const x=Math.min(r.x1,r.x2)/normW;
    const y=Math.min(r.y1,r.y2)/normH;
    const w=Math.abs(r.x2-r.x1)/normW;
    const h=Math.abs(r.y2-r.y1)/normH;
    const payload={vid:vidName,time_s:player.currentTime,frame_idx:currentIdx,shape:'rect',points:[x,y,x+w,y+h],color:r.color||color,note:`${baseNote} #${i+1}`};
    addPending(payload);
    try{
      const res = await fetch('/mask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
      if(!res.ok){
        const txt = await res.text();
        alert('Échec enregistrement masque: ' + res.status + ' ' + txt);
        break;
      }
    }catch(e){
      alert('Erreur réseau lors de l’enregistrement.');
      break;
    }
  }
  // Nettoyage des pendings naïf (optionnel)
  savePendingList([]); 
  await loadMasks(); await renderTimeline(currentIdx);
  showToast('Masques enregistrés ✅');
};

// Boot
async function boot(){
  const lst = JSON.parse(localStorage.getItem('ve_pending_masks_v1') || '[]'); if(lst.length){ /* flush pending si besoin */ }
  await loadFiles();
  if(serverVid){ vidName=serverVid; await loadVideoAndMeta(); }
  else{ const qs=new URLSearchParams(location.search); const v=qs.get('v')||''; if(v){ vidName=v; await loadVideoAndMeta(); } }
}
boot();

// Masquer les contrôles natifs en mode édition
const style = document.createElement('style');
style.textContent = `.player-wrap.edit-mode video::-webkit-media-controls { display: none !important; } .player-wrap.edit-mode video::before { content: none !important; }`;
document.head.appendChild(style);
</script>
</html>
"""

@app.get("/ui", response_class=HTMLResponse, tags=["meta"])
def ui(v: Optional[str] = "", msg: Optional[str] = ""):
    vid = v or ""
    try:
                safe_msg: str = urllib.parse.unquote(msg or "")
    except Exception:
        safe_msg = ""
    html = HTML_TEMPLATE.replace("__VID__", urllib.parse.quote(vid)).replace("__MSG__", safe_msg)
    return HTMLResponse(content=html)