File size: 46,562 Bytes
e65877c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8c863e
 
e65877c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Vardrobe – wirtualna przymierzalnia na Gemini Omni 1.2 Flash.
// Serwer bez zależności: trzyma klucz API, buduje prompt, woła Interactions API
// i zapisuje gotowe klipy w ./outputs.

import http from 'node:http';
import https from 'node:https';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
loadEnv(path.join(ROOT, '.env'));

const PORT = Number(process.env.PORT) || 3000;
const HOST = process.env.HOST || '127.0.0.1';
let API_KEY = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY || '';
let HF_TOKEN = process.env.HF_TOKEN || process.env.HUGGINGFACE_TOKEN || '';
const ENV_FILE = path.join(ROOT, '.env');
const MODEL = process.env.OMNI_MODEL || 'gemini-omni-1.2-flash';
const API_BASE = (process.env.GEMINI_API_BASE || 'https://generativelanguage.googleapis.com').replace(/\/$/, '');
const PUBLIC_DIR = path.join(ROOT, 'public');
const OUTPUT_DIR = path.join(ROOT, 'outputs');
const MAX_BODY = 40 * 1024 * 1024;
const REQUEST_TIMEOUT = 10 * 60 * 1000;

// Hugging Face Space ustawia SPACE_ID i SPACE_HOST. Klucze przychodzą wtedy
// z sekretów Space'a, a aplikacja jest dostępna pod adresem *.hf.space.
const ON_SPACE = Boolean(process.env.SPACE_ID);
const EXTRA_HOSTS = [process.env.SPACE_HOST, ...(process.env.ALLOWED_HOSTS || '').split(',')]
  .map((h) => (h || '').trim().toLowerCase())
  .filter(Boolean);
const APP_PASSWORD = process.env.APP_PASSWORD || '';

fs.mkdirSync(OUTPUT_DIR, { recursive: true });

// ---------------------------------------------------------------- opcje

const SCENES = {
  fitting:
    'A bright, modern fitting room with a full-length mirror and soft, even light. The person stands facing the camera, then turns slowly to the left and to the right to show the outfit from the front and both sides, glancing down at it as if checking the fit.',
  studio:
    'A clean photo studio with a light grey seamless backdrop and soft diffused light. The person stands facing the camera, then turns slowly through a full 360 degrees to show the outfit from every side, and ends facing the camera again.',
  original:
    'Keep the original location, background and lighting from the full-body photo of the person. The person shifts their weight and turns slightly left and right with small, natural movements to show the outfit.',
  street:
    'A sunny city street with a softly blurred background, in the style of a casual fashion editorial. The person walks naturally toward the camera, then stops and turns slightly to show the outfit.',
};
const ASPECTS = ['9:16', '16:9'];
const RESOLUTIONS = ['360p', '720p', '1080p'];
const DURATIONS = [4, 6, 8, 10];
const IMAGE_MIMES = ['image/jpeg', 'image/png', 'image/webp'];
const MAX_GARMENTS = 4;
const GARMENT_KINDS = ['upper', 'lower', 'dress', 'other'];
const KIND_EN = {
  upper: 'a top or other upper-body garment',
  lower: 'trousers, shorts or a skirt',
  dress: 'a dress or one-piece outfit',
  other: 'an accessory or other item, such as shoes, a bag or a hat',
};

// Szacunkowy rozmiar klipu w MB na sekundę. Powyżej ~4 MB Google zaleca
// dostarczenie wideo przez Files API (delivery: "uri") zamiast base64.
const MB_PER_SECOND = { '360p': 0.15, '720p': 0.4, '1080p': 0.9 };

function cleanOptions(raw = {}) {
  return {
    aspect: ASPECTS.includes(raw.aspect) ? raw.aspect : '9:16',
    resolution: RESOLUTIONS.includes(raw.resolution) ? raw.resolution : '360p',
    duration: DURATIONS.includes(Number(raw.duration)) ? Number(raw.duration) : 4,
    scene: Object.hasOwn(SCENES, raw.scene) ? raw.scene : 'fitting',
    notes: typeof raw.notes === 'string' ? raw.notes.trim().slice(0, 500) : '',
  };
}

function responseFormat(options) {
  const fmt = {
    type: 'video',
    aspect_ratio: options.aspect,
    resolution: options.resolution,
    duration: `${options.duration}s`,
  };
  if (options.duration * MB_PER_SECOND[options.resolution] > 3.5) fmt.delivery = 'uri';
  return fmt;
}

function cleanImage(img, label) {
  if (!img || typeof img.data !== 'string' || !img.data) {
    throw new UserError(`Brakuje zdjęcia: ${label}.`);
  }
  if (!IMAGE_MIMES.includes(img.mime)) {
    throw new UserError(`Nieobsługiwany format zdjęcia (${label}). Użyj JPG, PNG lub WebP.`);
  }
  const data = img.data.replace(/^data:[^,]*,/, '');
  if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
    throw new UserError(`Uszkodzone dane zdjęcia (${label}).`);
  }
  return { mime: img.mime, data };
}

// ---------------------------------------------------------------- prompt

function buildTryOnPrompt({ hasFace, garmentKinds, options }) {
  const refs = ['Image 1 is a full-body photo of the person who must appear in the video.'];
  let next = 2;
  if (hasFace) {
    refs.push('Image 2 is a close-up of the same person\'s face. Use it to keep their facial features exact.');
    next = 3;
  }
  garmentKinds.forEach((kind, i) => {
    refs.push(`Image ${next + i} is a clothing reference: ${KIND_EN[kind]}.`);
  });
  refs.push(
    'Use the clothing references only for the clothes. Ignore any model, mannequin, hanger, packaging or background shown in them.'
  );

  const lines = [
    'Virtual try-on video.',
    '',
    ...refs,
    '',
    'Create a photorealistic video of this exact person wearing the referenced clothing.',
    'Identity: keep the face, facial features, skin tone, hairstyle, hair colour, body shape, height and proportions exactly as in the photos of the person. It must clearly be the same person. Do not beautify, slim or reshape them.',
    'Clothing: reproduce every referenced item faithfully: the same colour, pattern, print, fabric texture, cut, length, fit, logos and small details such as buttons, seams and pockets. Each item replaces whatever the person wore on that part of the body; keep the rest of their original outfit. The fabric drapes, folds and moves naturally with the body, with a realistic fit for this person\'s size.',
    `Scene: ${SCENES[options.scene]}`,
    'Camera: full-body framing with the head and feet visible, steady camera, sharp focus, natural light.',
    'Audio: quiet natural ambience only, no music, no speech.',
    'Avoid: other people, text, captions, logos that are not on the garments, distorted hands, any change to the face.',
  ];
  if (options.notes) lines.push('', `Additional instructions from the user: ${options.notes}`);
  return lines.join('\n');
}

