File size: 59,302 Bytes
e02cbea
 
 
 
 
 
 
68e5297
be0fd54
c9c1811
68e5297
8ce84cd
68e5297
 
 
 
8ce84cd
 
e02cbea
 
 
 
abf19cd
 
68e5297
e02cbea
68e5297
be0fd54
 
 
e02cbea
be0fd54
 
 
 
 
 
 
 
 
 
 
 
e02cbea
abf19cd
68e5297
e02cbea
 
 
 
68e5297
 
 
 
be0fd54
e02cbea
68e5297
 
e02cbea
 
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
 
 
 
 
 
68e5297
be0fd54
e02cbea
68e5297
be0fd54
e02cbea
68e5297
be0fd54
e02cbea
68e5297
be0fd54
e02cbea
68e5297
be0fd54
 
 
 
 
 
 
 
cb113a6
be0fd54
 
e02cbea
be0fd54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb113a6
be0fd54
 
 
 
 
 
 
 
 
 
cb113a6
 
be0fd54
 
 
 
 
 
 
 
 
 
e02cbea
be0fd54
 
 
 
68e5297
be0fd54
 
 
 
 
 
68e5297
be0fd54
 
e02cbea
be0fd54
 
e02cbea
be0fd54
 
 
 
 
 
 
 
e02cbea
cb113a6
be0fd54
e02cbea
 
 
cb113a6
be0fd54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68e5297
e02cbea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd84955
e02cbea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c2ad4f
68e5297
e02cbea
 
 
 
 
 
68e5297
be0fd54
e02cbea
 
cb113a6
be0fd54
e02cbea
 
68e5297
be0fd54
 
e02cbea
 
68e5297
be0fd54
 
 
 
 
 
 
e02cbea
 
68e5297
be0fd54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
 
68e5297
be0fd54
e02cbea
 
68e5297
be0fd54
 
 
 
 
 
 
 
 
 
e02cbea
 
68e5297
be0fd54
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
 
68e5297
be0fd54
 
 
 
 
 
 
e02cbea
 
68e5297
be0fd54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abf19cd
 
 
 
e02cbea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abf19cd
 
 
fd84955
e02cbea
 
 
fd84955
 
 
abf19cd
e02cbea
 
 
 
 
 
 
 
abf19cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
abf19cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd84955
 
abf19cd
 
 
 
 
 
 
 
 
 
 
 
 
fd84955
abf19cd
fd84955
abf19cd
 
 
 
cb113a6
abf19cd
12d4264
abf19cd
 
 
 
 
 
 
 
 
 
 
e02cbea
abf19cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
 
 
 
 
 
 
abf19cd
 
 
 
 
 
 
e02cbea
abf19cd
e02cbea
abf19cd
 
 
 
e02cbea
abf19cd
 
fd84955
8ce84cd
abf19cd
 
 
 
 
 
fd84955
abf19cd
e02cbea
 
abf19cd
fd84955
 
 
 
 
 
 
 
 
 
d1b23dc
fd84955
 
 
 
 
 
 
e02cbea
 
 
 
 
 
fd84955
 
e02cbea
fd84955
 
 
 
e02cbea
fd84955
 
e02cbea
fd84955
 
 
 
e02cbea
fd84955
 
 
 
abf19cd
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abf19cd
fd84955
 
 
 
 
 
 
 
 
abf19cd
 
fd84955
 
 
 
 
 
 
 
 
 
e02cbea
fd84955
 
 
 
 
 
 
e02cbea
fd84955
 
 
 
e02cbea
 
 
 
 
 
fd84955
 
 
 
 
e02cbea
fd84955
 
 
 
e02cbea
fd84955
e02cbea
 
abf19cd
 
e02cbea
fd84955
 
 
 
 
e02cbea
fd84955
 
e02cbea
fd84955
 
 
 
e02cbea
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
fd84955
 
 
e02cbea
fd84955
 
 
 
 
 
 
 
e02cbea
fd84955
 
 
 
 
 
 
 
 
 