function buildRefinePrompt(instruction) {
  return [
    `Edit the previous video: ${instruction}`,
    'Keep the same person with an identical face and body, and the same clothing except for the requested change. Keep it photorealistic.',
  ].join('\n');
}

// ---------------------------------------------------------------- Gemini API

class UserError extends Error {
  constructor(message, status = 400) {
    super(message);
    this.status = status;
  }
}

class ApiError extends Error {
  constructor(status, detail) {
    super(detail);
    this.apiStatus = status;
  }
}

function request(urlString, { method = 'GET', headers = {}, body = null } = {}, redirects = 0) {
  return new Promise((resolve, reject) => {
    const url = new URL(urlString);
    const lib = url.protocol === 'http:' ? http : https;
    const req = lib.request(url, { method, headers, timeout: REQUEST_TIMEOUT }, (res) => {
      const location = res.headers.location;
      if ([301, 302, 303, 307, 308].includes(res.statusCode) && location && redirects < 5) {
        res.resume();
        const nextUrl = new URL(location, url);
        // Klucz API wysyłamy tylko do tego samego hosta.
        const nextHeaders = nextUrl.host === url.host && headers['x-goog-api-key']
          ? { 'x-goog-api-key': headers['x-goog-api-key'] }
          : {};
        resolve(request(nextUrl.toString(), { headers: nextHeaders }, redirects + 1));
        return;
      }
      const chunks = [];
      res.on('data', (c) => chunks.push(c));
      res.on('end', () => resolve({ status: res.statusCode, buffer: Buffer.concat(chunks) }));
      res.on('error', reject);
    });
    req.on('timeout', () => req.destroy(new Error('Google nie odpowiedział w ciągu 10 minut.')));
    req.on('error', reject);
    if (body) req.write(body);
    req.end();
  });
}

async function apiJSON(method, apiPath, payload) {
  const body = payload ? JSON.stringify(payload) : null;
  const headers = { 'x-goog-api-key': API_KEY };
  if (body) {
    headers['Content-Type'] = 'application/json';
    headers['Content-Length'] = Buffer.byteLength(body);
  }
  const { status, buffer } = await request(`${API_BASE}${apiPath}`, { method, headers, body });
  const text = buffer.toString('utf8');
  let json = null;
  try {
    json = JSON.parse(text);
  } catch {
    // zostaw null
  }
  if (status >= 400 || !json) {
    throw new ApiError(status, json?.error?.message || text.slice(0, 500) || `HTTP ${status}`);
  }
  return json;
}

function friendlyApiError(err) {
  const s = err.apiStatus;
  const d = err.message;
  if (s === 400) return new UserError(`Google odrzucił zapytanie: ${d}`, 400);
  if (s === 401 || s === 403)
    return new UserError(
      `Klucz API nie ma dostępu do modelu ${MODEL}. Sprawdź klucz i czy projekt ma włączone płatności (Omni nie ma darmowego planu). Szczegóły: ${d}`,
      502
    );
  if (s === 404) return new UserError(`Model ${MODEL} jest niedostępny dla tego klucza. Szczegóły: ${d}`, 502);
  if (s === 429) return new UserError(`Przekroczono limit zapytań lub budżet. Odczekaj chwilę i spróbuj ponownie. Szczegóły: ${d}`, 429);
  return new UserError(`Serwer Google zwrócił błąd ${s}. Spróbuj ponownie. Szczegóły: ${d}`, 502);
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const PENDING = new Set(['in_progress', 'queued', 'pending', 'running', 'created', 'processing']);
const FAILED = new Set(['failed', 'cancelled', 'canceled', 'expired']);

// Szuka wideo w odpowiedzi. SDK wystawia je jako output_video, a REST trzyma
// je w steps[].content[] z type "video", więc przeszukujemy całe drzewo.
function findVideo(node, depth = 0) {
  if (!node || typeof node !== 'object' || depth > 14) return null;
  if (!Array.isArray(node)) {
    const mime = node.mime_type || node.mimeType;
    const isVideo = node.type === 'video' || (typeof mime === 'string' && mime.startsWith('video/'));
    if (isVideo && (typeof node.data === 'string' || typeof node.uri === 'string')) {
      return { data: node.data || null, uri: node.uri || null };
    }
    if (node.output_video) {
      const v = findVideo({ type: 'video', ...node.output_video }, depth + 1);
      if (v) return v;
    }
  }
  for (const value of Array.isArray(node) ? node : Object.values(node)) {
    const found = findVideo(value, depth + 1);
    if (found) return found;
  }
  return null;
}

// Zbiera krótkie teksty z odpowiedzi (np. powód blokady), pomijając nasz prompt.
function collectTexts(node, prompt, out = new Set(), depth = 0) {
  if (!node || typeof node !== 'object' || depth > 14) return out;
  for (const [key, value] of Object.entries(node)) {
    if (typeof value === 'string') {
      if (/text|message|reason/i.test(key) && value.length < 1500 && value !== prompt) out.add(value.trim());
    } else if (value && typeof value === 'object') {
      collectTexts(value, prompt, out, depth + 1);
    }
  }
  return out;
}

function shrinkForLog(node) {
  if (typeof node === 'string') return node.length > 300 ? `${node.slice(0, 80)}… (${node.length} znaków)` : node;
  if (Array.isArray(node)) return node.map(shrinkForLog);
  if (node && typeof node === 'object') return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, shrinkForLog(v)]));
  return node;
}

async function downloadFile(uri) {
  const match = uri.match(/files\/([A-Za-z0-9_-]+)/);
  if (match) {
    const deadline = Date.now() + 5 * 60 * 1000;
    for (;;) {
      const file = await apiJSON('GET', `/v1beta/files/${match[1]}`);
      const state = String(file.state || '').toUpperCase();
      if (state === 'FAILED') throw new UserError('Google nie przetworzył pliku wideo.', 502);
      if (!state || state === 'ACTIVE') break;
      if (Date.now() > deadline) throw new UserError('Plik wideo nie był gotowy w ciągu 5 minut.', 504);
      await sleep(3000);
    }
  }
  let target = uri;
  if (match && !uri.includes(':download')) target = `${API_BASE}/v1beta/files/${match[1]}:download?alt=media`;
  else if (!/^https?:/.test(uri)) target = `${API_BASE}/v1beta/${uri.replace(/^\/?(v1beta\/)?/, '')}`;

  const sameHost = new URL(target).host === new URL(API_BASE).host;
  const { status, buffer } = await request(target, { headers: sameHost ? { 'x-goog-api-key': API_KEY } : {} });
  if (status >= 400) throw new ApiError(status, buffer.toString('utf8').slice(0, 300));
  return buffer;
}

async function runInteraction(body, prompt) {
  let res = await apiJSON('POST', '/v1beta/interactions', body);
  const deadline = Date.now() + REQUEST_TIMEOUT;
  while (!findVideo(res) && res.id && PENDING.has(String(res.status).toLowerCase())) {
    if (Date.now() > deadline) throw new UserError('Generowanie trwało ponad 10 minut. Spróbuj krótszego klipu.', 504);
    await sleep(5000);
    res = await apiJSON('GET', `/v1beta/interactions/${encodeURIComponent(res.id)}`);
  }
  await fsp.writeFile(path.join(OUTPUT_DIR, 'last-response.json'), JSON.stringify(shrinkForLog(res), null, 2));

  const video = findVideo(res);
  const texts = [...collectTexts(res, prompt)].filter(Boolean);
  if (!video || FAILED.has(String(res.status).toLowerCase())) {
    const why = texts.length ? ` Odpowiedź modelu: ${texts.join(' ')}` : '';
    throw new UserError(
      `Model nie zwrócił wideo (status: ${res.status || 'brak'}). Najczęściej to filtr bezpieczeństwa. Spróbuj innego zdjęcia lub opisu.${why}`,
      422
    );
  }
  const buffer = video.data ? Buffer.from(video.data, 'base64') : await downloadFile(video.uri);
  if (buffer.length < 1000) throw new UserError('Otrzymany plik wideo jest pusty.', 502);
  return { buffer, interactionId: res.id || null };
}

// ---------------------------------------------------------------- zapis wyników