e02cbea
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
fd84955
e02cbea
 
 
 
 
 
 
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
 
fd84955
 
 
 
 
 
 
e02cbea
fd84955
 
 
 
 
 
 
e02cbea
fd84955
 
 
 
e02cbea
 
fd84955
 
 
 
e02cbea
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
fd84955
e02cbea
fd84955
abf19cd
 
 
fd84955
 
 
e02cbea
fd84955
 
 
 
 
 
e02cbea
fd84955
 
 
 
 
e02cbea
fd84955
 
 
e02cbea
abf19cd
fd84955
 
 
 
 
 
 
abf19cd
fd84955
 
 
 
 
 
 
 
 
abf19cd
 
e02cbea
abf19cd
 
 
fd84955
 
 
 
 
 
 
 
e02cbea
 
 
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
fd84955
 
e02cbea
fd84955
e02cbea
fd84955
 
 
 
e02cbea
fd84955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02cbea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd84955
 
e02cbea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd84955
e02cbea
fd84955
e02cbea
fd84955
 
 
 
abf19cd
e02cbea
abf19cd
 
 
 
 
 
e02cbea
 
68e5297
fd84955
 
 
 
 
 
e02cbea
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
# app.py — Video Editor API (v0.8.2)
# Fixes:
#  - Portion rendering shows full selected range (e.g., 1→55, 70→480, 8→88)
#  - Accurate centering for "Aller à #" (no offset drift)
#  - Robust Warm-up (Hub) with safe imports + error surfacing (no silent crash)
# Base: compatible with previous v0.5.9 routes and UI

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, List
import uuid, shutil, cv2, json, time, urllib.parse, sys
import threading
import subprocess
import shutil as _shutil
import os
import httpx

print("[BOOT] Video Editor API starting…")

# --- POINTEUR DE BACKEND -----------------------------------------------------
POINTER_URL = os.getenv("BACKEND_POINTER_URL", "").strip()
FALLBACK_BASE = os.getenv("BACKEND_BASE_URL", "http://127.0.0.1:8765").strip()
_backend_url_cache = {"url": None, "ts": 0.0}

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

print(f"[BOOT] POINTER_URL={POINTER_URL or '(unset)'}")
print(f"[BOOT] FALLBACK_BASE={FALLBACK_BASE}")

app = FastAPI(title="Video Editor API", version="0.8.2")

# --- DATA DIRS ----------------------------------------------------------------
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 ----------------------------------------------------
@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)

# --- THUMBS PROGRESS (vid_stem -> state) -------------------------------------
progress_data: Dict[str, Dict[str, Any]] = {}

# --- 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")

# --- THUMBS GENERATION BG -----------------------------------------------------

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

# --- WARM-UP (Hub) ------------------------------------------------------------
from huggingface_hub import snapshot_download
try:
    from huggingface_hub.utils import HfHubHTTPError  # 0.13+
except Exception:
    class HfHubHTTPError(Exception):
        pass

warmup_state: Dict[str, Any] = {
    "state": "idle",  # idle|running|done|error
    "running": False,
    "percent": 0,
    "current": "",
    "idx": 0,
    "total": 0,
    "log": [],
    "started_at": None,
    "finished_at": None,
    "last_error": "",
}

WARMUP_MODELS: List[str] = [
    "facebook/sam2-hiera-large",
    "lixiaowen/diffuEraser",
    "runwayml/stable-diffusion-v1-5",
    "stabilityai/sd-vae-ft-mse",
    "ByteDance/Sa2VA-4B",
    "wangfuyun/PCM_Weights",
]

def _append_warmup_log(msg: str):
    warmup_state["log"].append(msg)
    if len(warmup_state["log"]) > 200:
        warmup_state["log"] = warmup_state["log"][-200:]

def _do_warmup():
    token = os.getenv("HF_TOKEN", None)
    warmup_state.update({
        "state": "running", "running": True, "percent": 0,
        "idx": 0, "total": len(WARMUP_MODELS), "current": "",
        "started_at": time.time(), "finished_at": None, "last_error": "",
        "log": []
    })
    try:
        total = len(WARMUP_MODELS)
        for i, repo in enumerate(WARMUP_MODELS):
            warmup_state["current"] = repo
            warmup_state["idx"] = i
            base_pct = int((i / max(1, total)) * 100)
            warmup_state["percent"] = min(99, base_pct)
            _append_warmup_log(f"➡️ Téléchargement: {repo}")
            try:
                snapshot_download(repo_id=repo, token=token)
                _append_warmup_log(f"✅ OK: {repo}")
            except HfHubHTTPError as he:
                _append_warmup_log(f"⚠️ HubHTTPError {repo}: {he}")
            except Exception as e:
                _append_warmup_log(f"⚠️ Erreur {repo}: {e}")
            # après chaque repo
            warmup_state["percent"] = int(((i+1) / max(1, total)) * 100)
        warmup_state.update({"state":"done","running":False,"finished_at":time.time(),"current":"","idx":total})
    except Exception as e:
        warmup_state.update({"state":"error","running":False,"last_error":str(e),"finished_at":time.time()})
        _append_warmup_log(f"❌ Warm-up erreur: {e}")

@app.post("/warmup/start", tags=["warmup"])
def warmup_start():
    if warmup_state.get("running"):
        return {"ok": False, "detail": "already running", "state": warmup_state}
    t = threading.Thread(target=_do_warmup, daemon=True)
    t.start()
    return {"ok": True, "state": warmup_state}

@app.get("/warmup/status", tags=["warmup"])
def warmup_status():
    return warmup_state

# --- API ROUTES ---------------------------------------------------------------
@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"]
    }

@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):
    ext = (Path(file.filename).suffix or ".mp4").lower()
    if ext not in {".mp4", ".mov", ".mkv", ".webm"}:
        raise HTTPException(400, "Formats acceptés : mp4/mov/mkv/webm")
    base = _safe_name(file.filename)
    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")

@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 = m["frames"]
    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}