function newId() {
  const d = new Date();
  const p = (n) => String(n).padStart(2, '0');
  const stamp = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}_${p(d.getHours())}-${p(d.getMinutes())}-${p(d.getSeconds())}`;
  return `${stamp}_${crypto.randomBytes(2).toString('hex')}`;
}

const OUTPUT_EXTS = ['.mp4', '.png', '.jpg', '.webp'];

// ext "mp4" zapisuje się jako wideo (pole video), pozostałe jako zdjęcie (pole image).
async function saveResult(buffer, ext, meta) {
  const id = newId();
  const url = `/outputs/${id}.${ext}`;
  const item = { id, created: new Date().toISOString(), ...(ext === 'mp4' ? { video: url } : { image: url }), ...meta };
  await fsp.writeFile(path.join(OUTPUT_DIR, `${id}.${ext}`), buffer);
  await fsp.writeFile(path.join(OUTPUT_DIR, `${id}.json`), JSON.stringify(item, null, 2));
  return item;
}

async function listHistory() {
  const files = await fsp.readdir(OUTPUT_DIR);
  const items = [];
  for (const f of files) {
    if (!f.endsWith('.json') || f === 'last-response.json') continue;
    try {
      const item = JSON.parse(await fsp.readFile(path.join(OUTPUT_DIR, f), 'utf8'));
      const media = item.image || item.video;
      if (media && fs.existsSync(path.join(OUTPUT_DIR, path.basename(media)))) items.push(item);
    } catch {
      // pomiń uszkodzony wpis
    }
  }
  return items.sort((a, b) => (a.created < b.created ? 1 : -1)).slice(0, 60);
}

// ---------------------------------------------------------------- handlery

function requireKey() {
  if (!API_KEY) throw new UserError('Brakuje klucza API. Dodaj go przyciskiem „Dodaj klucz API” u góry strony.', 503);
}

// ---------------------------------------------------------------- klucz API

function cleanKind(kind) {
  return GARMENT_KINDS.includes(kind) ? kind : 'upper';
}

function statusPayload() {
  return {
    keyConfigured: Boolean(API_KEY),
    keyHint: API_KEY ? `…${API_KEY.slice(-4)}` : null,
    model: MODEL,
    hf: {
      configured: Boolean(HF_TOKEN),
      user: hfUser?.name || null,
      isPro: Boolean(hfUser?.isPro),
      libraryInstalled: gradioModule !== null,
    },
  };
}

const LOOPBACK = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);

function requireLocal(req) {
  if (ON_SPACE) {
    throw new UserError('Na Hugging Face klucze zmienisz w ustawieniach Space\'a: Settings → Variables and secrets.', 403);
  }
  if (!LOOPBACK.has(req.socket.remoteAddress)) {
    throw new UserError('Klucz można zmienić tylko na komputerze, na którym działa serwer.', 403);
  }
}

async function verifyKey(key) {
  const headers = { 'x-goog-api-key': key };
  let list;
  let model;
  try {
    list = await request(`${API_BASE}/v1beta/models?pageSize=1`, { headers });
    model = list.status < 400 ? await request(`${API_BASE}/v1beta/models/${MODEL}`, { headers }) : null;
  } catch {
    throw new UserError('Nie udało się połączyć z Google. Sprawdź połączenie z internetem.', 502);
  }
  if ([400, 401, 403].includes(list.status)) {
    throw new UserError('Google nie przyjął tego klucza. Sprawdź, czy skopiowano go w całości.');
  }
  if (list.status >= 400) throw new UserError(`Nie udało się sprawdzić klucza (HTTP ${list.status}). Spróbuj za chwilę.`, 502);
  return { modelVisible: model.status < 400 };
}

async function writeEnvVar(name, value) {
  let text = '';
  try {
    text = await fsp.readFile(ENV_FILE, 'utf8');
  } catch {
    text = '# Ustawienia Vardrobe\n';
  }
  const line = `${name}=${value}`;
  const pattern = new RegExp(`^[ \\t]*(?:export[ \\t]+)?${name}[ \\t]*=.*$`, 'm');
  text = pattern.test(text) ? text.replace(pattern, () => line) : `${text}${text.endsWith('\n') ? '' : '\n'}${line}\n`;
  await fsp.writeFile(ENV_FILE, text, { mode: 0o600 });
}

const writeEnvKey = (key) => writeEnvVar('GEMINI_API_KEY', key);

async function handleSetKey(req, payload) {
  requireLocal(req);
  const key = typeof payload.key === 'string' ? payload.key.trim() : '';
  if (!/^[A-Za-z0-9_.-]{20,200}$/.test(key)) {
    throw new UserError('To nie wygląda na klucz API. Skopiuj go jeszcze raz z Google AI Studio.');
  }
  const { modelVisible } = await verifyKey(key);
  await writeEnvKey(key);
  API_KEY = key;
  console.log(`[vardrobe] zapisano klucz API ${statusPayload().keyHint}`);
  return { ...statusPayload(), modelVisible };
}

async function handleDeleteKey(req) {
  requireLocal(req);
  await writeEnvKey('');
  API_KEY = '';
  console.log('[vardrobe] usunięto klucz API');
  return statusPayload();
}

async function deleteHistoryItem(id) {
  if (!/^[\w-]{1,80}$/.test(id) || id === 'last-response') throw new UserError('Nieprawidłowy identyfikator.');
  for (const ext of [...OUTPUT_EXTS, '.json']) {
    await fsp.rm(path.join(OUTPUT_DIR, `${id}${ext}`), { force: true });
  }
  return { ok: true };
}

// ---------------------------------------------------------------- Hugging Face: zdjęcia

// Modele try-on uruchamiane na Spaces z ZeroGPU. Z tokenem konta PRO zużywają
// jego dzienny limit GPU (40 min), bez tokenu mały limit anonimowy.
const HF_MODELS = {
  fitdit: { space: 'BoyuanJiang/FitDiT', name: 'FitDiT', kinds: ['upper', 'lower', 'dress'] },
  idm: { space: 'yisol/IDM-VTON', name: 'IDM-VTON', kinds: ['upper'] },
  leffa: { space: 'franciszzj/Leffa', name: 'Leffa', kinds: ['upper', 'lower', 'dress'] },
};
const HF_TIMEOUT = 6 * 60 * 1000;
// Kolejność nakładania: sukienka, potem dół, na końcu góra (góra zachodzi na dół).
const KIND_ORDER = { dress: 0, lower: 1, upper: 2 };

let hfUser = null;
let gradioModule;

async function gradio() {
  if (gradioModule === undefined) gradioModule = await import('@gradio/client').catch(() => null);
  if (!gradioModule) {
    throw new UserError('Brakuje biblioteki do Hugging Face. W folderze aplikacji uruchom: npm install', 500);
  }
  return gradioModule;
}

const randomSeed = () => crypto.randomInt(0, 2 ** 31 - 1);

const HF_RUNNERS = {
  async fitdit(app, person, garment, kind, quality) {
    const { handle_file } = await gradio();
    const category = { upper: 'Upper-body', lower: 'Lower-body', dress: 'Dresses' }[kind];
    const mask = await app.predict('/generate_mask', {
      vton_img: handle_file(person),
      category,
      offset_top: 0,
      offset_bottom: 0,
      offset_left: 0,
      offset_right: 0,
    });
    const out = await app.predict('/process', {
      vton_img: handle_file(person),
      garm_img: handle_file(garment),
      pre_mask: mask.data[0],
      pose_image: mask.data[1],
      n_steps: quality === 'high' ? 30 : 20,
      image_scale: 2,
      seed: randomSeed(),
      num_images_per_prompt: 1,
      resolution: quality === 'high' ? '1152x1536' : '768x1024',
    });
    return out.data[0]?.[0]?.image;
  },

  async idm(app, person, garment, _kind, quality, description) {
    const { handle_file } = await gradio();
    const out = await app.predict('/tryon', {
      dict: { background: handle_file(person), layers: [], composite: null },
      garm_img: handle_file(garment),
      garment_des: description || 'a garment',
      is_checked: true,
      is_checked_crop: true,
      denoise_steps: quality === 'high' ? 40 : 30,
      seed: randomSeed(),
    });
    return out.data[0];
  },

  async leffa(app, person, garment, kind, quality) {
    const { handle_file } = await gradio();
    const out = await app.predict('/leffa_predict_vt', {
      src_image_path: handle_file(person),
      ref_image_path: handle_file(garment),
      ref_acceleration: false,
      step: quality === 'high' ? 50 : 30,
      scale: 2.5,
      seed: randomSeed(),
      vt_model_type: kind === 'upper' ? 'viton_hd' : 'dress_code',
      vt_garment_type: { upper: 'upper_body', lower: 'lower_body', dress: 'dresses' }[kind],
      vt_repaint: false,
    });
    return out.data[0];
  },
};

function withTimeout(promise, ms, message) {
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new UserError(message, 504)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}

async function fetchResultImage(fileData) {
  const url = typeof fileData === 'string' ? fileData : fileData?.url;
  if (!url) throw new UserError('Model nie zwrócił zdjęcia. Spróbuj innego zdjęcia albo modelu.', 502);
  const headers = HF_TOKEN && new URL(url).hostname.endsWith('.hf.space') ? { Authorization: `Bearer ${HF_TOKEN}` } : {};
  const res = await fetch(url, { headers });
  if (!res.ok) throw new UserError(`Nie udało się pobrać wyniku z Hugging Face (HTTP ${res.status}).`, 502);
  const type = (res.headers.get('content-type') || 'image/png').split(';')[0];
  return { buffer: Buffer.from(await res.arrayBuffer()), type };
}

function friendlyHfError(err, modelName) {
  const msg = String(err?.message || err || 'nieznany błąd');
  if (/quota/i.test(msg)) {
    let wait = /Try again in ([\d:]+)/.exec(msg)?.[1];
    if (wait && !/[1-9]/.test(wait)) wait = null;
    const tail = HF_TOKEN
      ? 'Konto PRO ma 40 minut GPU dziennie; po ich wykorzystaniu można dokupić czas w ustawieniach Hugging Face.'
      : 'Dodaj token Hugging Face w Połączeniach, żeby korzystać z limitu konta PRO.';
    return new UserError(`Wyczerpał się dzienny limit GPU na Hugging Face${wait ? ` (odnowi się za ${wait})` : ''}. ${tail}`, 429);
  }
  if (/space.*(sleep|paus|build|error)|not running|could not (resolve|connect)|config/i.test(msg)) {
    return new UserError(`Model ${modelName} jest teraz niedostępny na Hugging Face. Wybierz inny model albo spróbuj za kilka minut.`, 503);
  }
  return new UserError(`${modelName} zwrócił błąd: ${msg}`, 502);
}

async function handleTryOnPhoto(payload) {
  const person = cleanImage(payload.person, 'Twoja sylwetka');
  const raw = Array.isArray(payload.garments) ? payload.garments.slice(0, MAX_GARMENTS) : [];
  if (!raw.length) throw new UserError('Dodaj zdjęcie co najmniej jednego ubrania.');
  const garments = raw.map((g, i) => ({ ...cleanImage(g, `ubranie ${i + 1}`), kind: cleanKind(g.kind), index: i }));

  const wearable = garments.filter((g) => g.kind !== 'other').sort((a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind] || a.index - b.index);
  const skipped = garments.length - wearable.length;
  if (!wearable.length) {
    throw new UserError('Modele zdjęciowe ubierają tylko górę, dół i sukienki. Zmień rodzaj ubrania albo wybierz wideo z Gemini.');
  }

  const modelKey = Object.hasOwn(HF_MODELS, payload.options?.model) ? payload.options.model : 'fitdit';
  const quality = payload.options?.quality === 'high' ? 'high' : 'standard';
  const description = typeof payload.options?.description === 'string' ? payload.options.description.trim().slice(0, 200) : '';
  const { Client } = await gradio();

  const started = Date.now();
  const connections = {};
  const used = [];
  let current = Buffer.from(person.data, 'base64');
  let result = null;

  for (const g of wearable) {
    // IDM-VTON ubiera tylko górę; dół i sukienki przejmuje FitDiT.
    const key = HF_MODELS[modelKey].kinds.includes(g.kind) ? modelKey : 'fitdit';
    const model = HF_MODELS[key];
    try {
      connections[key] ??= await Client.connect(model.space, HF_TOKEN ? { token: HF_TOKEN } : {});
      const fileData = await withTimeout(
        HF_RUNNERS[key](connections[key], current, Buffer.from(g.data, 'base64'), g.kind, quality, description),
        HF_TIMEOUT,
        `${model.name} nie odpowiedział w ciągu 6 minut. Kolejka GPU może być długa, spróbuj za chwilę.`
      );
      result = await fetchResultImage(fileData);
    } catch (err) {
      throw err instanceof UserError ? err : friendlyHfError(err, model.name);
    }
    current = result.buffer;
    used.push(key);
  }

  const ext = { 'image/png': 'png', 'image/webp': 'webp', 'image/jpeg': 'jpg' }[result.type] || 'png';
  const item = await saveResult(result.buffer, ext, {
    kind: 'photo',
    engine: 'hf',
    model: modelKey,
    modelsUsed: [...new Set(used)],
    options: { model: modelKey, quality },
    garmentCount: wearable.length,
  });
  const notes = [];
  if (skipped) notes.push(`Pominięto ${skipped === 1 ? 'dodatek' : `${skipped} dodatki`}: modele zdjęciowe ubierają tylko górę, dół i sukienki.`);
  if (used.some((k) => k !== modelKey)) notes.push('IDM-VTON ubiera tylko górę, więc dół lub sukienkę przymierzył FitDiT.');
  log(`zdjęcie ${used.join(' → ')} (${quality})`, started, result.buffer);
  return { ...item, notes };
}

async function fetchHfUser(token) {
  let res;
  try {
    res = await fetch('https://huggingface.co/api/whoami-v2', { headers: { Authorization: `Bearer ${token}` } });
  } catch {
    throw new UserError('Nie udało się połączyć z Hugging Face. Sprawdź połączenie z internetem.', 502);
  }
  if (res.status === 401 || res.status === 403) {
    throw new UserError('Hugging Face nie przyjął tego tokenu. Sprawdź, czy skopiowano go w całości.');
  }
  if (!res.ok) throw new UserError(`Nie udało się sprawdzić tokenu (HTTP ${res.status}). Spróbuj za chwilę.`, 502);
  const me = await res.json();
  return { name: me.name, isPro: Boolean(me.isPro) };
}

async function handleSetHfToken(req, payload) {
  requireLocal(req);
  const token = typeof payload.token === 'string' ? payload.token.trim() : '';
  if (!/^hf_[A-Za-z0-9]{20,}$/.test(token)) {
    throw new UserError('Token Hugging Face zaczyna się od „hf_”. Skopiuj go jeszcze raz ze strony tokenów.');
  }
  const user = await fetchHfUser(token);
  await writeEnvVar('HF_TOKEN', token);
  HF_TOKEN = token;
  hfUser = user;
  console.log(`[vardrobe] połączono z Hugging Face jako ${user.name}${user.isPro ? ' (PRO)' : ''}`);
  return statusPayload();
}

async function handleDeleteHfToken(req) {
  requireLocal(req);
  await writeEnvVar('HF_TOKEN', '');
  HF_TOKEN = '';
  hfUser = null;
  console.log('[vardrobe] usunięto token Hugging Face');
  return statusPayload();
}

// Chroni lokalne API przed wywołaniem z obcych stron (CSRF, DNS rebinding):
// pozwalamy tylko na adresy lokalne/IP i zapytania z tej samej strony.
function hostAllowed(req) {
  const host = (req.headers.host || '').toLowerCase().replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
  return host === 'localhost' || /^[\d.]+$/.test(host) || host.includes(':') || host.endsWith('.local') || EXTRA_HOSTS.includes(host);
}

// ---------------------------------------------------------------- hasło (APP_PASSWORD)

// Bez APP_PASSWORD aplikacja jest otwarta (tak jak lokalnie). Z hasłem każda
// strona i każde API wymaga ciasteczka sesji. Token sesji wynika z hasła, więc
// przetrwa restart serwera, a zmiana hasła wylogowuje wszystkich.
const SESSION_COOKIE = 'vardrobe_session';
const SESSION_MAX_AGE = 30 * 24 * 60 * 60;
const SESSION_TOKEN = APP_PASSWORD
  ? crypto.createHmac('sha256', APP_PASSWORD).update('vardrobe-session-v1').digest('base64url')
  : '';
const MAX_FAILED_LOGINS = 8;
const LOCKOUT_MS = 15 * 60 * 1000;
const failedLogins = new Map();

function safeEqual(a, b) {
  const ha = crypto.createHash('sha256').update(String(a)).digest();
  const hb = crypto.createHash('sha256').update(String(b)).digest();
  return crypto.timingSafeEqual(ha, hb);
}

function readCookie(req, name) {
  for (const part of String(req.headers.cookie || '').split(';')) {
    const i = part.indexOf('=');
    if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();
  }
  return '';
}

function isAuthed(req) {
  return !APP_PASSWORD || safeEqual(readCookie(req, SESSION_COOKIE), SESSION_TOKEN);
}

function clientIp(req) {
  return String(req.headers['x-forwarded-for'] || '').split(',')[0].trim() || req.socket.remoteAddress || '';
}

function sessionCookie(req, value, maxAge) {
  // Na Space aplikacja działa też w ramce na huggingface.co, więc ciasteczko
  // musi być dozwolone w kontekście innej strony (SameSite=None; Partitioned).
  const https = ON_SPACE || req.headers['x-forwarded-proto'] === 'https';
  const attrs = [`${SESSION_COOKIE}=${value}`, 'Path=/', 'HttpOnly', `Max-Age=${maxAge}`];
  attrs.push(https ? 'Secure; SameSite=None; Partitioned' : 'SameSite=Lax');
  return attrs.join('; ');
}

function readText(req, limit) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    let size = 0;
    req.on('data', (c) => {
      size += c.length;
      if (size <= limit) chunks.push(c);
    });
    req.on('end', () => (size > limit ? reject(new UserError('Za duże zapytanie.', 413)) : resolve(Buffer.concat(chunks).toString('utf8'))));
    req.on('error', reject);
  });
}

function redirect(res, location, headers = {}) {
  res.writeHead(303, { Location: location, 'Cache-Control': 'no-store', ...headers });
  res.end();
}

async function handleLogin(req, res) {
  const ip = clientIp(req);
  const now = Date.now();
  let entry = failedLogins.get(ip);
  if (entry && entry.until <= now) entry = null;
  if (entry && entry.count >= MAX_FAILED_LOGINS) {
    return sendLoginPage(res, 429, 'Za dużo nieudanych prób. Spróbuj ponownie za kwadrans.');
  }
  const password = new URLSearchParams(await readText(req, 4096)).get('password') || '';
  if (!safeEqual(password, APP_PASSWORD)) {
    if (failedLogins.size > 5000) failedLogins.clear();
    failedLogins.set(ip, { count: (entry?.count || 0) + 1, until: now + LOCKOUT_MS });
    await new Promise((r) => setTimeout(r, 800));
    return sendLoginPage(res, 401, 'Nieprawidłowe hasło.');
  }
  failedLogins.delete(ip);
  return redirect(res, '/', { 'Set-Cookie': sessionCookie(req, SESSION_TOKEN, SESSION_MAX_AGE) });
}

function sendLoginPage(res, status, error = '') {
  const body = LOGIN_PAGE.replace('<!--ERROR-->', error ? `<p class="error" role="alert">${error}</p>` : '');
  res.writeHead(status, {
    'Content-Type': MIME['.html'],
    'Content-Length': Buffer.byteLength(body),
    'Cache-Control': 'no-store',
  });
  res.end(body);
}

// Zwraca true, gdy żądanie zostało już obsłużone (logowanie albo odmowa).
async function handleAuth(req, res, pathname) {
  if (!APP_PASSWORD) return false;
  if (pathname === '/login') {
    if (req.method === 'POST') await handleLogin(req, res);
    else if (isAuthed(req)) redirect(res, '/');
    else sendLoginPage(res, 200);
    return true;
  }
  if (pathname === '/logout') {
    redirect(res, '/login', { 'Set-Cookie': sessionCookie(req, '', 0) });
    return true;
  }
  if (isAuthed(req) || pathname === '/favicon.svg') return false;
  if (pathname.startsWith('/api/') || pathname.startsWith('/outputs/')) {
    sendJSON(res, 401, { error: 'Sesja wygasła. Zaloguj się ponownie.', login: true });
  } else {
    redirect(res, '/login');
  }
  return true;
}

const LOGIN_PAGE = `<!doctype html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Vardrobe – logowanie</title>
  <meta name="color-scheme" content="light dark">
  <link rel="icon" href="/favicon.svg" type="image/svg+xml">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Bodoni+Moda:opsz,wght@6..96,400..700&family=Schibsted+Grotesk:wght@400;500;600&display=swap" rel="stylesheet">
  <style>
    :root { --wall: #dde4dc; --paper: #f5f8f3; --ink: #1b2521; --ink-soft: #55635b; --line: #b6c1b8;
      --brass: #b0832f; --brass-deep: #6f4f17; --danger: #a33d2c; --focus: #2f6b55; color-scheme: light; }
    @media (prefers-color-scheme: dark) {
      :root { --wall: #151b18; --paper: #1e2622; --ink: #e2e9e4; --ink-soft: #9caaa2; --line: #36423b;
        --brass: #c4974a; --brass-deep: #7a5820; --danger: #e08672; --focus: #8fd0b4; color-scheme: dark; }
    }
    * { box-sizing: border-box; }
    body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px 16px;
      background: var(--wall); color: var(--ink); font: 1rem/1.5 'Schibsted Grotesk', system-ui, -apple-system, sans-serif; }
    main { width: 100%; max-width: 360px; background: var(--paper); border: 1px solid var(--line);
      border-radius: 8px; padding: 32px 28px; }
    h1 { margin: 0 0 4px; font: 500 2.5rem/1.1 'Bodoni Moda', Didot, Georgia, serif; letter-spacing: -0.01em; }
    p { margin: 0 0 24px; color: var(--ink-soft); }
    label { display: block; font-weight: 500; margin-bottom: 6px; }
    input[type=password] { width: 100%; font: inherit; color: inherit; background: var(--wall);
      border: 1px solid var(--line); border-radius: 4px; padding: 10px 12px; }
    input:focus-visible, button:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
    button { margin-top: 16px; width: 100%; font: inherit; font-weight: 600; color: #fff; background: var(--brass-deep);
      border: 0; border-radius: 4px; padding: 11px 12px; cursor: pointer; }
    button:hover { background: var(--brass); }
    .error { color: var(--danger); margin: 16px 0 0; }
    .frame-note { margin: 20px 0 0; font-size: 0.875rem; }
    .frame-note a { color: inherit; }
    [hidden] { display: none; }
  </style>
</head>
<body>
  <main>
    <h1>Vardrobe</h1>
    <p>Przymierzalnia jest chroniona hasłem.</p>
    <form method="post" action="/login">
      <input type="text" name="username" value="vardrobe" autocomplete="username" hidden>
      <label for="password">Hasło</label>
      <input id="password" type="password" name="password" autocomplete="current-password" required autofocus>
      <button type="submit">Wejdź</button>
    </form>
    <!--ERROR-->
    <p class="frame-note" id="frame-note" hidden>Jeśli logowanie w tej ramce nie działa (np. w Safari),
      <a href="/" target="_blank" rel="noopener">otwórz Vardrobe w nowej karcie</a>.</p>
  </main>
  <script>
    if (window.top !== window.self) {
      var note = document.getElementById('frame-note');
      note.querySelector('a').href = location.origin + '/';
      note.hidden = false;
    }
  </script>
</body>
</html>`;

function sameOrigin(req) {
  const origin = req.headers.origin;
  if (!origin) return true;
  try {
    return new URL(origin).host === req.headers.host;
  } catch {
    return false;
  }
}

function guardApi(req) {
  if (!hostAllowed(req)) throw new UserError('Niedozwolony adres hosta.', 403);
  if (req.method !== 'GET' && !sameOrigin(req)) throw new UserError('Zapytanie z innej strony zostało zablokowane.', 403);
  if (req.method === 'POST' && !String(req.headers['content-type'] || '').startsWith('application/json')) {
    throw new UserError('Oczekiwano danych JSON.', 415);
  }
}

async function handleTryOn(payload) {
  requireKey();
  const person = cleanImage(payload.person, 'Twoja sylwetka');
  const face = payload.face ? cleanImage(payload.face, 'Twoja twarz') : null;
  const garments = Array.isArray(payload.garments) ? payload.garments : [];
  if (!garments.length) throw new UserError('Dodaj zdjęcie co najmniej jednego ubrania.');
  if (garments.length > MAX_GARMENTS) throw new UserError(`Możesz dodać najwyżej ${MAX_GARMENTS} ubrania naraz.`);
  const cleanGarments = garments.map((g, i) => cleanImage(g, `ubranie ${i + 1}`));
  const garmentKinds = garments.map((g) => cleanKind(g.kind));
  const options = cleanOptions(payload.options);

  const prompt = buildTryOnPrompt({ hasFace: Boolean(face), garmentKinds, options });
  const images = [person, ...(face ? [face] : []), ...cleanGarments];
  const body = {
    model: MODEL,
    input: [
      ...images.map((img) => ({ type: 'image', data: img.data, mime_type: img.mime })),
      { type: 'text', text: prompt },
    ],
    response_format: responseFormat(options),
  };

  const started = Date.now();
  const { buffer, interactionId } = await runInteraction(body, prompt);
  const item = await saveResult(buffer, 'mp4', { kind: 'tryon', engine: 'gemini', interactionId, options, garmentCount: cleanGarments.length });
  log(`przymiarka ${options.duration}s ${options.resolution} ${options.aspect} ${options.scene}`, started, buffer);
  return item;
}

async function handleRefine(payload) {
  requireKey();
  const instruction = typeof payload.instruction === 'string' ? payload.instruction.trim().slice(0, 500) : '';
  if (!instruction) throw new UserError('Napisz, co zmienić w klipie.');
  if (typeof payload.interactionId !== 'string' || !payload.interactionId) {
    throw new UserError('Tego klipu nie da się poprawić, bo brakuje identyfikatora rozmowy z modelem.');
  }
  const options = cleanOptions(payload.options);
  const prompt = buildRefinePrompt(instruction);
  const body = {
    model: MODEL,
    previous_interaction_id: payload.interactionId,
    input: [{ type: 'text', text: prompt }],
    response_format: responseFormat(options),
  };

  const started = Date.now();
  const { buffer, interactionId } = await runInteraction(body, prompt);
  const item = await saveResult(buffer, 'mp4', {
    kind: 'refine',
    engine: 'gemini',
    interactionId,
    options,
    instruction,
    refinedFrom: typeof payload.fromId === 'string' ? payload.fromId : null,
  });
  log(`poprawka "${instruction}"`, started, buffer);
  return item;
}

function log(what, started, buffer) {
  const secs = ((Date.now() - started) / 1000).toFixed(1);
  const mb = (buffer.length / 1024 / 1024).toFixed(1);
  console.log(`[vardrobe] ${what}: ${secs} s, ${mb} MB`);
}

// ---------------------------------------------------------------- HTTP

const MIME = {
  '.html': 'text/html; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
  '.json': 'application/json; charset=utf-8',
  '.svg': 'image/svg+xml',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.webp': 'image/webp',
  '.ico': 'image/x-icon',
  '.mp4': 'video/mp4',
};

function sendJSON(res, status, data) {
  const body = JSON.stringify(data);
  res.writeHead(status, { 'Content-Type': MIME['.json'], 'Content-Length': Buffer.byteLength(body), 'Cache-Control': 'no-store' });
  res.end(body);
}

function readJSON(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    let size = 0;
    let tooBig = false;
    req.on('data', (c) => {
      size += c.length;
      if (size > MAX_BODY) tooBig = true;
      else chunks.push(c);
    });
    req.on('end', () => {
      if (tooBig) return reject(new UserError('Zdjęcia są za duże. Spróbuj mniejszych plików.', 413));
      try {
        resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
      } catch {
        reject(new UserError('Nieprawidłowe dane zapytania.'));
      }
    });
    req.on('error', reject);
  });
}

function safeJoin(base, rel) {
  let decoded;
  try {
    decoded = decodeURIComponent(rel);
  } catch {
    return null;
  }
  const full = path.resolve(base, `.${path.sep}${decoded}`);
  return full.startsWith(base + path.sep) ? full : null;
}

async function serveFile(req, res, filePath) {
  let stat;
  try {
    stat = await fsp.stat(filePath);
    if (!stat.isFile()) throw new Error('not a file');
  } catch {
    return sendJSON(res, 404, { error: 'Nie znaleziono.' });
  }
  const type = MIME[path.extname(filePath).toLowerCase()] || 'application/octet-stream';
  const range = req.headers.range && /^bytes=(\d*)-(\d*)$/.exec(req.headers.range);

  // Safari odtwarza wideo tylko z obsługą zakresów (Range).
  if (range) {
    let start;
    let end;
    if (range[1] === '') {
      start = stat.size - Number(range[2]);
      end = stat.size - 1;
    } else {
      start = Number(range[1]);
      end = range[2] === '' ? stat.size - 1 : Math.min(Number(range[2]), stat.size - 1);
    }
    if (!(start >= 0) || start > end) {
      res.writeHead(416, { 'Content-Range': `bytes */${stat.size}` });
      return res.end();
    }
    res.writeHead(206, {
      'Content-Type': type,
      'Content-Length': end - start + 1,
      'Content-Range': `bytes ${start}-${end}/${stat.size}`,
      'Accept-Ranges': 'bytes',
    });
    return fs.createReadStream(filePath, { start, end }).pipe(res);
  }

  res.writeHead(200, { 'Content-Type': type, 'Content-Length': stat.size, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-cache' });
  if (req.method === 'HEAD') return res.end();
  fs.createReadStream(filePath).pipe(res);
}

const server = http.createServer(async (req, res) => {
  const { pathname } = new URL(req.url, 'http://localhost');
  try {
    if (await handleAuth(req, res, pathname)) return;
    if (pathname.startsWith('/api/')) guardApi(req);
    if (pathname === '/api/status' && req.method === 'GET') {
      return sendJSON(res, 200, statusPayload());
    }
    if (pathname === '/api/key' && req.method === 'POST') {
      return sendJSON(res, 200, await handleSetKey(req, await readJSON(req)));
    }
    if (pathname === '/api/key' && req.method === 'DELETE') {
      return sendJSON(res, 200, await handleDeleteKey(req));
    }
    if (pathname === '/api/hf-token' && req.method === 'POST') {
      return sendJSON(res, 200, await handleSetHfToken(req, await readJSON(req)));
    }
    if (pathname === '/api/hf-token' && req.method === 'DELETE') {
      return sendJSON(res, 200, await handleDeleteHfToken(req));
    }
    if (pathname === '/api/tryon-photo' && req.method === 'POST') {
      return sendJSON(res, 200, await handleTryOnPhoto(await readJSON(req)));
    }
    if (pathname === '/api/history' && req.method === 'GET') {
      return sendJSON(res, 200, { items: await listHistory() });
    }
    if (pathname.startsWith('/api/history/') && req.method === 'DELETE') {
      return sendJSON(res, 200, await deleteHistoryItem(pathname.slice('/api/history/'.length)));
    }
    if (pathname === '/api/tryon' && req.method === 'POST') {
      return sendJSON(res, 200, await handleTryOn(await readJSON(req)));
    }
    if (pathname === '/api/refine' && req.method === 'POST') {
      return sendJSON(res, 200, await handleRefine(await readJSON(req)));
    }
    if (pathname.startsWith('/api/')) return sendJSON(res, 404, { error: 'Nie ma takiego adresu.' });

    if (req.method !== 'GET' && req.method !== 'HEAD') return sendJSON(res, 405, { error: 'Niedozwolona metoda.' });
    if (pathname.startsWith('/outputs/')) {
      const file = safeJoin(OUTPUT_DIR, pathname.slice('/outputs/'.length));
      if (!file || !OUTPUT_EXTS.includes(path.extname(file).toLowerCase())) return sendJSON(res, 404, { error: 'Nie znaleziono.' });
      return serveFile(req, res, file);
    }
    const file = safeJoin(PUBLIC_DIR, pathname === '/' ? 'index.html' : pathname.slice(1));
    if (!file) return sendJSON(res, 404, { error: 'Nie znaleziono.' });
    return serveFile(req, res, file);
  } catch (err) {
    const e = err instanceof ApiError ? friendlyApiError(err) : err;
    if (e instanceof UserError) {
      console.warn(`[vardrobe] ${e.message}`);
      return sendJSON(res, e.status, { error: e.message });
    }
    console.error('[vardrobe]', err);
    return sendJSON(res, 500, { error: `Błąd serwera: ${err.message}` });
  }
});

server.listen(PORT, HOST, () => {
  const shown = HOST === '0.0.0.0' ? 'localhost' : HOST;
  console.log(`Vardrobe działa: http://${shown}:${PORT}`);
  console.log(`Model: ${MODEL}`);
  if (!API_KEY && !HF_TOKEN) console.log('Brak połączeń: otwórz aplikację w przeglądarce i kliknij „Połączenia”.');
  if (HF_TOKEN) {
    fetchHfUser(HF_TOKEN)
      .then((user) => {
        hfUser = user;
        console.log(`Hugging Face: ${user.name}${user.isPro ? ' (PRO)' : ''}`);
      })
      .catch((err) => console.warn(`Hugging Face: ${err.message}`));
  }
  gradio().catch(() => console.warn('Uwaga: brak biblioteki @gradio/client. Uruchom npm install, żeby używać Hugging Face.'));
});

// ---------------------------------------------------------------- .env

function loadEnv(file) {
  let text;
  try {
    text = fs.readFileSync(file, 'utf8');
  } catch {
    return;
  }
  for (const line of text.split(/\r?\n/)) {
    if (/^\s*#/.test(line)) continue;
    const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/);
    if (!m) continue;
    let value = m[2];
    if (/^(["']).*\1$/.test(value)) value = value.slice(1, -1);
    if (process.env[m[1]] === undefined) process.env[m[1]] = value;
  }
}