# ----- 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 ----------------------------------------------------------------------
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}
 .playhead{position:absolute;top:0;bottom:0;width:2px;background:var(--active-border);opacity:.9;pointer-events:none;display:block}
 #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}
 #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}
 /* Warmup UI */
 #warmupBox{display:flex;align-items:center;gap:8px}
 #warmup-progress{flex:1;height:8px;background:#eef2f7;border-radius:4px;overflow:hidden}
 #warmup-progress > div{height:100%;width:0;background:#10b981;border-radius:4px}
 #warmup-status{font-size:12px;color:#334155;min-width:140px}
 .err{color:#b91c1c}
</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>
</div>
<div class="card" style="margin-bottom:10px">
 <div id="warmupBox">
  <button id="warmupBtn" class="btn">⚡ Warm‑up modèles (Hub)</button>
  <div id="warmup-status">—</div>
  <div id="warmup-progress"><div id="warmup-fill"></div></div>
 </div>
 <div class="muted" id="warmup-log" style="margin-top:6px;max-height:90px;overflow:auto"></div>
</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 class="muted" style="margin-left:10px">Astuce: fin = exclusive ("55" inclut #55)</span>
    <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 le masque sélectionné">💾 Enregistrer masque</button>
   <button id="btnClear" class="btn" style="display:none" title="Effacer la sélection actuelle">🧽 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>
<div id="toast"></div>
<script>
const serverVid = "__VID__";
const serverMsg = "__MSG__";
document.getElementById('msg').textContent = serverMsg;
// Elements
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');
const gotoBtn = document.getElementById('gotoBtn');
// Warmup UI
const warmBtn = document.getElementById('warmupBtn');
const warmStat = document.getElementById('warmup-status');
const warmBar  = document.getElementById('warmup-fill');
const warmLog  = document.getElementById('warmup-log');

// 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 currentIdx = 0;
let mode = 'view';
let rect = null, dragging=false, sx=0, sy=0;
let color = '#10b981';
let rectMap = new Map();
let masks = [];
let maskedSet = new Set();
let timelineUrls = [];
let portionStart = null;
let portionEnd = null; // exclusive
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){
  const boxRect = tlBox.getBoundingClientRect();
  const elRect  = el.getBoundingClientRect();
  const current = tlBox.scrollLeft;
  const elMid   = (elRect.left - boxRect.left) + current + (elRect.width / 2);
  const target  = Math.max(0, elMid - (tlBox.clientWidth / 2));
  tlBox.scrollTo({ left: target, behavior: 'auto' });
}
async function ensureThumbVisibleCentered(idx){
  for(let k=0; k<50; k++){
    const el = findThumbEl(idx);
    if(el){
      const img = el.querySelector('img');
      if(!img.complete || img.naturalWidth === 0){
        await new Promise(r=>setTimeout(r, 30));
      }else{
        rawCenterThumb(el);
        await new Promise(r=>requestAnimationFrame(()=>r()));
        updatePlayhead();
        return true;
      }
    }else{
      await new Promise(r=>setTimeout(r, 30));
    }
  }
  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 ✅');
}
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; }
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';
    rect = rectMap.get(currentIdx) || null; 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';
    rect=null; draw();
  }
}
function draw(){
  ctx.clearRect(0,0,canvas.width,canvas.height);
  if(rect){
    const x=Math.min(rect.x1,rect.x2), y=Math.min(rect.y1,rect.y2);
    const w=Math.abs(rect.x2-rect.x1), h=Math.abs(rect.y2-rect.y1);
    ctx.strokeStyle=rect.color||color; ctx.lineWidth=2; ctx.strokeRect(x,y,w,h);
    ctx.fillStyle=(rect.color||color)+'28'; ctx.fillRect(x,y,w,h);
  }
}
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;
  rect={x1:sx,y1:sy,x2:sx,y2:sy,color:color}; draw();
});
canvas.addEventListener('mousemove',(e)=>{
  if(!dragging) return;
  const r=canvas.getBoundingClientRect();
  rect.x2=e.clientX-r.left; rect.y2=e.clientY-r.top; draw();
});
['mouseup','mouseleave'].forEach(ev=>canvas.addEventListener(ev,()=>{ dragging=false; }));
btnClear.onclick=()=>{ rect=null; rectMap.delete(currentIdx); 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(rect){ rect.color=color; draw(); }
  };
});
// === Timeline ===
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, Math.min(portionStart, frames-1));
    const e = Math.max(s+1, Math.min(frames, portionEnd)); // fin exclusive
    tlBox.innerHTML = ''; thumbEls = new Map(); ensureOverlays();
    for (let i = s; i < e; i++) addThumb(i, 'append');  // rendre TOUTE la portion
    timelineStart = s; 
    timelineEnd   = e;
    viewRangeStart = s;
    viewRangeEnd   = e;
    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];
  img.onerror = () => {
    const fallback = `/frame_idx?vid=${encodeURIComponent(vidName)}&idx=${idx}`;
    img.onerror = null;
    img.src = fallback;
    img.onload = () => {
      const nu = `/thumbs/f_${vidStem}_${idx}.jpg?b=${Date.now()}`;
      timelineUrls[idx] = nu;
      img.src = nu;
      img.onload = null;
    };
  };
  if(idx===currentIdx){ img.classList.add('sel'); if(isPaused) img.classList.add('sel-strong'); }
  img.onclick=async ()=>{
    currentIdx=idx; player.currentTime=idxToSec(currentIdx);
    if(mode==='edit'){ rect = rectMap.get(currentIdx)||null; 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);
}
// Scroll chunk (mode normal uniquement)
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
isolerBoucle.onclick = async ()=>{
  const start = Math.max(0, parseInt(goFrame.value || '1',10) - 1);
  const endIn = parseInt(endPortion.value || '',10);
  if(!endPortion.value || endIn <= (start+1) || endIn > frames){ alert('Portion invalide (fin > début)'); return; }
  const endExclusive = Math.min(frames, endIn); // fin exclusive; "55" => inclut #55 (idx 54)
  portionStart = start; 
  portionEnd   = endExclusive;
  viewRangeStart = start; viewRangeEnd = endExclusive;
  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
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 (thumbs)
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{
    const r=await fetch('/meta/'+encodeURIComponent(vidName));
    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{ const r=await fetch('/meta/'+encodeURIComponent(vidName)); if(r.ok){ const m=await r.json(); fps=m.fps||30; frames=m.frames||0; } }catch{}
  }
  currentIdx=0; goFrame.value=1; rectMap.clear(); rect=null; draw();
});
window.addEventListener('resize', ()=>{ fitCanvas(); });
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'){ rect = rectMap.get(currentIdx) || null; 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);
  if(mode==='edit'){ rect = rectMap.get(currentIdx) || null; draw(); }
  await renderTimeline(currentIdx);
  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);
  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
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)));
  rectMap.clear();
  // simple: un seul rect "actif" par frame (on affiche le dernier enregistré)
  masks.forEach(m=>{
    if(m.shape==='rect'){
      const [x1,y1,x2,y2] = m.points;
      const normW = canvas.clientWidth, normH = canvas.clientHeight;
      rectMap.set(m.frame_idx, {x1:x1*normW, y1:y1*normH, x2:x2*normW, y2:y2*normH, color:m.color});
    }
  });
  maskedCount.textContent = `(${maskedSet.size} ⭐)`;
  if(!masks.length){ box.textContent='—'; loadingInd.style.display='none'; 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';
}
// Save mask (+ cache)
btnSave.onclick = async ()=>{
  if(!rect || !vidName){ alert('Aucune sélection.'); return; }
  const defaultName = `frame ${currentIdx+1}`;
  const note = (prompt('Nom du masque (optionnel) :', defaultName) || defaultName).trim();
  const normW = canvas.clientWidth, normH = canvas.clientHeight;
  const x=Math.min(rect.x1,rect.x2)/normW;
  const y=Math.min(rect.y1,rect.y2)/normH;
  const w=Math.abs(rect.x2-rect.x1)/normW;
  const h=Math.abs(rect.y2-rect.y1)/normH;
  const payload={vid:vidName,time_s:player.currentTime,frame_idx:currentIdx,shape:'rect',points:[x,y,x+w,y+h],color:rect.color||color,note:note};
  addPending(payload);
  try{
    const r=await fetch('/mask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
    if(r.ok){
      const lst = loadPending().filter(x => !(x.vid===payload.vid && x.frame_idx===payload.frame_idx && x.time_s===payload.time_s));
      savePendingList(lst);
      rectMap.set(currentIdx,{...rect});
      await loadMasks(); await renderTimeline(currentIdx);
      showToast('Masque enregistré ✅');
    } else {
      const txt = await r.text();
      alert('Échec enregistrement masque: ' + r.status + ' ' + txt);
    }
  }catch(e){
    alert('Erreur réseau lors de l’\u00e9nregistrement du masque.');
  }
};
// Warm-up button
warmBtn.onclick = async ()=>{
  try{ await fetch('/warmup/start',{method:'POST'}); }catch{}
  const poll = async ()=>{
    try{
      const r = await fetch('/warmup/status');
      const st = await r.json();
      warmBar.style.width = (st.percent||0) + '%';
      let txt = (st.state||'idle');
      if(st.state==='running' && st.current){ txt += ' · ' + st.current; }
      if(st.state==='error'){ txt += ' · erreur'; }
      warmStat.textContent = txt;
      const lines = (st.log||[]).slice(-6);
      warmLog.innerHTML = lines.map(x=>String(x)).join('<br>');
      if(st.state==='done' || st.state==='error') return; else setTimeout(poll, 1000);
    }catch{ setTimeout(poll, 1500); }
  };
  poll();
};
// 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();
// Hide controls in edit-mode
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:
    msg = urllib.parse.unquote(msg or "")
  except Exception:
    pass
  html = HTML_TEMPLATE.replace("__VID__", urllib.parse.quote(vid)).replace("__MSG__", msg)
  return HTMLResponse(content=html)